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/dev/shtanko/algorithms/leetcode/MinMovesToSeat.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.abs
/**
* 2037. Minimum Number of Moves to Seat Everyone
* @see <a href="https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/">Source</a>
*/
fun interface MinMovesToSeat {
operator fun invoke(seats: IntArray, students: IntArray): Int
}
class MinMovesToSeatBruteForce : MinMovesToSeat {
override operator fun invoke(seats: IntArray, students: IntArray): Int {
var moves = 0
seats.sort()
students.sort()
for (i in seats.indices) {
val seat = seats[i]
val student = students[i]
if (seat > student) {
moves += seat.minus(student)
} else if (student > seat) {
moves += student.minus(seat)
}
}
return moves
}
}
class MinMovesToSeatMath : MinMovesToSeat {
override operator fun invoke(seats: IntArray, students: IntArray): Int {
var moves = 0
seats.sort()
students.sort()
for (i in seats.indices) {
val seat = seats[i]
val student = students[i]
moves += abs(seat - student)
}
return moves
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,816 | kotlab | Apache License 2.0 |
src/Day03.kt | morris-j | 573,197,835 | false | {"Kotlin": 7085} | fun main() {
fun getRank(value: Char): Int {
if(value.isUpperCase()) {
return value.code - 64 + 26
}
return value.code - 96
}
fun findCommon(first: String, second: String): Char {
first.forEach {
if(second.contains(it)) {
return it
}
}
return 'a'
}
fun findCommonGroup(first: String, second: String, third: String): Char {
first.forEach {
if(second.contains(it) && third.contains(it)) {
return it
}
}
return 'a'
}
fun processInput(input: List<String>): List<Triple<String, String, Char>> {
return input.map {
val mid = it.length / 2
val first = it.substring(0, mid)
val second = it.substring(mid)
val common = findCommon(first, second)
Triple(first, second, common)
}
}
fun processInputGroup(input: List<String>): List<Char> {
return input.chunked(3).map {
findCommonGroup(it[0], it[1], it[2])
}
}
fun part1(input: List<String>): Int {
var sum = 0
val processedInput = processInput(input)
processedInput.forEach {
sum += getRank(it.third)
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
val processedInput = processInputGroup(input)
processedInput.forEach {
sum += getRank(it)
}
return sum
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e3f2d02dad432dbc1b15c9e0eefa7b35ace0e316 | 1,633 | kotlin-advent-of-code-2022 | Apache License 2.0 |
lib/src/main/kotlin/aoc/day05/Day05.kt | Denaun | 636,769,784 | false | null | package aoc.day05
data class Crate(val name: Char)
data class Step(val quantity: Int, val from: Int, val to: Int)
abstract class CrateMover {
fun execute(steps: List<Step>, initialStacks: List<List<Crate>>): List<List<Crate>> =
steps.fold(initialStacks) { stacks, step -> execute(step, stacks) }
abstract fun execute(step: Step, stacks: List<List<Crate>>): List<List<Crate>>
}
class CrateMover9000: CrateMover() {
override fun execute(step: Step, stacks: List<List<Crate>>): List<List<Crate>> {
return stacks.mapIndexed { index, stack ->
when (index) {
step.from -> stack.dropLast(step.quantity)
step.to -> stack + stacks[step.from].takeLast(step.quantity).asReversed()
else -> stack
}
}
}
}
class CrateMover9001: CrateMover() {
override fun execute(step: Step, stacks: List<List<Crate>>): List<List<Crate>> {
return stacks.mapIndexed { index, stack ->
when (index) {
step.from -> stack.dropLast(step.quantity)
step.to -> stack + stacks[step.from].takeLast(step.quantity)
else -> stack
}
}
}
}
fun part1(input: String): String {
val (initialStacks, steps) = parse(input)
val finalStacks = CrateMover9000().execute(steps, initialStacks)
return finalStacks.map { it.last().name }.joinToString("")
}
fun part2(input: String): String {
val (initialStacks, steps) = parse(input)
val finalStacks = CrateMover9001().execute(steps, initialStacks)
return finalStacks.map { it.last().name }.joinToString("")
} | 0 | Kotlin | 0 | 0 | 560f6e33f8ca46e631879297fadc0bc884ac5620 | 1,638 | aoc-2022 | Apache License 2.0 |
src/year2022/16/Day16.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`16`
import java.util.PriorityQueue
import readInput
/**
* With help of solution from
* https://github.com/LiquidFun/adventofcode
*
* (This task was really hard and I've couldn't manage to solve it by myself)
*/
data class State(
var remainingTime: RemainingTime,
var currentValve: Valve,
var elephantRemainingTime: RemainingTime? = null,
var elephantValve: Valve? = null,
var openedValves: Set<Valve> = setOf(),
var sumOfPressure: Pressure = Pressure(0),
) : Comparable<State> {
override fun compareTo(other: State) = compareValuesBy(this, other) { -it.sumOfPressure.amount }
}
@JvmInline
value class Valve(val title: String)
@JvmInline
value class RemainingTime(val time: Int) {
operator fun plus(second: RemainingTime): RemainingTime {
return RemainingTime(time + second.time)
}
operator fun plus(second: Int): RemainingTime {
return RemainingTime(time + second)
}
operator fun minus(second: RemainingTime): RemainingTime {
return RemainingTime(time - second.time)
}
operator fun minus(second: Int): RemainingTime {
return RemainingTime(time - second)
}
}
@JvmInline
value class Pressure(val amount: Int) {
operator fun plus(second: Pressure): Pressure {
return Pressure(amount + second.amount)
}
operator fun times(second: Int): Pressure {
return Pressure(amount * second)
}
}
/**
* @param inputNeighbours - initial map of Valve to its Neighbours
* @param inputFlows - initial map of Valve to it's pressure
* @param currentValve - [Valve] to calculate result to
* @param currentRemainingTime - [RemainingTime] on this current step
* @param visitedValves - set of already visited valves
*/
private fun createMapOfValvesToDistanceInTime(
inputNeighbours: Map<Valve, List<Valve>>,
inputFlows: Map<Valve, Pressure>,
currentValve: Valve,
currentRemainingTime: RemainingTime,
visitedValves: Set<Valve> = setOf()
): Map<Valve, RemainingTime> {
val resultValvesDistances = mutableMapOf<Valve, RemainingTime>()
/**
* Iterate only on not visited neighbours
*/
inputNeighbours[currentValve]!!.filter { it !in visitedValves }.forEach { neighborValve ->
/**
* If pressure for new valve is not empty - open it and spend 1 minute
*/
if (inputFlows[neighborValve]!! != Pressure(0)) {
resultValvesDistances[neighborValve] = currentRemainingTime + 1
}
/**
* Then find all neighbours for this valve
*/
createMapOfValvesToDistanceInTime(
inputNeighbours = inputNeighbours,
inputFlows = inputFlows,
currentValve = neighborValve,
currentRemainingTime = currentRemainingTime + 1,
visitedValves = visitedValves + setOf(currentValve)
)
/**
* Update result map with new data - where time is minimised
* (Less time means that to arrive we will select most optimal path)
*/
.forEach { (valve, distance) ->
resultValvesDistances[valve] = listOfNotNull(
distance, resultValvesDistances.getOrDefault(valve, null)
).minBy { it.time }
}
}
return resultValvesDistances
}
/**
* @param inputValveToDistancesMap is map of [Valve] for all distances to another valves
* @param inputFlowsMap is initial data of valves [Pressure]
*/
private fun solve(
inputValveToDistancesMap: Map<Valve, Map<Valve, RemainingTime>>,
inputFlowsMap: Map<Valve, Pressure>,
initialState: State
): Int {
val queue = PriorityQueue<State>().also { it.add(initialState) }
var resultBestPressureSummary = 0
val visitedListsOfValves: MutableMap<List<Valve>, Pressure> = mutableMapOf()
/**
* Iterate over each possible [State]
*/
while (queue.isNotEmpty()) {
var (time, currentValve, elephantTime, elephantValve, openedSet, flowValue) = queue.remove()
/**
* Update best pressure data with largest pressure
*/
resultBestPressureSummary = maxOf(resultBestPressureSummary, flowValue.amount)
/**
* Get sorted list of opened valves, currentValve, elephantValve
*/
val visitedList: List<Valve> =
(openedSet.toList() + listOfNotNull(currentValve, elephantValve)).sortedBy { it.title }
/**
* Optimisation - if it happens that current visited list is already in this map
* AND
* its cached pressure summary is more then current - just skip (it will not give us better result)
*/
if (visitedListsOfValves.getOrDefault(
visitedList, Pressure(-1)
).amount >= flowValue.amount
) continue
/**
* Cache pressure for current visited list
*/
visitedListsOfValves[visitedList] = flowValue
/**
* Check needed for part 2
* If elephantTime and valve is non null (it means we solve part 2) AND current remaining time less then when elephant help
* That means that we need to switch elephant and ourself (to try the same state but inversed)
*/
if (elephantTime != null && elephantValve != null && time.time < elephantTime.time) {
time = elephantTime.also { elephantTime = time }
currentValve = elephantValve.also { elephantValve = currentValve }
}
/**
* Iterate over all neighbours to distances
*/
inputValveToDistancesMap[currentValve]!!.forEach { (neighbor, dist) ->
/**
* Calculate newTime that is current State TIME - current distance to valve - 1
* 1 means that it takes 1 minute to open valve
*/
val newTime = time - dist - 1
/**
* Calculate sum pressure for current step (state)
* We calculate for whole state, not on each step
*/
val newFlow = flowValue + inputFlowsMap[neighbor]!! * newTime.time
/**
* Optimisation
* If new time is not negative: <0 means VOLCANO ERUPTION
* And current neighbour is still not opened (if it is opened, we throw away this result as useless/visited)
*/
if (newTime.time >= 0 && neighbor !in openedSet) {
/**
* Simply create new State to iterate over in parent cycle
*/
queue.add(
State(
remainingTime = newTime,
currentValve = neighbor,
elephantRemainingTime = elephantTime,
elephantValve = elephantValve,
/**
* This is because we opened this valve
*/
openedValves = openedSet + setOf(neighbor),
sumOfPressure = newFlow
)
)
}
}
}
return resultBestPressureSummary
}
fun main() {
/**
* Parse Input
*/
val input: List<List<String>> =
readInput("Day16").map { Regex("([A-Z]{2}|\\d+)").findAll(it).toList().map { it.value } }
/**
* Get map all neighbours info
*/
val initialNeighbours: Map<Valve, List<Valve>> =
input.associate { Valve(it[0]) to it.slice(2 until it.size).map { Valve(it) } }
/**
* Get map of all Pressure info
*/
val flows: Map<Valve, Pressure> = input.associate { Valve(it[0]) to Pressure(it[1].toInt()) }
/**
* Map each valve to all Distance info for other valves
*/
val nonZeroNeighbors: Map<Valve, Map<Valve, RemainingTime>> = input.associate {
val currentValve = Valve(it[0])
currentValve to createMapOfValvesToDistanceInTime(
inputNeighbours = initialNeighbours,
inputFlows = flows,
currentValve = currentValve,
currentRemainingTime = RemainingTime(0)
)
}
/**
* Solve First Part of Problem
*/
solve(
inputValveToDistancesMap = nonZeroNeighbors, inputFlowsMap = flows, initialState = State(
RemainingTime(30), Valve("AA")
)
).run(::println)
/**
* Solve second part of problem
*/
solve(
inputValveToDistancesMap = nonZeroNeighbors, inputFlowsMap = flows, initialState = State(
remainingTime = RemainingTime(26),
currentValve = Valve("AA"),
elephantRemainingTime = RemainingTime(26),
elephantValve = Valve("AA")
)
).run(::println)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 8,758 | KotlinAdventOfCode | Apache License 2.0 |
year2020/day06/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day06/part1/Year2020Day06Part1.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Day 6: Custom Customs ---
As your flight approaches the regional airport where you'll switch to a much larger plane, customs
declaration forms are distributed to the passengers.
The form asks a series of 26 yes-or-no questions marked a through z. All you need to do is identify
the questions for which anyone in your group answers "yes". Since your group is just you, this
doesn't take very long.
However, the person sitting next to you seems to be experiencing a language barrier and asks if you
can help. For each of the people in their group, you write down the questions for which they answer
"yes", one per line. For example:
abcx
abcy
abcz
In this group, there are 6 questions to which anyone answered "yes": a, b, c, x, y, and z.
(Duplicate answers to the same question don't count extra; each question counts at most once.)
Another group asks for your help, then another, and eventually you've collected answers from every
group on the plane (your puzzle input). Each group's answers are separated by a blank line, and
within each group, each person's answers are on a single line. For example:
abc
a
b
c
ab
ac
a
a
a
a
b
This list represents answers from five groups:
- The first group contains one person who answered "yes" to 3 questions: a, b, and c.
- The second group contains three people; combined, they answered "yes" to 3 questions: a, b, and c.
- The third group contains two people; combined, they answered "yes" to 3 questions: a, b, and c.
- The fourth group contains four people; combined, they answered "yes" to only 1 question, a.
- The last group contains one person who answered "yes" to only 1 question, b.
In this example, the sum of these counts is 3 + 3 + 3 + 1 + 1 = 11.
For each group, count the number of questions to which anyone answered "yes". What is the sum of
those counts?
*/
package com.curtislb.adventofcode.year2020.day06.part1
import com.curtislb.adventofcode.common.io.forEachSection
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2020, day 6, part 1.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
val file = inputPath.toFile()
var total = 0
file.forEachSection { lines ->
total += lines.fold(emptySet<Char>()) { answers, line -> answers + line.toSet() }.size
}
return total
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,463 | AdventOfCode | MIT License |
src/main/kotlin/day11/Day11.kt | vitalir2 | 572,865,549 | false | {"Kotlin": 89962} | package day11
import Challenge
import product
private typealias MonkeyId = Int
object Day11 : Challenge(11) {
override fun part1(input: List<String>): Any {
return solveDay(input, 20) { level -> level / 3 }
}
override fun part2(input: List<String>): Any {
return solveDay(input, 10000)
}
private fun solveDay(
input: List<String>,
rounds: Int,
onNewLevelCalculated: (worryLevel: Int) -> Int = { it },
): Long {
val monkeys = input
.map(String::trim)
.chunked(7) // length of one monkey input + line break
.map(::createMonkeyFromInput)
// we only need to know if item is divisible by some number,
// so we can keep them in the ring of integers modulo "product of the numbers which we need divide by"
val modulus = monkeys
.map(Monkey::divisibilityNumber)
.product()
val inspectItemsCount: MutableMap<MonkeyId, Long> = mutableMapOf()
repeat(rounds) {
executeRound(monkeys, modulus, onNewLevelCalculated) { monkeyId ->
val lastValue = inspectItemsCount[monkeyId] ?: 0
inspectItemsCount[monkeyId] = lastValue + 1
}
}
return inspectItemsCount
.values
.sortedDescending()
.take(2)
.product()
}
private fun createMonkeyFromInput(input: List<String>): Monkey {
val monkeyId = input[0]
.removePrefix("Monkey ")
.takeWhile(Char::isDigit)
.toInt()
val initItems = input[1]
.removePrefix("Starting items: ")
.split(", ")
.map(String::toInt)
val changeWorryLevel = input[2]
.removePrefix("Operation: new = ")
.let { operation ->
val (left, op, right) = operation.split(" ")
Monkey.Expression(
left = left.toOperand(),
operation = op.toOperation(),
right = right.toOperand(),
)
}
val divisibleBy = input[3]
.removePrefix("Test: divisible by ")
.toInt()
val ifDivisible = input[4]
.removePrefix("If true: throw to monkey ")
.toInt()
val ifNotDivisible = input[5]
.removePrefix("If false: throw to monkey ")
.toInt()
val divisibilityTest = Monkey.DivisibilityTest(
number = divisibleBy,
ifTrue = ifDivisible,
ifFalse = ifNotDivisible,
)
return Monkey(
id = monkeyId,
items = initItems.toMutableList(),
changeWorryLevel = changeWorryLevel,
divisibilityTest = divisibilityTest,
)
}
private fun String.toOperand(): Monkey.Expression.Operand {
return when (this) {
"old" -> Monkey.Expression.Operand.OldExpressionValue
else -> Monkey.Expression.Operand.Number(this.toInt())
}
}
private fun String.toOperation(): Monkey.Expression.Operation {
return when (this) {
"*" -> Monkey.Expression.Operation.MULTIPLICATION
"+" -> Monkey.Expression.Operation.ADDITION
else -> error("Invalid operation")
}
}
private fun executeRound(
monkeys: List<Monkey>,
modulus: Long,
transformLevel: (worryLevel: Int) -> Int,
onItemInspected: (monkeyId: MonkeyId) -> Unit,
) {
monkeys.forEach { it.inspectItems(monkeys, modulus, transformLevel, onItemInspected) }
}
private data class ThrownItem(
val worryLevel: Int,
val toMonkey: MonkeyId,
)
private class Monkey(
private val id: MonkeyId,
private val items: MutableList<Int>,
private val changeWorryLevel: Expression,
private val divisibilityTest: DivisibilityTest,
) {
val divisibilityNumber: Long
get() = divisibilityTest.number.toLong()
fun inspectItems(
monkeys: List<Monkey>,
modulus: Long,
transformLevel: (worryLevel: Int) -> Int,
onItemInspected: (monkeyId: MonkeyId) -> Unit,
) {
val thrownItems = mutableListOf<ThrownItem>()
for (item in items) {
onItemInspected(id)
val newWorryLevel = transformLevel((changeWorryLevel.execute(item) % modulus).toInt())
val newMonkeyOwner = divisibilityTest.test(newWorryLevel)
thrownItems += ThrownItem(
worryLevel = newWorryLevel,
toMonkey = newMonkeyOwner,
)
}
items.clear()
for (thrownItem in thrownItems) {
monkeys[thrownItem.toMonkey].items += thrownItem.worryLevel
}
}
class Expression(
private val left: Operand,
private val operation: Operation,
private val right: Operand,
) {
sealed interface Operand {
@JvmInline
value class Number(val number: Int) : Operand
object OldExpressionValue : Operand
}
enum class Operation {
ADDITION,
MULTIPLICATION,
}
fun execute(oldValue: Int): Long {
val leftValue = left.value(oldValue).toLong()
val rightValue = right.value(oldValue).toLong()
return when (operation) {
Operation.ADDITION -> leftValue + rightValue
Operation.MULTIPLICATION -> leftValue * rightValue
}
}
companion object {
private fun Operand.value(oldExpressionValue: Int): Int {
return when (this) {
is Operand.Number -> number
is Operand.OldExpressionValue -> oldExpressionValue
}
}
}
}
class DivisibilityTest(
val number: Int,
private val ifTrue: MonkeyId,
private val ifFalse: MonkeyId,
) {
fun test(worryLevel: Int): MonkeyId {
return if (worryLevel % number == 0) ifTrue else ifFalse
}
}
}
}
| 0 | Kotlin | 0 | 0 | ceffb6d4488d3a0e82a45cab3cbc559a2060d8e6 | 6,436 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2016/Day20.kt | tginsberg | 74,924,040 | false | null | /*
* Copyright (c) 2016 by <NAME>
*/
package com.ginsberg.advent2016
/**
* Advent of Code - Day 20: December 20, 2016
*
* From http://adventofcode.com/2016/day/20
*
*/
class Day20(val input: List<String>) {
val ipRanges = parseInput()
fun solvePart1(): Long =
ipRanges.first().last.inc()
fun solvePart2(upperBound: Long = 4294967295): Long =
upperBound.inc() - ipRanges.map { (it.last - it.first).inc() }.sum()
private fun parseInput(): List<LongRange> =
optimize(input
.map { it.split("-") }
.map { LongRange(it[0].toLong(), it[1].toLong()) }
.sortedBy { it.first }
)
private fun optimize(ranges: List<LongRange>): List<LongRange> =
ranges.drop(1).fold(ranges.take(1)) { carry, next ->
if (carry.last().combinesWith(next)) carry.dropLast(1).plusElement(carry.last().plus(next))
else carry.plusElement(next)
}
private fun LongRange.plus(other: LongRange): LongRange =
LongRange(Math.min(this.first, other.first), Math.max(this.last, other.last))
private fun LongRange.combinesWith(other: LongRange): Boolean =
other.first in this || this.last + 1 in other
}
| 0 | Kotlin | 0 | 3 | a486b60e1c0f76242b95dd37b51dfa1d50e6b321 | 1,233 | advent-2016-kotlin | MIT License |
2022/src/main/kotlin/day3_fast.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.split
object Day3Fast : Solution<List<String>>() {
override val name = "day3"
override val parser = Parser.lines
override fun part1(input: List<String>): Int {
var sum = 0
input.forEach { line ->
val (l, r) = line.split()
var lmask = 0L
var rmask = 0L
for (char in l.toCharArray()) {
lmask = lmask or (1L shl char.priority)
}
for (char in r.toCharArray()) {
rmask = rmask or (1L shl char.priority)
}
val priority = (lmask and rmask).countTrailingZeroBits()
sum += (priority + 1)
}
return sum
}
override fun part2(input: List<String>): Number {
var sum = 0
(input.indices step 3).forEach { i ->
var mask = 0L
var linemask = 0L
for (char in input[i].toCharArray()) { mask = mask or (1L shl char.priority) }
for (char in input[i + 1].toCharArray()) { linemask = linemask or (1L shl char.priority) }
mask = mask and linemask
linemask = 0
for (char in input[i + 2].toCharArray()) { linemask = linemask or (1L shl char.priority) }
mask = mask and linemask
sum += mask.countTrailingZeroBits() + 1
}
return sum
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,242 | aoc_kotlin | MIT License |
src/main/kotlin/days/Day04.kt | julia-kim | 569,976,303 | false | null | package days
import readInput
fun main() {
fun part1(input: List<String>): Int {
var assignmentPairs = 0
input.forEach {
// 2-4,6-8
val (first, second) = it.split(",").map { range ->
val (start, end) = range.split("-", limit = 2).map(String::toInt)
start..end
}
val combined = (first + second).distinct().sorted()
if (combined == first.toList() || combined == second.toList()) assignmentPairs++
}
return assignmentPairs
}
fun part2(input: List<String>): Int {
var overlappingPairs = 0
input.forEach {
val (first, second) = it.split(",").map { range ->
range.split("-").let { (a, b) -> a.toInt()..b.toInt() }
}
if (first.any { second.contains(it) }) overlappingPairs++
}
return overlappingPairs
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 1,123 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day05.kt | jmerle | 434,010,865 | false | {"Kotlin": 60581} | package com.jaspervanmerle.aoc2021.day
import kotlin.math.max
import kotlin.math.min
class Day05 : Day("4993", "21101") {
private data class Point(val x: Int, val y: Int)
private data class Line(val from: Point, val to: Point) {
val coordinates = if (from.x == to.x) {
val yFrom = min(from.y, to.y)
val yTo = max(from.y, to.y)
(yFrom..yTo).map { Point(from.x, it) }
} else {
val coords = mutableListOf<Point>()
val slope = (to.y - from.y) / (to.x - from.x)
val yIntercept = from.y - (slope * from.x)
val xFrom = min(from.x, to.x)
val xTo = max(from.x, to.x)
(xFrom..xTo).map { Point(it, slope * it + yIntercept) }
}
}
private val lines = input
.lines()
.flatMap { it.split(" -> ") }
.map {
val parts = it.split(",")
Point(parts[0].toInt(), parts[1].toInt())
}
.windowed(2, 2)
.map { Line(it[0], it[1]) }
override fun solvePartOne(): Any {
return getNumberOfOverlappingCoordinates { it.from.x == it.to.x || it.from.y == it.to.y }
}
override fun solvePartTwo(): Any {
return getNumberOfOverlappingCoordinates { true }
}
private fun getNumberOfOverlappingCoordinates(lineFilter: (line: Line) -> Boolean): Int {
return lines
.filter(lineFilter)
.flatMap { it.coordinates }
.groupBy { it }
.count { it.value.size > 1 }
}
}
| 0 | Kotlin | 0 | 0 | dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e | 1,544 | advent-of-code-2021 | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day5.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInput
object Day5 : Day {
override val input = Supplies.create()
override fun part1() = input.moveAll(false).print()
override fun part2() = input.moveAll(true).print()
data class Move(val items: Int, val from: Int, val to: Int)
data class Supplies(private val stacks: Map<Int, List<Char>>, private val moves: List<Move>) {
companion object {
fun create(): Supplies {
val (stacks, moves) = readInput(5)
.split("(?m)^\\s*$".toRegex())
.map { p -> p.trimEnd().lines().filter { it.isNotBlank() } }
return Supplies(
parseStacks(stacks),
parseMoves(moves)
)
}
private fun parseStacks(stackLines: List<String>): Map<Int, List<Char>> {
return stackLines.last()
.mapIndexedNotNull { i, c -> i.takeIf { c.isDigit() } }
.mapIndexed { idx, col -> idx to col }
.associate { (idx, col) ->
idx + 1 to
stackLines.dropLast(1)
.mapNotNull { l -> l.getOrNull(col) }
.filter { it.isLetter() }
.reversed()
}
}
private fun parseMoves(moveLines: List<String>): List<Move> {
return moveLines
.map { l ->
l.split(' ')
.mapNotNull { s -> s.trim().filter { it.isDigit() }.takeIf { it.isNotBlank() } }
.map { it.toInt() }
}
.map { (items, from, to) -> Move(items, from, to) }
}
}
fun moveAll(preserveOrder: Boolean) = copy(stacks = moves.fold(stacks) { a, c -> move(c, a, preserveOrder) })
fun print() = stacks.map { it.value.last() }.joinToString("")
private fun move(
move: Move,
stacks: Map<Int, List<Char>>,
preserveOrder: Boolean
): Map<Int, List<Char>> {
return stacks.mapValues { ArrayDeque(it.value) }.apply {
val from = getValue(move.from)
val stack = buildList {
repeat(move.items) { from.removeLast().also { if (preserveOrder) add(0, it) else add(it) } }
}
getValue(move.to).apply { addAll(stack) }
}
}
}
} | 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 2,674 | aoc2022 | MIT License |
src/Day09.kt | Kanialdo | 573,165,497 | false | {"Kotlin": 15615} | fun main() {
data class Pos(val x: Int, val y: Int)
fun part1(input: List<String>): Int {
var h = Pos(0, 0)
var t = Pos(0, 0)
val tail = mutableSetOf(t)
input.forEach {
val direction = it.split(" ").first()
val moves = it.split(" ").last().toInt()
repeat(moves) {
h = when (direction) {
"R" -> Pos(h.x + 1, h.y)
"L" -> Pos(h.x - 1, h.y)
"U" -> Pos(h.x, h.y + 1)
"D" -> Pos(h.x, h.y - 1)
else -> throw IllegalStateException("Unknown direction $direction")
}
t = when {
h.x == t.x + 2 -> Pos(t.x + 1, h.y)
h.x == t.x - 2 -> Pos(t.x - 1, h.y)
h.y == t.y + 2 -> Pos(h.x, t.y + 1)
h.y == t.y - 2 -> Pos(h.x, t.y - 1)
else -> t
}
tail.add(t)
}
}
return tail.size
}
fun part2(input: List<String>): Int {
return TODO()
}
val testInput = readInput("Day09_test")
check(part1(testInput), 13)
// check(part2(testInput), TODO)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 10a8550a0a85bd0a928970f8c7c5aafca2321a4b | 1,330 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | Daan-Gunnink | 572,614,830 | false | {"Kotlin": 8595} | class Day04 : AdventOfCode(2,4) {
private fun getSectors(data: String): List<List<Int>>{
return data.split(",").map {sectors ->
val splitSectors = sectors.split("-")
val range = IntRange(splitSectors[0].toInt(), splitSectors[1].toInt())
range.toList()
}
}
override fun part1(input: List<String>): Int {
val result = input.map{ data ->
val sectorRanges = getSectors(data)
val compare = sectorRanges[0].containsAll(sectorRanges[1]) || sectorRanges[1].containsAll(sectorRanges[0])
compare
}
return result.filter { it }.size
}
override fun part2(input: List<String>): Int {
val result = input.map{ data ->
val sectorRanges = getSectors(data)
val compare = sectorRanges[0].any { sectorRanges[1].contains(it) } || sectorRanges[1].any { sectorRanges[0].contains(it) }
compare
}
return result.filter { it }.size
}
}
| 0 | Kotlin | 0 | 0 | 15a89224f332faaed34fc2d000c00fbefe1a3c08 | 1,003 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2022/Day14.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 14 - Regolith Reservoir
* Problem Description: http://adventofcode.com/2022/day/14
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day14/
*/
package com.ginsberg.advent2022
class Day14(input: List<String>) {
private val cave: MutableSet<Point2D> = parseInput(input)
private val sandSource: Point2D = Point2D(500, 0)
private val maxY: Int = cave.maxOf { it.y }
fun solvePart1(): Int =
dropSand(maxY + 1)
fun solvePart2(): Int {
val minX: Int = cave.minOf { it.x }
val maxX: Int = cave.maxOf { it.x }
cave.addAll(Point2D(minX - maxY, maxY + 2).lineTo(Point2D(maxX + maxY, maxY + 2)))
return dropSand(maxY + 3) + 1
}
private fun dropSand(voidStartsAt: Int): Int {
var start = sandSource
var landed = 0
while (true) {
val next = listOf(start.down(), start.downLeft(), start.downRight()).firstOrNull { it !in cave }
start = when {
next == null && start == sandSource -> return landed
next == null -> {
cave.add(start)
landed += 1
sandSource
}
next.y == voidStartsAt -> return landed
else -> next
}
}
}
private fun Point2D.down(): Point2D = Point2D(x, y + 1)
private fun Point2D.downLeft(): Point2D = Point2D(x - 1, y + 1)
private fun Point2D.downRight(): Point2D = Point2D(x + 1, y + 1)
private fun parseInput(input: List<String>): MutableSet<Point2D> =
input.flatMap { row ->
row.split(" -> ")
.map { Point2D.of(it) }
.zipWithNext()
.flatMap { (from, to) ->
from.lineTo(to)
}
}.toMutableSet()
}
| 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 1,916 | advent-2022-kotlin | Apache License 2.0 |
src/Day09.kt | Venkat-juju | 572,834,602 | false | {"Kotlin": 27944} | import java.lang.Math.abs
fun main() {
fun isAdjacentPoint(firstPoint: Pair<Int, Int>, secondPoint: Pair<Int, Int>): Boolean {
val distanceRowWise = abs(secondPoint.first - firstPoint.first)
val distanceColumnWise = abs(secondPoint.second - firstPoint.second)
return (distanceRowWise == 1 && distanceColumnWise == 1) ||
(distanceRowWise == 1 && distanceColumnWise == 0) ||
(distanceColumnWise == 1 && distanceRowWise == 0) ||
(distanceRowWise == 0 && distanceColumnWise == 0)
}
fun getNewPositionAfterMove(currentPosition: Pair<Int, Int>, direction: String): Pair<Int, Int> {
return when(direction) {
"R" -> Pair(currentPosition.first + 1, currentPosition.second)
"L" -> Pair(currentPosition.first - 1, currentPosition.second)
"U" -> Pair(currentPosition.first, currentPosition.second - 1)
"D" -> Pair(currentPosition.first, currentPosition.second + 1)
else -> error("Invalid input")
}
}
fun getNewTailPositionToNearHeadPosition(tailPosition: Pair<Int, Int>, headPosition: Pair<Int, Int>): Pair<Int, Int> {
val isSameRow = (headPosition.second - tailPosition.second) == 0
val isSameColumn = (headPosition.first - tailPosition.first) == 0
if (isSameRow) {
return if (isAdjacentPoint(Pair(tailPosition.first+1, tailPosition.second), headPosition))
Pair(tailPosition.first+1, tailPosition.second)
else
Pair(tailPosition.first-1, tailPosition.second)
} else if (isSameColumn) {
return if(isAdjacentPoint(Pair(tailPosition.first, tailPosition.second-1), headPosition))
Pair(tailPosition.first, tailPosition.second-1)
else
Pair(tailPosition.first, tailPosition.second+1)
} else {
val isHeadIsDownToTheTailNode = headPosition.second - tailPosition.second > 0
val isHeadIsLeftToTheTailNode = headPosition.first - tailPosition.first < 0
return if (isHeadIsDownToTheTailNode) {
if(isHeadIsLeftToTheTailNode) {
Pair(tailPosition.first-1, tailPosition.second+1)
} else {
Pair(tailPosition.first+1, tailPosition.second+1)
}
} else {
if (isHeadIsLeftToTheTailNode) {
Pair(tailPosition.first-1, tailPosition.second-1)
} else {
Pair(tailPosition.first+1, tailPosition.second-1)
}
}
}
}
fun part1(inputs: List<String>): Int {
val travelledPoints = mutableSetOf<Pair<Int, Int>>()
var currentTailPosition = Pair(0, 0)
var currentHeadPosition = Pair(0, 0)
var previousHeadPosition = Pair(0, 0)
travelledPoints.add(currentTailPosition)
inputs.forEach { input ->
val (direction, steps) = input.split(" ")
repeat(steps.toInt()) {
currentHeadPosition = getNewPositionAfterMove(currentHeadPosition, direction)
if (!isAdjacentPoint(currentTailPosition, currentHeadPosition)) {
currentTailPosition = getNewTailPositionToNearHeadPosition(currentTailPosition, currentHeadPosition)
travelledPoints.add(currentTailPosition)
}
previousHeadPosition = currentHeadPosition
}
}
return travelledPoints.size
}
fun part2(inputs: List<String>): Int {
val travelledPoints = mutableSetOf<Pair<Int, Int>>()
var previousKnotPositions = mutableListOf<Pair<Int, Int>>().apply {
repeat(10) {
add(Pair(0,0))
}
}
var currentKnotPositions = mutableListOf<Pair<Int, Int>>().apply {
repeat(10) {
add(Pair(0,0))
}
}
travelledPoints.add(currentKnotPositions.first())
inputs.forEach { input ->
val (direction, numOfSteps) = input.split(" ")
// println("move $direction $numOfSteps times")
repeat(numOfSteps.toInt()) {
// println(direction)
currentKnotPositions[0] = getNewPositionAfterMove(currentKnotPositions[0], direction)
currentKnotPositions.forEachIndexed { index, knot ->
if (index < currentKnotPositions.size - 1 && !isAdjacentPoint(knot, currentKnotPositions[index + 1])) {
currentKnotPositions[index+1] = getNewTailPositionToNearHeadPosition(currentKnotPositions[index+1], knot)
}
}
// println(currentKnotPositions)
travelledPoints.add(currentKnotPositions.last())
previousKnotPositions.clear()
previousKnotPositions.addAll(currentKnotPositions)
}
// println(currentKnotPositions)
}
return travelledPoints.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
println(part1(testInput)) // 13 with test input 1
println(part2(testInput)) // 36 with test input 2
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
/**
* test input for part1
* R 4
* U 4
* L 3
* D 1
* R 4
* D 1
* L 5
* R 2
*/
/**
* test input for part2
* R 5
* U 8
* L 8
* D 3
* R 17
* D 10
* L 25
* U 20
*/
| 0 | Kotlin | 0 | 0 | 785a737b3dd0d2259ccdcc7de1bb705e302b298f | 5,569 | aoc-2022 | Apache License 2.0 |
src/Day21.kt | frungl | 573,598,286 | false | {"Kotlin": 86423} | data class Monkey(val left: String?, val operation: String?, val right: String?, var number: Long) {
init {
if (left == null || right == null || operation == null) {
require(left == null && right == null && operation == null)
}
}
val hasNumber: Boolean
get() = left == null && right == null && operation == null
}
fun main() {
fun applyOp(left: Long, right: Long, op: String): Long {
return when (op) {
"+" -> left + right
"-" -> left - right
"*" -> left * right
"/" -> left / right
else -> throw IllegalArgumentException("Unknown op $op")
}
}
fun dfs(graph: Map<String, Monkey>, monkeyName: String): Long {
val monkey = graph[monkeyName] ?: throw IllegalArgumentException("Unknown monkey $monkeyName")
if (monkey.hasNumber) {
return monkey.number
}
val left = dfs(graph, monkey.left ?: throw IllegalArgumentException("No left for $monkeyName"))
val right = dfs(graph, monkey.right ?: throw IllegalArgumentException("No right for $monkeyName"))
val result = applyOp(left, right, monkey.operation ?: throw IllegalArgumentException("No op for $monkeyName"))
monkey.number = result
return result
}
fun parse(input: List<String>): Map<String, Monkey> = input.map {
val name = it.substringBefore(":")
if ((it.toSet() intersect setOf('+', '-', '/', '*')).isNotEmpty()) {
val splited = it.substringAfter(": ").split(" ")
val left = splited[0]
val operation = splited[1]
val right = splited[2]
name to Monkey(left, operation, right, 0)
} else {
name to Monkey(null, null, null, it.substringAfter(": ").toLong())
}
}.toMap()
fun part1(input: List<String>): Long {
val tree = parse(input)
return dfs(tree, "root")
}
fun reverseOpLeft(op: String, right: Long, need: Long): Long {
return when (op) {
"+" -> need - right
"-" -> need + right
"*" -> need / right
"/" -> need * right
else -> throw IllegalArgumentException("Unknown op $op")
}
}
fun reverseOpRight(op: String, left: Long, need: Long): Long {
return when (op) {
"+" -> need - left
"-" -> left - need
"*" -> need / left
"/" -> left / need
else -> throw IllegalArgumentException("Unknown op $op")
}
}
fun goToHuman(tree: Map<String, Monkey>, monkeyName: String): String? {
if (monkeyName == "humn") {
return ""
}
val monkey = tree[monkeyName] ?: throw IllegalArgumentException("Unknown monkey $monkeyName")
if (monkey.hasNumber) {
return null
}
val left = goToHuman(tree, monkey.left ?: throw IllegalArgumentException("No left for $monkeyName"))
val right = goToHuman(tree, monkey.right ?: throw IllegalArgumentException("No right for $monkeyName"))
if (left != null) {
return "L$left"
} else if (right != null) {
return "R$right"
}
return null
}
fun part2(input: List<String>): Long {
val tree = parse(input)
dfs(tree, "root")
val path = goToHuman(tree, "root") ?: throw IllegalArgumentException("No path to human")
var monkeyName = "root"
var needValue = 0L
path.forEach { next ->
if (monkeyName == "humn") {
return@forEach
}
val monkey = tree[monkeyName] ?: throw IllegalArgumentException("Unknown monkey $monkeyName")
val op = monkey.operation ?: throw IllegalArgumentException("No op for $monkeyName")
val left = monkey.left ?: throw IllegalArgumentException("No left for $monkeyName")
val right = monkey.right ?: throw IllegalArgumentException("No right for $monkeyName")
val monkeyLeft = tree[left] ?: throw IllegalArgumentException("Unknown monkey $left")
val monkeyRight = tree[right] ?: throw IllegalArgumentException("Unknown monkey $right")
if (monkeyName == "root") {
needValue = if (next == 'L') {
monkeyRight.number
} else {
monkeyLeft.number
}
} else {
needValue = if (next == 'L') {
reverseOpLeft(op, monkeyRight.number, needValue)
} else {
reverseOpRight(op, monkeyLeft.number, needValue)
}
}
monkeyName = if (next == 'L') {
left
} else {
right
}
}
return needValue
}
val testInput = readInput("Day21_test")
check(part1(testInput) == 152L)
check(part2(testInput) == 301L)
val input = readInput("Day21")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d4cecfd5ee13de95f143407735e00c02baac7d5c | 5,075 | aoc2022 | Apache License 2.0 |
src/aoc2021/Day10.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2021
import readInput
import java.util.*
fun main() {
val (year, day) = "2021" to "Day10"
fun List<String>.toScores(corrupted: Boolean) = map { line ->
val stack = LinkedList<Char>()
line.forEach { c ->
when (c) {
')' -> {
val match = stack.pop()
if (match != '(') {
return@map if (corrupted) 3 else 0
}
}
']' -> {
val match = stack.pop()
if (match != '[') {
return@map if (corrupted) 57 else 0
}
}
'}' -> {
val match = stack.pop()
if (match != '{') {
return@map if (corrupted) 1197 else 0
}
}
'>' -> {
val match = stack.pop()
if (match != '<') {
return@map if (corrupted) 25137 else 0
}
}
else -> {
stack.push(c)
}
}
}
return@map if (corrupted) 0 else stack.map {
when (it) {
'(' -> 1L
'[' -> 2L
'{' -> 3L
else -> 4L
}
}.reduce { acc, i -> acc * 5L + i }
}
fun part1(input: List<String>) =
input.toScores(corrupted = true).sum()
fun part2(input: List<String>): Long {
val scores = input.toScores(corrupted = false)
.filter { it != 0L }
.sorted()
return scores[scores.size / 2]
}
val testInput = readInput(name = "${day}_test", year = year)
val input = readInput(name = day, year = year)
check(part1(testInput) == 26397L)
println(part1(input))
check(part2(testInput) == 288957L)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,986 | aoc-kotlin | Apache License 2.0 |
src/Day04.kt | sms-system | 572,903,655 | false | {"Kotlin": 4632} | fun main() {
fun prepareData (input: List<String>): List<String> = input
.map {
it.split(",").map {
it.split("-").map {
it.toInt()
}
}
}
fun part1(input: List<String>): Int = prepareData(input).filter {
it[0][0] <= it[1][0] && it[0][1] >= it[1][1] ||
it[1][0] <= it[0][0] && it[1][1] >= it[0][1]
}
.size
fun part2(input: List<String>): Int = prepareData(input).filter {
!(it[0][1] < it[1][0] || it[1][1] < it[0][0])
}
.size
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 266dd4e52f3b01912fbe2aa23d1ee70d1292827d | 774 | adventofcode-2022-kotlin | Apache License 2.0 |
15/src/main/kotlin/Cokies.kt | kopernic-pl | 109,750,709 | false | null | import Ingredient.IngredientProperty
import com.google.common.io.Resources
const val TEASPOONS_CAPACITY = 100
@Suppress("UnstableApiUsage")
fun main() {
val allIngredients: List<Ingredient> = Resources.getResource("input.txt")
.readText().lines()
.map(Ingredient.Companion::fromString)
val allSolutions = ReceiptGenerator.generate(TEASPOONS_CAPACITY, allIngredients.size)
val cookieScoringFunction = { receipt: List<Int> -> calcSingleReceiptScore(receipt, allIngredients) }
val noFiltering: (List<Int>) -> Boolean = { true }
val maxCookieByNonCalories =
CookiesCalculator.calcBestCookie(
allSolutions,
allIngredients,
noFiltering,
cookieScoringFunction,
maxScore()
)
println("Best cookie by non-calories is scored at $maxCookieByNonCalories")
val max500CaloriesCookieByNonCalories =
CookiesCalculator.calcBestCookie(
allSolutions, allIngredients, only500calories(allIngredients), cookieScoringFunction,
maxScore()
)
println("Best 500 calories cookie is scored at $max500CaloriesCookieByNonCalories")
}
private fun maxScore(): (List<Int>) -> Int = { it.maxOrNull()!! }
const val CALORIES_TARGET_500 = 500
private fun only500calories(allIngredients: List<Ingredient>): (List<Int>) -> Boolean = {
calcSingleReceiptCaloriesValue(it, allIngredients) == CALORIES_TARGET_500
}
private fun calcSingleReceiptScore(receipt: List<Int>, ingredients: List<Ingredient>): Int {
return getPropertyForIngredient(receipt, ingredients, IngredientProperty.CAPACITY) *
getPropertyForIngredient(receipt, ingredients, IngredientProperty.DURABILITY) *
getPropertyForIngredient(receipt, ingredients, IngredientProperty.FLAVOR) *
getPropertyForIngredient(receipt, ingredients, IngredientProperty.TEXTURE)
}
private fun calcSingleReceiptCaloriesValue(receipt: List<Int>, ingredients: List<Ingredient>): Int {
return getPropertyForIngredient(receipt, ingredients, IngredientProperty.CALORIES)
}
private fun getPropertyForIngredient(
receipt: List<Int>,
ingredients: List<Ingredient>,
property: IngredientProperty
): Int {
return receipt.zip(ingredients.map { it.getProperty(property) })
.map { (spoons, value) -> spoons * value }
.sum()
.coerceAtLeast(0)
}
object CookiesCalculator {
fun calcBestCookie(
allRecipes: Set<List<Int>>,
ingredients: List<Ingredient>,
solutionFilter: (List<Int>) -> Boolean,
cookieScoringFunction: (List<Int>) -> Int,
bestCookieSelector: (List<Int>) -> Int
): Int {
require(allRecipes.map { it.size }.all { it == ingredients.size }) { "All recipes must use all ingredients" }
require(allRecipes.isNotEmpty())
return allRecipes
.filter(solutionFilter)
.map(cookieScoringFunction)
.let(bestCookieSelector)
}
}
object ReceiptGenerator {
fun generate(teaspoonsCapacity: Int, numberOfIngredients: Int): Set<List<Int>> {
var result = setOf(List(numberOfIngredients) { 0 })
repeat(teaspoonsCapacity) { result = result.flatMap { addSpoonToSingleIngredient(it) }.toSet() }
return result
}
private fun addSpoonToSingleIngredient(solution: List<Int>): List<List<Int>> {
return solution.withIndex()
.map { (index, value) -> solution.toMutableList().apply { this[index] = value + 1 } }
}
}
| 0 | Kotlin | 0 | 0 | 06367f7e16c0db340c7bda8bc2ff991756e80e5b | 3,506 | aoc-2015-kotlin | The Unlicense |
src/main/kotlin/biz/koziolek/adventofcode/year2021/day22/day22.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2021.day22
import biz.koziolek.adventofcode.*
import kotlin.math.max
import kotlin.math.min
fun main() {
val inputFile = findInput(object {})
val lines = inputFile.bufferedReader().readLines()
val rebootSteps = parseReactorRebootSteps(lines)
val onCubes = executeRebootSteps(rebootSteps, min = -50, max = 50)
println("On cubes in -50..50: $onCubes")
val onCubesAll = executeRebootStepsV2(rebootSteps, min = Int.MIN_VALUE, max = Int.MAX_VALUE)
println("On cubes everywhere: $onCubesAll")
}
data class RebootStep(val turnOn: Boolean, val cuboid: Cuboid)
sealed interface ICuboid {
fun exclude(cuboid: ICuboid): ICuboid
fun getCubes(): Sequence<Coord3d>
fun intersects(other: ICuboid): Boolean
fun intersection(other: ICuboid): ICuboid
fun countContained(): Long
operator fun contains(coord3d: Coord3d): Boolean
}
object EmptyCuboid : ICuboid {
override fun exclude(cuboid: ICuboid) = EmptyCuboid
override fun getCubes() = emptySequence<Coord3d>()
override fun intersects(other: ICuboid) = false
override fun intersection(other: ICuboid) = EmptyCuboid
override fun countContained() = 0L
override fun contains(coord3d: Coord3d) = false
}
data class Cuboid(val from: Coord3d, val to: Coord3d, private val excluded: List<ICuboid> = emptyList()) : ICuboid {
override fun exclude(cuboid: ICuboid): Cuboid {
return when (val excludedIntersection = cuboid.intersection(this)) {
is Cuboid -> copy(excluded = excluded.map { it.exclude(excludedIntersection) } + excludedIntersection)
is EmptyCuboid -> this
}
}
override fun getCubes(): Sequence<Coord3d> =
(from.x..to.x).asSequence().flatMap { x ->
(from.y..to.y).asSequence().flatMap { y ->
(from.z..to.z).asSequence().map { z ->
Coord3d(x, y, z)
}
}
}.filter { coord -> excluded.none { it.contains(coord) } }
override fun intersects(other: ICuboid) =
when (other) {
is Cuboid ->
this.from.x <= other.to.x && other.from.x <= this.to.x
&& this.from.y <= other.to.y && other.from.y <= this.to.y
&& this.from.z <= other.to.z && other.from.z <= this.to.z
is EmptyCuboid -> false
}
override fun intersection(other: ICuboid): ICuboid =
if (intersects(other) && other is Cuboid) {
Cuboid(
from = Coord3d(
x = max(this.from.x, other.from.x),
y = max(this.from.y, other.from.y),
z = max(this.from.z, other.from.z),
),
to = Coord3d(
x = min(this.to.x, other.to.x),
y = min(this.to.y, other.to.y),
z = min(this.to.z, other.to.z),
),
)
} else {
EmptyCuboid
}
override fun countContained(): Long =
(to.x - from.x + 1L) * (to.y - from.y + 1L) * (to.z - from.z + 1L) - excluded.sumOf { it.countContained() }
override operator fun contains(coord3d: Coord3d) =
from.x <= coord3d.x && coord3d.x <= to.x
&& from.y <= coord3d.y && coord3d.y <= to.y
&& from.z <= coord3d.z && coord3d.z <= to.z
fun cutOut(other: Cuboid): Set<Cuboid> =
buildSet {
val xSplits = split(from.x, to.x, other.from.x, other.to.x)
val ySplits = split(from.y, to.y, other.from.y, other.to.y)
val zSplits = split(from.z, to.z, other.from.z, other.to.z)
for ((x1, x2) in xSplits) {
for ((y1, y2) in ySplits) {
for ((z1, z2) in zSplits) {
val cuboid = Cuboid(
from = Coord3d(x = x1, y = y1, z = z1),
to = Coord3d(x = x2, y = y2, z = z2),
)
if (!cuboid.intersects(other)) {
add(cuboid)
}
}
}
}
}
private fun split(start: Int, end: Int, cut1: Int, cut2: Int): List<Pair<Int, Int>> {
return buildList {
if (start < cut1 && cut2 < end) {
add(start to cut1 - 1)
add(cut1 to cut2)
add(cut2 + 1 to end)
} else if (start < cut1 && cut1 <= end) {
add(start to cut1 - 1)
add(cut1 to end)
} else if (start <= cut2 && cut2 < end) {
add(start to cut2)
add(cut2 + 1 to end)
} else {
add(start to end)
}
}
}
override fun toString(): String {
return toString(indent = 0)
}
fun toString(indent: Int = 0): String {
val separator = "\n" + " ".repeat(indent + 2)
return "${from.x},${from.y},${from.z} -> ${to.x},${to.y},${to.z}" +
excluded.joinToString(separator = separator, prefix = separator) {
when (it) {
is Cuboid -> it.toString(indent + 2)
else -> it.toString()
}
}
}
}
fun parseReactorRebootSteps(lines: List<String>): List<RebootStep> =
lines.map { line ->
Regex("(on|off) x=(-?[0-9]+)\\.\\.(-?[0-9]+),y=(-?[0-9]+)\\.\\.(-?[0-9]+),z=(-?[0-9]+)\\.\\.(-?[0-9]+)")
.find(line)
?.let { result ->
RebootStep(
turnOn = result.groupValues[1] == "on",
cuboid = Cuboid(
from = Coord3d(
x = result.groupValues[2].toInt(),
y = result.groupValues[4].toInt(),
z = result.groupValues[6].toInt(),
),
to = Coord3d(
x = result.groupValues[3].toInt(),
y = result.groupValues[5].toInt(),
z = result.groupValues[7].toInt(),
),
),
)
}
?: throw IllegalArgumentException("Could not parse reboot step: $line")
}
fun executeRebootSteps(rebootSteps: List<RebootStep>, min: Int, max: Int): Int {
val region = Cuboid(Coord3d(min, min, min), Coord3d(max, max, max))
return rebootSteps
.filter { region.intersects(it.cuboid) }
.fold(mutableMapOf<Coord3d, Boolean>()) { map, rebootStep ->
rebootStep.cuboid.getCubes()
.filter { region.contains(it) }
.fold(map) { map2, coord3d ->
map2[coord3d] = rebootStep.turnOn
map2
}
}
.count { it.value }
}
fun executeRebootStepsV2(rebootSteps: List<RebootStep>, min: Int, max: Int): Long {
val region = Cuboid(Coord3d(min, min, min), Coord3d(max, max, max))
return rebootSteps
.filter { region.intersects(it.cuboid) }
.fold(listOf<Cuboid>()) { list, rebootStep ->
if (rebootStep.turnOn) {
list.map { it.exclude(rebootStep.cuboid) } + rebootStep.cuboid
} else {
list.map { it.exclude(rebootStep.cuboid) }
}
}
.sumOf { it.countContained() }
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 7,501 | advent-of-code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinTaps.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 dev.shtanko.algorithms.E_9
import kotlin.math.max
import kotlin.math.min
/**
* 1326. Minimum Number of Taps to Open to Water a Garden
* @see <a href="https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden">Source</a>
*/
fun interface MinTaps {
operator fun invoke(n: Int, ranges: IntArray): Int
}
/**
* Approach 1: Dynamic Programming
*/
class MinTapsDP : MinTaps {
override operator fun invoke(n: Int, ranges: IntArray): Int {
// Create an array to store the minimum number of taps needed for each position
val dp = IntArray(n + 1) { E_9.toInt() }
// Initialize the starting position of the garden
dp[0] = 0
for (i in 0..n) {
// Calculate the leftmost position reachable by the current tap
val tapStart = max(0, i - ranges[i])
// Calculate the rightmost position reachable by the current tap
val tapEnd = min(n, i + ranges[i])
for (j in tapStart..tapEnd) {
// Update with the minimum number of taps
dp[tapEnd] = min(dp[tapEnd].toDouble(), (dp[j] + 1).toDouble()).toInt()
}
}
// Check if the garden can be watered completely
// Return the minimum number of taps needed to water the entire garden
return if (dp[n] == E_9.toInt()) {
// Garden cannot be watered
-1
} else {
dp[n]
}
}
}
/**
* Approach 2: Greedy
*/
class MinTapsGreedy : MinTaps {
override operator fun invoke(n: Int, ranges: IntArray): Int {
// Create an array to track the maximum reach for each position
val maxReach = IntArray(n + 1)
// Calculate the maximum reach for each tap
for (i in ranges.indices) {
// Calculate the leftmost position the tap can reach
val start = max(0, i - ranges[i])
// Calculate the rightmost position the tap can reach
val end = min(n, i + ranges[i])
// Update the maximum reach for the leftmost position
maxReach[start] = max(maxReach[start].toDouble(), end.toDouble()).toInt()
}
// Number of taps used
var taps = 0
// Current rightmost position reached
var currEnd = 0
// Next rightmost position that can be reached
var nextEnd = 0
// Iterate through the garden
for (i in 0..n) {
// Current position cannot be reached
if (i > nextEnd) {
return -1
}
// Increment taps when moving to a new tap
if (i > currEnd) {
taps++
// Move to the rightmost position that can be reached
currEnd = nextEnd
}
// Update the next rightmost position that can be reached
nextEnd = max(nextEnd.toDouble(), maxReach[i].toDouble()).toInt()
}
// Return the minimum number of taps used
return taps
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,673 | kotlab | Apache License 2.0 |
src/main/kotlin/wtf/log/xmas2021/day/day10/Day10.kt | damianw | 434,043,459 | false | {"Kotlin": 62890} | package wtf.log.xmas2021.day.day10
import wtf.log.xmas2021.Day
import java.io.BufferedReader
import java.util.*
object Day10 : Day<List<List<Token>>, Long, Long> {
override fun parseInput(reader: BufferedReader): List<List<Token>> = reader
.lineSequence()
.map { line ->
line.map(Token::match)
}
.toList()
override fun part1(input: List<List<Token>>): Long = input.sumOf { line ->
(parseTokens(line) as? ParseResult.Invalid)
?.firstIllegalTokenKind
?.syntaxErrorScore
?.toLong()
?: 0L
}
override fun part2(input: List<List<Token>>): Long = input
.map(::parseTokens)
.filterIsInstance<ParseResult.Incomplete>()
.map { (completion) ->
completion.fold(0L) { acc, token ->
(acc * 5) + token.kind.completionScore
}
}
.sorted().let { it[it.size / 2] }
private fun parseTokens(tokens: List<Token>): ParseResult {
val stack = ArrayDeque<Token.Kind>()
for (token in tokens) {
when (token.type) {
Token.Type.OPEN -> stack.addFirst(token.kind)
Token.Type.CLOSE -> {
val firstKind = stack.removeFirst()
if (firstKind != token.kind) {
return ParseResult.Invalid(token.kind)
}
}
}
}
if (stack.isEmpty()) {
return ParseResult.Complete
}
val completion = mutableListOf<Token>()
while (stack.isNotEmpty()) {
val first = stack.removeFirst()
completion += Token(Token.Type.CLOSE, first)
}
return ParseResult.Incomplete(completion)
}
private sealed class ParseResult {
data class Invalid(val firstIllegalTokenKind: Token.Kind) : ParseResult()
data class Incomplete(val completion: List<Token>) : ParseResult() {
init {
require(completion.isNotEmpty())
}
}
object Complete : ParseResult()
}
}
data class Token(
val type: Type,
val kind: Kind,
) {
enum class Type {
OPEN,
CLOSE,
;
}
enum class Kind(
val openingChar: Char,
val closingChar: Char,
val syntaxErrorScore: Int,
) {
PARENTHESES('(', ')', syntaxErrorScore = 3),
SQUARE_BRACKETS('[', ']', syntaxErrorScore = 57),
CURLY_BRACES('{', '}', syntaxErrorScore = 1197),
ANGLE_BRACKETS('<', '>', syntaxErrorScore = 25137),
;
val completionScore: Int
get() = ordinal + 1
}
companion object {
private val mapping: Map<Char, Token> = Kind
.values()
.flatMap { kind ->
listOf(
kind.openingChar to Token(Type.OPEN, kind),
kind.closingChar to Token(Type.CLOSE, kind),
)
}
.toMap()
fun match(char: Char): Token = mapping.getValue(char)
}
}
| 0 | Kotlin | 0 | 0 | 1c4c12546ea3de0e7298c2771dc93e578f11a9c6 | 3,107 | AdventOfKotlin2021 | BSD Source Code Attribution |
src/Day08.kt | OskarWalczak | 573,349,185 | false | {"Kotlin": 22486} | fun main() {
val treeMatrix: Array<IntArray> = Array(99){IntArray(99)}
val testMatrix: Array<IntArray> = Array(5){IntArray(5)}
fun readLinesToMatrix(lines: List<String>, matrix: Array<IntArray>){
lines.forEachIndexed { lineIndex, s ->
s.forEachIndexed { stringIndex, c ->
matrix[lineIndex][stringIndex] = c.digitToInt()
}
}
}
fun part1(matrix: Array<IntArray>): Int {
var numOfVisible = 0
fun checkVisibleLeft(i: Int, j: Int): Boolean{
for(j1 in 0 until j){
if(matrix[i][j1] >= matrix[i][j])
return false
}
return true
}
fun checkVisibleRight(i: Int, j: Int): Boolean{
for(j1 in j+1 .. matrix[i].lastIndex){
if(matrix[i][j1] >= matrix[i][j])
return false
}
return true
}
fun checkVisibleUp(i: Int, j: Int): Boolean{
for(i1 in 0 until i){
if(matrix[i1][j] >= matrix[i][j])
return false
}
return true
}
fun checkVisibleDown(i: Int, j: Int): Boolean{
for(i1 in i+1 .. matrix.lastIndex){
if(matrix[i1][j] >= matrix[i][j])
return false
}
return true
}
for(i in matrix.indices){
for(j in matrix[i].indices){
if(i == 0 || i == matrix.lastIndex || j == 0 || j == matrix[i].lastIndex) {
numOfVisible++
continue
}
if(checkVisibleLeft(i, j) || checkVisibleRight(i, j) || checkVisibleUp(i, j) || checkVisibleDown(i, j))
numOfVisible++
}
}
return numOfVisible
}
fun part2(matrix: Array<IntArray>): Int {
var maxScenicScore = 0
fun visibleTreesLeft(i: Int, j: Int): Int{
var numOfTrees = 0
for(j1 in j-1 downTo 0){
numOfTrees++
if(matrix[i][j1] >= matrix[i][j])
break
}
return numOfTrees
}
fun visibleTreesRight(i: Int, j: Int): Int{
var numOfTrees = 0
for(j1 in j+1 .. matrix[i].lastIndex){
numOfTrees++
if(matrix[i][j1] >= matrix[i][j])
break
}
return numOfTrees
}
fun visibleTreesUp(i: Int, j: Int): Int{
var numOfTrees = 0
for(i1 in i-1 downTo 0){
numOfTrees++
if(matrix[i1][j] >= matrix[i][j])
break
}
return numOfTrees
}
fun visibleTreesDown(i: Int, j: Int): Int{
var numOfTrees = 0
for(i1 in i+1 .. matrix.lastIndex){
numOfTrees++
if(matrix[i1][j] >= matrix[i][j])
break
}
return numOfTrees
}
for(i in 1 until matrix.lastIndex){
for(j in 1 until matrix[i].lastIndex){
val currentScenicScore = visibleTreesLeft(i, j) * visibleTreesRight(i, j) * visibleTreesUp(i, j) * visibleTreesDown(i, j)
if(currentScenicScore > maxScenicScore)
maxScenicScore = currentScenicScore
}
}
return maxScenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
readLinesToMatrix(testInput, testMatrix)
check(part1(testMatrix) == 21)
val input = readInput("Day08")
readLinesToMatrix(input, treeMatrix)
println(part1(treeMatrix))
println(part2(treeMatrix))
}
| 0 | Kotlin | 0 | 0 | d34138860184b616771159984eb741dc37461705 | 3,820 | AoC2022 | Apache License 2.0 |
src/Day03.kt | hadiamin | 572,509,248 | false | null | fun main() {
fun part1(input: List<String>): Int {
return input.map {
rucksack -> rucksack.substring(0, rucksack.length / 2) to rucksack.substring(rucksack.length / 2)
}
// .also { println(it) }
.flatMap { (first, second) -> first.toSet() intersect second.toSet() }
// .also {
// it.forEach { println(it.priority()) }
// }
.sumOf { it.priority }
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.also { println(it) }
.flatMap { (first, second, third) -> first.toSet() intersect second.toSet() intersect third.toSet() }
.sumOf { it.priority }
}
val input = readInput("Day03")
println(part2(input))
}
val Char.priority: Int
get(): Int {
return when (this) {
in 'a' .. 'z' -> this - 'a' + 1
in 'A' .. 'Z' -> this - 'A' + 27
else -> error("Check your input")
}
} | 0 | Kotlin | 0 | 0 | e63aea2a55b629b9ac3202cdab2a59b334fb7041 | 1,006 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/g1401_1500/s1473_paint_house_iii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1401_1500.s1473_paint_house_iii
// #Hard #Array #Dynamic_Programming #2023_06_13_Time_235_ms_(100.00%)_Space_38.5_MB_(63.64%)
class Solution {
private lateinit var prev: Array<IntArray>
private lateinit var curr: Array<IntArray>
private lateinit var mins: Array<IntArray>
fun minCost(houses: IntArray, cost: Array<IntArray>, m: Int, n: Int, target: Int): Int {
prev = Array(n) { IntArray(target) }
curr = Array(n) { IntArray(target) }
mins = Array(2) { IntArray(target) }
for (i in 0 until m) calculate(i, houses, cost, n, target)
var min = Int.MAX_VALUE
for (i in 0 until n) min = Math.min(min, curr[i][target - 1])
return if (min == Int.MAX_VALUE) -1 else min
}
private fun calculate(house: Int, houses: IntArray, cost: Array<IntArray>, n: Int, target: Int) {
swap()
calculateMins(n, target)
if (houses[house] > 0) costInPaintedHouse(house, houses, cost, target) else costNotPaintedHouse(
house,
cost,
target
)
}
private fun costInPaintedHouse(house: Int, houses: IntArray, cost: Array<IntArray>, target: Int) {
val color = houses[house] - 1
for (i in cost[house].indices) {
val group = Math.min(target - 1, house)
val newG = house == group
if (i == color) {
curr[i][0] = prev[i][0]
for (j in 1..group) {
curr[i][j] = if (mins[0][j - 1] == prev[i][j - 1]) mins[1][j - 1] else mins[0][j - 1]
curr[i][j] = if (newG && j == group) curr[i][j] else Math.min(curr[i][j], prev[i][j])
}
} else for (j in 0..group) curr[i][j] = Int.MAX_VALUE
}
}
private fun costNotPaintedHouse(house: Int, cost: Array<IntArray>, target: Int) {
for (i in cost[house].indices) {
val group = Math.min(target - 1, house)
val newG = house == group
curr[i][0] = if (prev[i][0] == Int.MAX_VALUE) prev[i][0] else prev[i][0] + cost[house][i]
for (j in 1..group) {
curr[i][j] = if (mins[0][j - 1] == prev[i][j - 1]) mins[1][j - 1] else mins[0][j - 1]
curr[i][j] = if (newG && j == group) curr[i][j] else Math.min(curr[i][j], prev[i][j])
curr[i][j] = if (curr[i][j] == Int.MAX_VALUE) Int.MAX_VALUE else curr[i][j] + cost[house][i]
}
}
}
private fun swap() {
val temp = prev
prev = curr
curr = temp
}
private fun calculateMins(n: Int, target: Int) {
for (i in 0 until target - 1) {
mins[0][i] = prev[0][i]
mins[1][i] = Int.MAX_VALUE
for (j in 1 until n) {
if (prev[j][i] <= mins[0][i]) {
mins[1][i] = mins[0][i]
mins[0][i] = prev[j][i]
} else if (prev[j][i] <= mins[1][i]) mins[1][i] = prev[j][i]
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,015 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/days/Day17.kt | sicruse | 315,469,617 | false | null | package days
class Day17 : Day(17) {
// 4D Array!!
// 3D Array?
// 2D Array?
class Matrix(private val space: List<List<List<List<Boolean>>>>, private val dimensions: Dimensions) {
enum class Dimensions {THREE, FOUR}
fun active(x: Int, y: Int, z: Int, w: Int): Boolean {
return if (x in xRange && y in yRange && z in zRange && w in wRange) space[w][z][y][x] else false
}
fun count(x: Int, y: Int, z: Int, w: Int): Int = if (active(x,y,z,w)) 1 else 0
fun activeNeighbors(x: Int, y: Int, z: Int, w: Int): Int {
val xBoxRange = (x-1)..(x+1)
val yBoxRange = (y-1)..(y+1)
val zBoxRange = (z-1)..(z+1)
val wBoxRange = if (dimensions == Dimensions.FOUR) (w-1)..(w+1) else 0..0
val values = xBoxRange.flatMap { xb -> yBoxRange.flatMap { yb -> zBoxRange.flatMap { zb -> wBoxRange.map { wb-> count(xb, yb, zb, wb) } } } }
return values.fold(0) { acc, v -> acc + v } - count(x,y,z,w)
}
// cycle is where the magic happens
fun cycle(previous: Matrix): Matrix {
// Every cycle will build a matrix two units larger in every dimension
val xNewRange = 0..previous.xRange.endInclusive + 2
val yNewRange = 0..previous.yRange.endInclusive + 2
val zNewRange = 0..previous.zRange.endInclusive + 2
val wNewRange = if (dimensions == Dimensions.FOUR) 0..previous.wRange.endInclusive + 2 else 0..0
val data = wNewRange.map { w ->
val wb = if (dimensions == Dimensions.FOUR) w - 1 else 0
zNewRange.map { z ->
yNewRange.map { y ->
xNewRange.map { x ->
val count = previous.activeNeighbors(x - 1, y - 1, z - 1, wb)
// If a cube is active and exactly 2 or 3 of its neighbors are also active, the cube remains active. Otherwise, the cube becomes inactive.
// If a cube is inactive but exactly 3 of its neighbors are active, the cube becomes active. Otherwise, the cube remains inactive.
if (previous.active(x - 1, y - 1, z - 1, wb))
count in 2..3
else
count == 3
}
}
}
}
return Matrix(data, dimensions)
}
// We will assume that x & y dimensions are represented by
// the first entry in each list
val xRange: IntRange
get() = 0 until space[0][0][0].size
val yRange: IntRange
get() = 0 until space[0][0].size
val zRange: IntRange
get() = 0 until space[0].size
val wRange: IntRange
get() = 0 until space.size
// Count all active cells
val totalActive: Int
get() =
xRange.flatMap { x -> yRange.flatMap { y -> zRange.flatMap { z -> wRange.map{ w -> count(x, y, z, w) } } } }
.fold(0) { acc, v -> acc + v }
// Helper for debug printing
fun to2DMap(z: Int, w: Int) : String =
space[w][z].map { row ->
buildString {
row.forEach { v -> if (v) append('#') else append('.') }
append("\n")
}
}.joinToString("")
companion object {
// take input and create 3D space representation
// (z, y, x)
fun from2DMap(data: List<String>, dimensions: Dimensions): Matrix {
return Matrix(listOf<List<List<List<Boolean>>>>(
listOf<List<List<Boolean>>>(
data.map { rowText ->
rowText.map { c -> c == '#' }
}
)), dimensions)
}
}
}
fun frames(dimensions: Matrix.Dimensions = Matrix.Dimensions.THREE): Sequence<Matrix> = sequence {
// The first frame in the sequence is loaded from file
var frame = Matrix.from2DMap(inputList, dimensions)
yield(frame)
while (true) {
frame = frame.cycle(frame)
yield(frame)
}
}
override fun partOne(): Any {
return frames(Matrix.Dimensions.THREE).elementAt(6).totalActive
}
override fun partTwo(): Any {
return frames(Matrix.Dimensions.FOUR).elementAt(6).totalActive
}
}
| 0 | Kotlin | 0 | 0 | 9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f | 4,521 | aoc-kotlin-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/sk/mkiss/algorithms/dynamic/BuyAndSellStock.kt | marek-kiss | 430,858,906 | false | {"Kotlin": 85343} | package sk.mkiss.algorithms.dynamic;
import kotlin.math.max
object BuyAndSellStock {
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
fun maxProfitFromOneDeal(prices: IntArray): Int {
require(prices.isNotEmpty())
require(prices.all { it >= 0 })
var maxProfit = 0
var maxSell = prices.last()
(prices.size - 2 downTo 0).forEach { i ->
maxProfit = max(maxProfit, maxSell - prices[i])
maxSell = max(maxSell, prices[i])
}
return maxProfit
}
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii
fun maxProfitFromMultipleDeals(prices: IntArray): Int {
require(prices.isNotEmpty())
require(prices.all { it >= 0 })
var totalProfit = 0
var buy = -1
var sell = -1
for (i in 0 .. prices.size-2) {
if (buy == -1) {
if (prices[i] < prices[i + 1]) {
buy = i
sell = i + 1
}
} else {
if (prices[i] < prices[i + 1]) {
sell = i + 1
} else if (prices[i] > prices[i + 1]) {
if (sell != -1) {
totalProfit += prices[sell] - prices[buy]
sell = -1
}
buy = i + 1
}
}
}
if(buy!=-1 && prices[buy]<prices.last()) {
totalProfit += prices.last() - prices[buy]
}
return totalProfit
}
} | 0 | Kotlin | 0 | 0 | 296cbd2e04a397597db223a5721b6c5722eb0c60 | 1,574 | algo-in-kotlin | MIT License |
src/main/kotlin/days/day22/Day22.kt | Stenz123 | 725,707,248 | false | {"Kotlin": 123279, "Shell": 862} | package days.day22
import days.Day
import java.util.*
class Day22: Day() {
override fun partOne(): Any {
val bricks = parseInput()
val brickCoordinateMap = mutableListOf<Coordinate>()
val queue: PriorityQueue<Brick> = PriorityQueue()
queue.addAll(bricks)
while (queue.isNotEmpty()) {
val current = queue.poll()
//println("$current ${current.lowestZ}")
while (current.checkIfCanFall(brickCoordinateMap)) {
current.moveDown()
}
brickCoordinateMap.addAll(current.getAllBrickCoordinates())
}
var result = 0
for (brick in bricks) {
val brickCoordinateMapWithBrickRemoved = brickCoordinateMap.toMutableList()
brickCoordinateMapWithBrickRemoved.removeAll (brick.getAllBrickCoordinates())
val bricksAbove = bricks.filter { it.lowestZ > brick.lowestZ && it != brick }.sortedBy { it.lowestZ }
var isValid = true
for (otherBrick in bricksAbove) {
if (otherBrick.checkIfCanFall(brickCoordinateMapWithBrickRemoved)) {
isValid = false
break
}
}
if (isValid) result++
}
return result
}
override fun partTwo(): Any {
val bricks = parseInput()
val brickCoordinateMap = mutableListOf<Coordinate>()
val queue: PriorityQueue<Brick> = PriorityQueue()
queue.addAll(bricks)
while (queue.isNotEmpty()) {
val current = queue.poll()
//println("$current ${current.lowestZ}")
while (current.checkIfCanFall(brickCoordinateMap)) {
current.moveDown()
}
brickCoordinateMap.addAll(current.getAllBrickCoordinates())
}
var result = 0
for (brick in bricks.reversed()) {
val brickCoordinateMapWithBrickRemoved = brickCoordinateMap.toMutableList()
brickCoordinateMapWithBrickRemoved.removeAll (brick.getAllBrickCoordinates())
val bricksAbove = bricks.filter { it.lowestZ > brick.lowestZ && it != brick }.sortedBy { it.lowestZ }
for (otherBrick in bricksAbove) {
if (otherBrick.checkIfCanFall(brickCoordinateMapWithBrickRemoved)) {
brickCoordinateMapWithBrickRemoved.removeAll(otherBrick.getAllBrickCoordinates())
result++
}
}
}
return result
}
fun parseInput():List<Brick>{
return readInput().map {
val split = it.split(("~"))
val coordinates = split.map {
val coSplit = it.split(",").map { it.toInt() }
Coordinate(coSplit[0], coSplit[1], coSplit[2])
}
Brick(coordinates[0], coordinates[1])
}
}
}
class Brick(val start: Coordinate, val end: Coordinate):Comparable<Brick>{
val lowestZ get() = if (start.z > end.z) end.z else start.z
fun checkIfCanFall(map: List<Coordinate>):Boolean {
if (this.lowestZ == 1) return false
val res = !getAllBrickCoordinates().any {
val down = it.down()
if (!getAllBrickCoordinates().contains(down)) {
map.contains(it.down())
} else {
false
}
}
return res
}
fun getAllBrickCoordinates(): List<Coordinate> {
if (this.start == this.end) return listOf(this.start)
val res = mutableListOf<Coordinate>()
if (start.x - end.x != 0) {
val xRange = if (start.x < end.x) start.x .. end.x else end.x .. start.x
for (newX in xRange) { res.add(Coordinate(newX,start.y,start.z)) }
}else if (start.y - end.y != 0) {
val yRange = if (start.y < end.y) start.y .. end.y else end.y .. start.y
for (newY in yRange) { res.add(Coordinate(start.x,newY,start.z)) }
}else if (start.z - end.z != 0) {
val zRange = if (start.z < end.z) start.z .. end.z else end.z .. start.z
for (newZ in zRange) { res.add(Coordinate(start.x, start.y, newZ)) }
}
return res
}
fun moveDown() {
this.start.z--
this.end.z--
}
override fun compareTo(other: Brick): Int {
var res = this.lowestZ.compareTo(other.lowestZ)
return res
}
override fun toString(): String {
return "($start ~ $end)"
}
}
class Coordinate(val x: Int, val y: Int, var z: Int) {
fun down(): Coordinate {
return Coordinate(x,y,z-1)
}
override fun toString(): String {
return "($x, $y, $z)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Coordinate
if (x != other.x) return false
if (y != other.y) return false
if (z != other.z) return false
return true
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
result = 31 * result + z
return result
}
} | 0 | Kotlin | 1 | 0 | 3de47ec31c5241947d38400d0a4d40c681c197be | 5,175 | advent-of-code_2023 | The Unlicense |
src/main/kotlin/Day04.kt | arosenf | 726,114,493 | false | {"Kotlin": 40487} | import java.math.BigDecimal
import kotlin.system.exitProcess
fun main(args: Array<String>) {
if (args.isEmpty() or (args.size < 2)) {
println("Scratchcard not specified")
exitProcess(1)
}
val fileName = args.first()
println("Reading $fileName")
val lines = readLines(fileName)
val result =
if (args[1] == "part1") {
Day04().countPoints(lines)
} else {
Day04().countPoints2(lines)
}
println("Result: $result")
}
class Day04 {
private val delimiter = "\\s+".toRegex()
fun countPoints(lines: Sequence<String>): Int {
return lines
.map(::parseGame)
.map(::countHits)
.map(::score)
.sum()
}
fun countPoints2(lines: Sequence<String>): Int {
var result = 0
val games = lines
.map(::parseGame)
.toList()
result += games.size
var copies = games
.flatMap { copies(it, games) }
while (copies.isNotEmpty()) {
result += copies.size
copies = copies.flatMap { copies(it, games) }
}
return result
}
private fun parseGame(line: String): Game {
val gameNumber = line
.substringBefore(':')
.partition { c -> c.isDigit() }
.first
.toInt()
val winningNumbers = line.substringAfter(':')
.trim()
.substringBefore('|')
.trim()
.splitToSequence(delimiter)
.map(String::toInt)
.toList()
val actualNumbers = line.substringAfter('|')
.trim()
.splitToSequence(delimiter)
.map(String::toInt)
.toList()
return Game(gameNumber, winningNumbers, actualNumbers)
}
private fun countHits(game: Game): Int {
return game.winningNumbers.intersect(game.actualNumbers).size
}
private fun score(hitCount: Int): Int {
return if (hitCount < 1) {
0
} else {
BigDecimal.valueOf(2).pow(hitCount - 1).toInt()
}
}
private fun copies(game: Game, games: List<Game>): List<Game> {
val hits = countHits(game)
return if (hits < 1) {
listOf()
} else {
games.subList(game.gameNumber, game.gameNumber + hits)
}
}
data class Game(val gameNumber: Int, val winningNumbers: List<Int>, val actualNumbers: List<Int>)
}
| 0 | Kotlin | 0 | 0 | d9ce83ee89db7081cf7c14bcad09e1348d9059cb | 2,503 | adventofcode2023 | MIT License |
src/Day03.kt | sjgoebel | 573,578,579 | false | {"Kotlin": 21782} | fun main() {
fun part1(input: List<String>): Int {
var priorities = 0
for (line in input) {
val first = line.substring(0 until line.length/2)
//println(first)
val second = line.substring(line.length/2 until line.length)
//println(second)
for (char in first) {
if (char in second) {
//println(char)
priorities += if (char.isLowerCase()) {
char.minus('a') + 1
} else {
char.minus('A') + 27
//println(char.minus('A') + 27)
}
break
//println(priorities)
}
}
//println(priorities)
}
//print(priorities)
return priorities
}
fun part2(input: List<String>): Int {
var priorities = 0
for (index in input.indices step 3) {
for (char in input[index]) {
if (char in input[index + 1] && char in input[index + 2]) {
priorities += if (char.isLowerCase()) {
char.minus('a') + 1
} else {
char.minus('A') + 27
}
break
}
}
}
//println(priorities)
return priorities
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ae1588dbbb923dbcd4d19fd1495ec4ebe8f2593e | 1,779 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/day7/Code.kt | fcolasuonno | 221,697,249 | false | null | package day7
import java.io.File
fun main() {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed)}")
println("Part 2 = ${part2(parsed)}")
}
fun parse(input: List<String>) = input.requireNoNulls()
private fun String.isABBA() = windowed(4).any {
it[0] == it[3] && it[1] == it[2] && it[0] != it[1]
}
fun part1(input: List<String>): Any? = input.count {
val (supernet, hyper) = it.split("""[\[\]]""".toRegex())
.withIndex().partition { it.index % 2 == 0 }
supernet.any { it.value.isABBA() } && hyper.none { it.value.isABBA() }
}
fun part2(input: List<String>): Any? = input.count {
val (supernet, hyper) = it.split("""[\[\]]""".toRegex())
.withIndex().partition { it.index % 2 == 0 }
val abas = supernet.flatMap { it.value.windowed(3).filter { it[0] == it[2] && it[0] != it[1] } }
val babs = hyper.flatMap { it.value.windowed(3).filter { it[0] == it[2] && it[0] != it[1] } }
abas.any { "${it[1]}${it[0]}${it[1]}" in babs }
}
| 0 | Kotlin | 0 | 0 | 73110eb4b40f474e91e53a1569b9a24455984900 | 1,152 | AOC2016 | MIT License |
leetcode2/src/leetcode/ValidPalindrome.kt | hewking | 68,515,222 | false | null | package leetcode
/**
* 125. 验证回文串
* https://leetcode-cn.com/problems/valid-palindrome/
* Created by test
* Date 2019/6/7 0:45
* Description
* 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object ValidPalindrome {
@JvmStatic
fun main(args : Array<String>) {
// Solution().isPalindrome("A man, a plan, a canal: Panama")
// println(Solution().isPalindrome(".a"))
println(Solution().isPalindrome("0P"))
}
class Solution {
fun isPalindrome(s: String): Boolean {
if (s.isEmpty()) return true
var l = 0
var r = s.length - 1
while (l in 0..(r - 1)) {
while (l in 0..(r - 1) && !valid(s[l])) {
l ++
}
while (l in 0..(r - 1) && !valid(s[r])) {
r --
}
if (s[l].toUpperCase() != s[r].toUpperCase()) {
return false
}
l++
r--
}
return true
}
fun valid(ch : Char) : Boolean{
return ch in 'a'..'z' || ch in 'A'..'Z' || ch in '0' .. '9'
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,653 | leetcode | MIT License |
advent_of_code/2018/solutions/day_10_b.kt | migafgarcia | 63,630,233 | false | {"C++": 121354, "Kotlin": 38202, "C": 34840, "Java": 23043, "C#": 10596, "Python": 8343} | import java.io.File
import java.lang.Math.abs
data class Point(var position: Pair<Int, Int>, val velocity: Pair<Int, Int>)
fun main(args: Array<String>) {
val regex = Regex("position=<([- \\d]+),([- \\d]+)> velocity=<([- \\d]+),([- \\d]+)>")
val points = ArrayList<Point>(400)
File(args[0]).forEachLine{ line ->
val results = regex.find(line)!!.groupValues
val x = results[1].trim().toInt()
val y = results[2].trim().toInt()
points.add(Point(Pair(x, y), Pair(results[3].trim().toInt(), results[4].trim().toInt())))
}
var lastDistance = Long.MAX_VALUE
for(time in generateSequence(0) { it + 1 }) {
val d = points.map { (position) ->
points.map { (position1) -> manhattanDistance(position, position1)}.sum()
}.sum()
if(d > lastDistance) {
points.forEach { it.position = Pair(it.position.first - it.velocity.first, it.position.second - it.velocity.second) }
printPoints(points)
break
}
lastDistance = d
points.forEach { it.position = Pair(it.position.first + it.velocity.first, it.position.second + it.velocity.second) }
}
}
private fun printPoints(points: ArrayList<Point>) {
val xMin = points.minBy { it.position.first }!!.position.first
val yMin = points.minBy { it.position.second }!!.position.second
val xMax = points.maxBy { it.position.first }!!.position.first
val yMax = points.maxBy { it.position.second }!!.position.second
val xSize = xMax - xMin + 1
val ySize = yMax - yMin + 1
val matrix = Array(xSize) { BooleanArray(ySize) }
points.forEach { p ->
matrix[p.position.first - xMin][p.position.second - yMin] = true
}
for (y in yMin..yMax) {
for (x in xMin..xMax) {
if (matrix[x - xMin][y - yMin])
print('#')
else
print(' ')
}
println()
}
}
fun manhattanDistance(p1: Pair<Int, Int>, p2: Pair<Int, Int>): Long = (abs(p1.first - p2.first) + abs(p1.second - p2.second)).toLong() | 0 | C++ | 3 | 9 | 82f5e482c0c3c03fd39e46aa70cab79391ed2dc5 | 2,099 | programming-challenges | MIT License |
src/Day01.kt | kerchen | 573,125,453 | false | {"Kotlin": 137233} | fun main() {
fun part1(input: List<String>): Int {
var max_calories = 0
var sum_calories = 0
var elf = 0
for (calories in input) {
val c: Int = try { calories.toInt() } catch (e:NumberFormatException) { 0 }
if (c != 0) {
sum_calories += c
} else {
if (sum_calories > max_calories) {
max_calories = sum_calories
}
sum_calories = 0
elf += 1
}
}
return max_calories
}
fun part2(input: List<String>): Int {
val elf_calories = mutableListOf<Int>()
var elf = 0
elf_calories.add(0)
for (calories in input) {
val c: Int = try { calories.toInt() } catch (e:NumberFormatException) { 0 }
if (c != 0) {
elf_calories[elf] += c
} else {
elf_calories.add(0)
elf += 1
}
}
val sorted_elf_calories = elf_calories.sortedDescending()
return sorted_elf_calories[0] + sorted_elf_calories[1] + sorted_elf_calories[2]
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dc15640ff29ec5f9dceb4046adaf860af892c1a9 | 1,411 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2022/Day08.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2022
import net.voldrich.BaseDay
// https://adventofcode.com/2022/day/7
fun main() {
Day08().run()
}
class Day08 : BaseDay() {
override fun task1() : Int {
return countVisibleTrees(input.lines().filter { it.isNotBlank() })
}
override fun task2() : Int {
return countViewIndex(input.lines().filter { it.isNotBlank() })
}
fun countViewIndex(grid: List<String>): Int {
val size = grid.size
val indexes = Array(size) { IntArray(size) { 0 } }
val maxIndex = size - 1
for (i in 1 until maxIndex) {
for (j in 1 until maxIndex) {
indexes[i][j] = calculateScenicIndex(grid, i, j)
}
}
return indexes.maxOf { it.max() }
}
fun calculateScenicIndex(grid: List<String>, row: Int, col: Int) : Int {
val height = grid[row][col]
var scoreLeft = 0
for (j in col-1 downTo 0) {
scoreLeft +=1
if (grid[row][j] >= height) {
break
}
}
var scoreRight = 0
for (j in col+1 until grid.size) {
scoreRight +=1
if (grid[row][j] >= height) {
break
}
}
var scoreUp = 0
for (i in row-1 downTo 0) {
scoreUp +=1
if (grid[i][col] >= height) {
break
}
}
var scoreDown = 0
for (i in row + 1 until grid.size) {
scoreDown +=1
if (grid[i][col] >= height) {
break
}
}
return scoreLeft * scoreRight * scoreUp * scoreDown
}
fun countVisibleTrees(grid: List<String>): Int {
val size = grid.size
val maxIndex = size - 1
val visible = Array(size) { IntArray(size) { 0 } }
// Count all edge trees
for (i in 0 until size) {
for (j in 0 until size) {
if (i == 0 || i == maxIndex || j == 0 || j == maxIndex) {
visible[i][j] = 1
}
}
}
// Check each row
for (i in 1 until maxIndex) {
var maxLeft = grid[i][0]
var maxRight = grid[i][maxIndex]
for (j in 1 until maxIndex) {
// From left to right
if (grid[i][j] > maxLeft) {
maxLeft = grid[i][j]
visible[i][j] = 1
}
// From right to left
if (grid[i][maxIndex - j] > maxRight) {
maxRight = grid[i][maxIndex - j]
visible[i][maxIndex - j] = 1
}
}
}
// Check each column
for (j in 1 until maxIndex) {
var maxTop = grid[0][j]
var maxBottom = grid[maxIndex][j]
for (i in 1 until maxIndex) {
// From top to bottom
if (grid[i][j] > maxTop) {
maxTop = grid[i][j]
visible[i][j] = 1
}
// From bottom to top
if (grid[maxIndex - i][j] > maxBottom) {
maxBottom = grid[maxIndex - i][j]
visible[maxIndex - i][j] = 1
}
}
}
return visible.sumOf { it.sumOf { it } }
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 3,385 | advent-of-code | Apache License 2.0 |
problems/2020adventofcode17b/submissions/accepted/Stefan.kt | stoman | 47,287,900 | false | {"C": 169266, "C++": 142801, "Kotlin": 115106, "Python": 76047, "Java": 68331, "Go": 46428, "TeX": 27545, "Shell": 3428, "Starlark": 2165, "Makefile": 1582, "SWIG": 722} | import java.util.*
const val cycles = 6
fun main() {
val s = Scanner(System.`in`)
val input = mutableListOf<List<Boolean>>()
while (s.hasNext()) {
input.add(s.next().map { it == '#' })
}
var map = List(1 + 2 * cycles) {
List(1 + 2 * cycles) {
List(input.size + 2 * cycles) {
MutableList(input[0].size + 2 * cycles) { false }
}
}
}
for (i in input.indices) {
for (j in input[i].indices) {
map[cycles][cycles][i + cycles][j + cycles] = input[i][j]
}
}
for (i in 1..cycles) {
val newMap =
List(map.size) { List(map[0].size) { List(map[0][0].size) { MutableList(map[0][0][0].size) { false } } } }
for (a in map.indices) {
for (b in map[a].indices) {
for (c in map[a][b].indices) {
for (d in map[a][b][c].indices) {
var neighbors = if (map[a][b][c][d]) -1 else 0
for (x in -1..1) {
for (y in -1..1) {
for (z in -1..1) {
for (q in -1..1) {
if (a + x in map.indices
&& b + y in map[a + x].indices
&& c + z in map[a + x][b + y].indices
&& d + q in map[a + x][b + y][c + z].indices
&& map[a + x][b + y][c + z][d + q]) {
neighbors++
}
}
}
}
}
newMap[a][b][c][d] = (map[a][b][c][d] && neighbors in setOf(2, 3)) || (!map[a][b][c][d] && neighbors == 3)
}
}
}
}
map = newMap
}
println(map.flatten().flatten().flatten().count { it })
}
| 0 | C | 1 | 3 | ee214c95c1dc1d5e9510052ae425d2b19bf8e2d9 | 1,658 | CompetitiveProgramming | MIT License |
src/day2/Day2.kt | pocmo | 433,766,909 | false | {"Kotlin": 134886} | package day2
import java.io.File
sealed interface Command {
data class Forward(
val steps: Int
): Command
data class Down(
val steps: Int
) : Command
data class Up(
val steps: Int
) : Command
}
fun readCourse(): List<Command> {
val lines = File("day2.txt").readLines()
return lines.map { line ->
val (command, steps) = line.split(" ").let { raw ->
Pair(raw[0], raw[1].toInt())
}
when (command) {
"forward" -> Command.Forward(steps)
"down" -> Command.Down(steps)
"up" -> Command.Up(steps)
else -> throw IllegalStateException("Unknown command: $command")
}
}
}
class Submarine {
var horizontalPosition = 0
private set
var depth = 0
private set
var aim = 0
private set
fun process(course: List<Command>) {
course.forEach { command ->
when (command) {
is Command.Forward -> horizontalPosition += command.steps
is Command.Up -> depth -= command.steps
is Command.Down -> depth += command.steps
}
}
}
fun processNew(course: List<Command>) {
course.forEach { command ->
when (command) {
is Command.Forward -> {
horizontalPosition += command.steps
depth += aim * command.steps
}
is Command.Up -> {
aim -= command.steps
}
is Command.Down -> {
aim += command.steps
}
}
}
}
fun getSolution(): Int {
return horizontalPosition * depth
}
}
fun part1() {
val course = readCourse()
println("Size: " + course.size)
val submarine = Submarine()
submarine.process(course)
println("Position: " + submarine.horizontalPosition)
println("Depth: " + submarine.depth)
println(submarine.getSolution())
}
fun part2() {
val course = readCourse()
println("Size: " + course.size)
val submarine = Submarine()
submarine.processNew(course)
println("Position: " + submarine.horizontalPosition)
println("Depth: " + submarine.depth)
println("Aim: " + submarine.aim)
println("Solution: " + submarine.getSolution())
}
fun main() {
part2()
} | 0 | Kotlin | 1 | 2 | 73bbb6a41229e5863e52388a19108041339a864e | 2,408 | AdventOfCode2021 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MajorityElement.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.Random
/**
* 169. Majority Element
* @see <a href="https://leetcode.com/problems/majority-element">Source</a>
*/
fun interface MajorityElement {
operator fun invoke(nums: IntArray): Int
}
class MajorityElementHashTable : MajorityElement {
override fun invoke(nums: IntArray): Int {
val counter = HashMap<Int, Int>()
for (num in nums) {
val count = counter.getOrDefault(num, 0) + 1
counter[num] = count
if (count > nums.size / 2) {
return num
}
}
return 0
}
}
class MajorityElementSorting : MajorityElement {
override fun invoke(nums: IntArray) = nums.takeIf { it.isNotEmpty() }?.sorted()?.get(nums.size / 2) ?: 0
}
class MajorityElementRandomization : MajorityElement {
override fun invoke(nums: IntArray): Int {
val n = nums.size
if (n == 0) return 0
val random = Random()
var candidate: Int
var counter: Int
while (true) {
candidate = nums[random.nextInt(n)]
counter = 0
for (num in nums) {
if (num == candidate) {
counter++
}
}
if (counter > n / 2) {
return candidate
}
}
}
}
class MajorityElementDivideAndConquer : MajorityElement {
override fun invoke(nums: IntArray): Int {
if (nums.isEmpty()) {
return 0
}
return majority(nums.toList(), 0, nums.size - 1)
}
private fun majority(nums: List<Int>, l: Int, r: Int): Int {
if (l == r) {
return nums[l]
}
val m = l + (r - l) / 2
val lm = majority(nums, l, m)
val rm = majority(nums, m + 1, r)
if (lm == rm) {
return lm
}
val countLm = nums.subList(l, r + 1).count { it == lm }
val countRm = nums.subList(l, r + 1).count { it == rm }
return if (countLm > countRm) lm else rm
}
}
class MajorityElementBit : MajorityElement {
companion object {
private const val POSITIONS = 32
}
override fun invoke(nums: IntArray): Int {
var majority = 0
for (i in 0 until POSITIONS) {
var bits = 0
for (num in nums) {
if (num and (1 shl i) != 0) {
bits++
}
}
if (bits > nums.size / 2) {
majority = majority or (1 shl i)
}
}
return majority
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,219 | kotlab | Apache License 2.0 |
src/year2023/13/Day13.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`13`
import readInput
import utils.printDebug
import utils.printlnDebug
private const val CURRENT_DAY = "13"
private data class Point(
val x: Int,
val y: Int,
)
private fun parseIntoListsOfLists(input: List<String>): List<List<String>> {
val mutableRes = mutableListOf<List<String>>()
var currentList = mutableListOf<String>()
input.forEach {
if (it.isNotBlank()) {
currentList.add(it)
} else {
mutableRes.add(currentList)
currentList = mutableListOf()
}
}
mutableRes.add(currentList)
return mutableRes
}
private fun parseMap(input: List<String>): Set<Point> {
val mutableMap = mutableSetOf<Point>()
input.forEachIndexed { y, line ->
line.split("")
.filter { it.isNotBlank() }
.forEachIndexed { x, value ->
if (value == "#") {
mutableMap.add(Point(x, y))
}
}
}
return mutableMap
}
private fun Set<Point>.tryToFindMirrorsDifferentItems(): List<Set<Point>> {
val newSetList: MutableList<Set<Point>> = mutableListOf()
val maxX = maxOf { it.x }
val maxY = maxOf { it.y }
for (x in 0..maxX) {
for (y in 0..maxY) {
val point = Point(x, y)
val newSet = if (this.contains(point)) {
this - point
} else {
this + point
}
newSetList.add(newSet)
}
}
check(newSetList.all { it.size in setOf(size + 1, size - 1) })
return newSetList
}
private fun Set<Point>.tryToFindMirrors(prevAnswers: Set<Int>): Int? {
val maxX = maxOf { it.x }
val res: MutableSet<Int> = mutableSetOf()
for (i in 0..maxX) {
val mapToCheck = isMirroredHorizontally(i)
val isValid = verify(maxX, this, mapToCheck)
// if (isValid) println("X = $i isValid=$isValid")
if (isValid) res.add(i)
}
return (res - prevAnswers).firstOrNull()
}
private fun Set<Point>.tryToFindVerticalMirrors(prevAnswers: Set<Int>): Int? {
val maxY = maxOf { it.y }
val res: MutableSet<Int> = mutableSetOf()
for (i in 0..maxY) {
val mapToCheck = isMirroredVertically(i)
val isValid = verifyVertical(maxY, this, mapToCheck)
// if (isValid) println("Y = $i isValid=$isValid")
if (isValid) res.add(i)
}
return (res - prevAnswers).firstOrNull()
}
private fun verify(
maxX: Int,
points: Set<Point>,
validPoints: Map<Point, Boolean>,
): Boolean {
if (validPoints.values.distinct().size == 1) return false
val list = mutableListOf<Boolean>()
for (i in 0..maxX) {
val allSameForX = points.filter { it.x == i }
.map { validPoints[it]!! }
.distinctBy { it }
.size == 1
list.add(points.filter { it.x == i }
.map { validPoints[it]!! }
.all { it })
if (allSameForX.not()) return false
}
var count = 0
list.reduce { acc, b ->
if (acc == b) {
b
} else {
count++
b
}
}
return count == 1
}
private fun verifyVertical(
maxY: Int,
points: Set<Point>,
validPoints: Map<Point, Boolean>,
): Boolean {
if (validPoints.values.distinct().size == 1) return false
val list = mutableListOf<Boolean>()
for (i in 0..maxY) {
val allSameForY = points.filter { it.y == i }
.map { validPoints[it]!! }
.distinctBy { it }
.size == 1
list.add(points.filter { it.y == i }
.map { validPoints[it]!! }
.all { it })
if (allSameForY.not()) return false
}
var count = 0
list.reduce { acc, b ->
if (acc == b) {
b
} else {
count++
b
}
}
return count == 1
}
private fun Map<Point, Boolean>.height(): Long = maxOf { it.key.y }.toLong()
private fun Map<Point, Boolean>.width(): Long = maxOf { it.key.x }.toLong()
private fun printSet(set: Map<Point, Boolean>) {
val height = set.height()
printlnDebug { }
for (i in 0..height) {
printDebug { "|" }
repeat(set.width().toInt() + 1) {
val symbol = when (set[Point(it, i.toInt())]) {
true -> "1"
false -> "0"
null -> "."
}
printDebug { symbol }
}
printDebug { "|" }
printlnDebug { }
}
printlnDebug { }
}
private fun Set<Point>.isMirroredHorizontally(currentX: Int): Map<Point, Boolean> {
val result = associate {
if (it.x >= currentX) {
val xDelta = it.x - currentX
val pointToSearch = it.copy(x = currentX - xDelta - 1)
it to (pointToSearch in this)
} else {
val xDelta = currentX - it.x
val pointToSearch = it.copy(x = currentX + xDelta - 1)
it to (pointToSearch in this)
}
}
return result
}
private fun Set<Point>.isMirroredVertically(currentY: Int): Map<Point, Boolean> {
val result = associate {
if (it.y >= currentY) {
val xDelta = it.y - currentY
val pointToSearch = it.copy(y = currentY - xDelta - 1)
it to (pointToSearch in this)
} else {
val yDelta = currentY - it.y
val pointToSearch = it.copy(y = currentY + yDelta - 1)
it to (pointToSearch in this)
}
}
return result
}
fun main() {
fun part1(input: List<String>): Int {
var horizontalCounter = 0
var verticalCounter = 0
parseIntoListsOfLists(input)
.map { parseMap(it) }
.forEach {
printlnDebug { "NEW SET ARRIVED" }
printSet(it.associateWith { true })
val horizontal = it.tryToFindMirrors(emptySet())
val vertical = it.tryToFindVerticalMirrors(emptySet())
if (horizontal != null) {
horizontalCounter += horizontal
}
if (vertical != null) {
verticalCounter += vertical
}
}
return horizontalCounter + verticalCounter * 100
}
fun part2(input: List<String>): Int {
var horizontalCounter = 0
var verticalCounter = 0
parseIntoListsOfLists(input)
.map { parseMap(it) }
.forEach { ourSetOfPoints ->
printlnDebug { "NEW SET ARRIVED" }
val horizontal = ourSetOfPoints.tryToFindMirrors(emptySet())
val vertical = ourSetOfPoints.tryToFindVerticalMirrors(emptySet())
val resList = ourSetOfPoints.tryToFindMirrorsDifferentItems()
resList
.asSequence()
.map {
val newMirror = it.tryToFindMirrors(setOfNotNull(horizontal))
val newVMirror = it.tryToFindVerticalMirrors(setOfNotNull(vertical))
Triple(it, newMirror, newVMirror)
}
.filter { (_, hMirror, vMirror) ->
hMirror != null || vMirror != null
}
.filter { (_, hMirror, vMirror) ->
hMirror != horizontal || vMirror != vertical
}
.distinctBy { (_, hMirror, vMirror) -> hMirror to vMirror }
.onEach { (_, hMirror, vMirror) ->
printlnDebug { "H: $horizontal V:$vertical NEW_H:$hMirror NEW_V:$vMirror" }
if (hMirror != null && hMirror != horizontal) {
horizontalCounter += hMirror
}
if (vMirror != null && vMirror != vertical) {
verticalCounter += vMirror
}
}
.toList()
.ifEmpty {
printlnDebug { "NEW SET IS EMPTY - CHECK THIS" }
printSet(ourSetOfPoints.associateWith { true })
}
}
return horizontalCounter + verticalCounter * 100
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 405)// + 700)
val part2Test = part2(testInput)
println(part2Test)
check(part2Test == 400)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input)
println(part1)
check(part1 == 34993)
// Part 2
val part2 = part2(input)
println(part2)
check(part2 == 29341)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 8,840 | KotlinAdventOfCode | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/MinimumDifference.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
import com.daily.algothrim.tree.TreeNode
import kotlin.math.min
/**
* 二叉树的最小绝对差(leetcode 530)
*
* 给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
* 示例:
*
* 输入:
*
* 1
* \
* 3
* /
* 2
*
* 输出:
* 1
*
* 解释:
* 最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
*
* 提示:
* 树中至少有 2 个节点。
*/
class MinimumDifference {
private var mPre = -1
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(MinimumDifference().getMinimumDifference(TreeNode(5, left = TreeNode(4), right = TreeNode(7))))
}
}
/**
* O(n)
*/
fun getMinimumDifference(root: TreeNode<Int>?): Int {
return dfs(root, Int.MAX_VALUE)
}
/**
* 中序遍历之后是一个递增的有序队列,直接比较
*/
private fun dfs(root: TreeNode<Int>?, currentMin: Int): Int {
if (root == null) return currentMin
var sCurrentMin: Int
sCurrentMin = dfs(root.left, currentMin)
if (mPre < 0) {
mPre = root.data
} else {
sCurrentMin = min(sCurrentMin, root.data - mPre)
mPre = root.data
}
sCurrentMin = dfs(root.right, sCurrentMin)
return sCurrentMin
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 1,452 | daily_algorithm | Apache License 2.0 |
src/kotlin2023/Day01.kt | egnbjork | 571,981,366 | false | {"Kotlin": 18156} | package kotlin2023
import readInput
val spelledNumbers = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9
)
fun main() {
val lines = readInput("kotlin2023/Day01_test")
val result = lines.sumOf {
it.getDigits()
}
println(result)
}
fun String.getDigits(): Int {
val noSpellNumbers = this.parseSpelledNumbers()
var digits = ""
noSpellNumbers.forEach {
if (it.isDigit()) {
digits += it
}
}
return when (digits.length) {
2 -> digits.toInt()
1 -> (digits + digits).toInt()
else -> (digits.first() + "" + digits.last()).toInt()
}
}
fun String.parseSpelledNumbers(): String {
var result = this
spelledNumbers.forEach {
if(result.contains(it.key)) {
result = result.replace(it.key,
"${it.key.first()}${it.value}${it.key.last()}",
false)
}
}
return result
}
| 0 | Kotlin | 0 | 0 | 1294afde171a64b1a2dfad2d30ff495d52f227f5 | 1,084 | advent-of-code-kotlin | Apache License 2.0 |
src/Day18.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | import java.util.*
import kotlin.collections.ArrayDeque
import kotlin.math.abs
fun main() {
data class Cube(val x: Int, val y: Int, val z: Int)
fun part1(input: List<String>): Int {
val cubes = HashSet<Cube>()
for (s in input) {
val (x, y, z) = s.split(',').map { it.toInt() }
cubes += Cube(x, y, z)
}
var cnt = 0
for (c in cubes) {
val (x, y, z) = c
for (dx in -1..1) {
for (dy in -1..1) {
for (dz in -1..1) {
if (abs(dx) + abs(dy) + abs(dz) == 1) {
val c1 = Cube(x + dx, y + dy, z + dz)
if (c1 !in cubes) cnt++
}
}
}
}
}
return cnt
}
fun <T, R : Comparable<R>> List<T>.minMax(getValue: (T) -> R): Pair<R, R> {
var min = getValue(this[0])
var max = min
for (i in 1 until size) {
min = minOf(min, getValue(this[i]))
max = maxOf(max, getValue(this[i]))
}
return min to max
}
fun part2(input: List<String>): Int {
val cubes = mutableListOf<Cube>()
for (s in input) {
val (x, y, z) = s.split(',').map { it.toInt() }
cubes += Cube(x, y, z)
}
fun Pair<Int, Int>.toRange() = first - 1..second + 1
val dxs = cubes.minMax { it.x }.toRange()
val dys = cubes.minMax { it.y }.toRange()
val dzs = cubes.minMax { it.z }.toRange()
fun IntRange.minMax() = listOf(first, last)
val q = ArrayDeque<Cube>()
val used = HashSet<Cube>()
for (x in dxs.minMax()) {
for (y in dys.minMax()) {
for (z in dzs.minMax()) {
q += Cube(x, y, z)
used += Cube(x, y, z)
}
}
}
while (!q.isEmpty()) {
val (x, y, z) = q.removeFirst()
for (dx in -1..1) {
for (dy in -1..1) {
for (dz in -1..1) {
if (abs(dx) + abs(dy) + abs(dz) == 1) {
val c1 = Cube(x + dx, y + dy, z + dz)
if (c1 in cubes) continue
if (c1.x in dxs && c1.y in dys && c1.z in dzs) {
if (used.add(c1)) {
q.add(c1)
}
}
}
}
}
}
}
var cnt = 0
for (c in cubes) {
val (x, y, z) = c
for (dx in -1..1) {
for (dy in -1..1) {
for (dz in -1..1) {
if (abs(dx) + abs(dy) + abs(dz) == 1) {
val c1 = Cube(x + dx, y + dy, z + dz)
if (c1 in used) cnt++
}
}
}
}
}
return cnt
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 18)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 3,535 | advent-of-code-2022 | Apache License 2.0 |
2023/src/main/kotlin/day20.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.cut
import utils.lcm
import utils.mapItems
import java.util.LinkedList
fun main() {
Day20.run(skipTest = true)
}
object Day20 : Solution<Map<String, Day20.Module>>() {
override val name = "day20"
override val parser = Parser.lines
.mapItems { Module.parse(it) }
.map { it.associateBy { m -> m.name } + mapOf("button" to Module.Broadcast("button", listOf("broadcaster"))) }
private fun Pair<Long, Long>.addSig(high: Boolean, amount: Long): Pair<Long, Long> {
return if (high) first to second + amount else first + amount to second
}
sealed class Module {
abstract val name: String
abstract val targets: List<String>
var connected = mutableSetOf<String>()
abstract fun send(modules: Map<String, Module>, src: String, high: Boolean): Boolean?
open fun connectSrc(modules: Map<String, Module>, src: String) {
if (src in connected) {
return
}
connected += src
targets.map { modules[it] }.forEach { it?.connectSrc(modules, this.name) }
}
data class FlipFlop(
override val name: String,
override val targets: List<String>,
) : Module() {
var pulse = false
override fun send(modules: Map<String, Module>, src: String, high: Boolean): Boolean? {
if (high) {
return null
}
pulse = !pulse
return pulse
}
}
data class And(
override val name: String,
override val targets: List<String>,
) : Module() {
var mem = mutableMapOf<String, Boolean>()
override fun send(modules: Map<String, Module>, src: String, high: Boolean): Boolean {
mem[src] = high
return mem.values.any { !it }
}
override fun connectSrc(modules: Map<String, Module>, src: String) {
mem.putIfAbsent(src, false)
super.connectSrc(modules, src)
}
}
data class Broadcast(
override val name: String,
override val targets: List<String>,
) : Module() {
override fun send(modules: Map<String, Module>, src: String, high: Boolean): Boolean {
return high
}
}
companion object {
fun parse(line: String): Module {
val (module, targetStrs) = line.cut(" -> ")
val targets = targetStrs.split(", ")
val name = module.removePrefix("%").removePrefix("&")
return when (module[0]) {
'%' -> FlipFlop(name, targets)
'&' -> And(name, targets)
else -> Broadcast(name, targets)
}
}
}
}
override fun part1(): Long {
val bc = input["broadcaster"]!!
bc.connectSrc(input, "button")
val pulses = LinkedList<Triple<String, String, Boolean>>()
var sent = 0L to 0L
val times = 1000
repeat (times) {
pulses.add(Triple("button", "broadcaster", false))
while (pulses.isNotEmpty()) {
val (src, dst, high) = pulses.removeFirst()
sent = sent.addSig(high, 1L)
val module = input[dst] ?: continue
val send = module.send(input, src, high)
if (send != null) {
module.targets.forEach {
pulses.addLast(Triple(dst, it, send))
}
}
}
}
return sent.first * sent.second
}
override fun part2(): Long {
val bc = input["broadcaster"]!!
bc.connectSrc(input, "button")
// determined from input by hand:D
// val counters = listOf("qb", "nn", "rd", "rl")
// TODO(madis) can we do better here
val counters = input.values
.filterIsInstance<Module.And>()
.filter { it.connected.all { src -> input[src] is Module.FlipFlop } }
val periods = mutableMapOf<String, Int>()
val pulses = LinkedList<Triple<String, String, Boolean>>()
var count = 0L
outer@while (true) {
pulses.add(Triple("button", "broadcaster", false))
count++
while (pulses.isNotEmpty()) {
val (src, dst, high) = pulses.removeFirst()
if (dst == "rx" && !high) {
break@outer
}
val module = input[dst] ?: continue
val send = module.send(input, src, high)
if (send != null) {
module.targets.forEach {
pulses.addLast(Triple(dst, it, send))
}
}
for (counter in counters) {
if (periods[counter.name] == null && counter.mem.values.all { it }) {
periods[counter.name] = count.toInt() // count will be low at this point
}
if (periods.size == counters.size) {
// all periods gathered, stop
break@outer
}
}
}
}
return lcm(periods.values.toList())
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 4,676 | aoc_kotlin | MIT License |
src/Day22.kt | syncd010 | 324,790,559 | false | null | import java.math.BigInteger
class Day22: Day {
enum class Oper {CUT, DEAL, REVERSE}
data class Instruction(val op: Oper, val arg: Long)
fun convert(input: List<String>, sz: Long) : List<Instruction> {
return input.mapNotNull { inst ->
when {
inst.startsWith("cut") ->
Instruction(Oper.CUT, (inst.substringAfter("cut ").toLong() + sz) % sz)
inst.startsWith("deal with increment") ->
Instruction(Oper.DEAL, inst.substringAfter("increment ").toLong())
inst.startsWith("deal into new stack") ->
Instruction(Oper.REVERSE, 0)
else -> null
}
}
}
override fun solvePartOne(input: List<String>): Int {
val sz = 10007L
val instructions = convert(input, sz)
var deck = Array(sz.toInt()) { it }
instructions.forEach { inst ->
when (inst.op) {
Oper.CUT -> {
deck = deck.sliceArray(inst.arg.toInt() until sz.toInt()) + deck.sliceArray(0 until inst.arg.toInt())
}
Oper.DEAL -> {
val oldDeck = deck.copyOf()
for (i in deck.indices)
deck[((i * inst.arg) % sz).toInt()] = oldDeck[i]
}
Oper.REVERSE -> {
deck.reverse()
}
}
}
return deck.indexOf(2019)
}
fun unshufflePos(startPos: BigInteger, sz: BigInteger, instructions: List<Instruction>): BigInteger {
var pos = startPos
instructions.asReversed().forEach { inst ->
val n = BigInteger.valueOf(inst.arg)
pos = when (inst.op) {
Oper.CUT -> (pos + n).mod(sz)
Oper.DEAL -> (n.modInverse(sz) * pos).mod(sz)
Oper.REVERSE -> sz - pos - BigInteger.ONE
}
}
return pos
}
override fun solvePartTwo(input: List<String>): Long {
// Couldn't solve this. Implemented solution from:
// https://www.reddit.com/r/adventofcode/comments/ee0rqi/2019_day_22_solutions/fbnifwk/
val sz = BigInteger.valueOf(119315717514047)
val instructions = convert(input, sz.toLong())
// Shuffle is linear, so there exists A and B such that shuffle(x) = A*x + B (in modulo sz)
// So, find f1 = shuffle(x) and f2 = shuffle(f1), f1 = A*x + B, f2 = A*f1 + B
// f1 - f2 = A*(x - f1) thus A = (f1 - f2)/(x - f1) and B = f1 - A*x
val x = BigInteger.ZERO
val f1 = unshufflePos(x, sz, instructions)
val f2 = unshufflePos(f1, sz, instructions)
val a = ((f1 - f2) * (x - f1).modInverse(sz)).mod(sz)
val b = (f1 - a * x).mod(sz)
// Now to apply n times f:
// f^n(x) = A^n*x + A^(n-1)*B + A^(n-2)*B + ... B
// = A^n*x + (A^(n-1) + A^(n-2) + ... 1) * B
// = A^n*x + (A^n-1) / (A - 1) * B
val pos = BigInteger.valueOf(2020L)
val iter = BigInteger.valueOf(101741582076661)
val an = a.modPow(iter, sz)
return ((an * pos + (an - BigInteger.ONE) * (a - BigInteger.ONE).modInverse(sz) * b).mod(sz)).toLong()
}
} | 0 | Kotlin | 0 | 0 | 11c7c7d6ccd2488186dfc7841078d9db66beb01a | 3,343 | AoC2019 | Apache License 2.0 |
Algorithms/Search/SherlockandArray/Solution.kt | ahmed-mahmoud-abo-elnaga | 449,443,709 | false | {"Kotlin": 14218} | /*
Problem: https://www.hackerrank.com/challenges/sherlock-and-array/problem
Kotlin Language Version
Tool Version : Android Studio
Thoughts (Key points in algorithm):
This is quite a straight forward problem. All elements of the input array is
set to the sum of all the elements upto that point of the input array, i.e.
arr[i] = Sum(arr[j]) for 0 <= j <=i < n
Then in an other loop we compare arr[i] and arr[n-1] - arr[i] , which will
turn the answer to be YES, otherwise it is NO.
Time Complexity : O( n ) for each test case.
Space Complextiy : O( n ) for entire input file.
*/
object Main {
/* Complete the 'balancedSums' function below.
* The function is expected to return a STRING.
* The function accepts INTEGER_ARRAY arr as parameter.
*/
fun balancedSums(arr: Array<Int>): String {
if (arr.size == 1) return "YES"
var incrementalArray = IntArray(arr.size)
incrementalArray[0] = arr[0]
for (i in 1 until arr.size) {
incrementalArray[i] = arr[i] + incrementalArray[i - 1]
}
var currentRightSideSum = 0
loop@ for (i in 1 until incrementalArray.size) {
//RightSide without current value
currentRightSideSum = incrementalArray[incrementalArray.size - 1] -
incrementalArray[i]
if (incrementalArray[i - 1] == currentRightSideSum ||
incrementalArray[i - 1] == incrementalArray[incrementalArray.size - 1]
) {
return "YES"
}
}
return "NO"
}
fun main(args: Array<String>) {
val T = readLine()!!.trim().toInt()
for (TItr in 1..T) {
val n = readLine()!!.trim().toInt()
val arr = readLine()!!.trimEnd().split(" ").map { it.toInt() }.toTypedArray()
val result = balancedSums(arr)
println(result)
}
}
}
| 0 | Kotlin | 1 | 1 | a65ee26d47b470b1cb2c1681e9d49fe48b7cb7fc | 2,002 | HackerRank | MIT License |
src/main/kotlin/com/github/freekdb/aoc2019/old/Day3Version1.kt | FreekDB | 228,241,398 | false | null | package com.github.freekdb.aoc2019.old
import java.io.File
import kotlin.experimental.or
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
private const val NUMBER_PATH_1 = 0
private const val NUMBER_PATH_2 = 1
private const val DIRECTION_UP = 'U'
private const val DIRECTION_DOWN = 'D'
private const val DIRECTION_LEFT = 'L'
private const val DIRECTION_RIGHT = 'R'
// https://adventofcode.com/2019/day/3
fun main(arguments: Array<String>) {
val inputPath = if (arguments.isEmpty()) "input/day-03--input.txt" else arguments[0]
val crossingDistance = findCrossingDistance(inputPath)
println("Crossing distance for input file $inputPath: $crossingDistance")
}
private fun findCrossingDistance(inputPath: String): Int {
val inputLines = readInput(inputPath)
return if (inputLines.size == 2) {
val path1 = inputLines[0]
val path2 = inputLines[1]
val grid = Grid(
mergeDimensions(
calculateDimensions(
path1
),
calculateDimensions(path2)
)
)
grid.registerPath(path1, NUMBER_PATH_1)
grid.registerPath(path2, NUMBER_PATH_2)
grid.findClosestDistance()
} else {
0
}
}
private fun readInput(inputPath: String): List<String> {
return File(inputPath)
.readLines()
.filter { it.isNotEmpty() }
}
private fun calculateDimensions(path: String): Dimensions {
var rowIndex = 0
var columnIndex = 0
var minimumRowIndex = 0
var maximumRowIndex = 0
var minimumColumnIndex = 0
var maximumColumnIndex = 0
path
.split(",")
.forEach {
val direction = it[0]
val distance = it.substring(1).toInt()
rowIndex += calculateVerticalDistance(direction, distance)
columnIndex += calculateHorizontalDistance(
direction,
distance
)
minimumRowIndex = min(minimumRowIndex, rowIndex)
maximumRowIndex = max(maximumRowIndex, rowIndex)
minimumColumnIndex = min(minimumColumnIndex, columnIndex)
maximumColumnIndex = max(maximumColumnIndex, columnIndex)
}
return Dimensions(
minimumRowIndex,
maximumRowIndex,
minimumColumnIndex,
maximumColumnIndex
)
}
private fun calculateVerticalDistance(direction: Char, distance: Int): Int {
return when (direction) {
DIRECTION_UP -> -distance
DIRECTION_DOWN -> distance
else -> 0
}
}
private fun calculateHorizontalDistance(direction: Char, distance: Int): Int = when (direction) {
DIRECTION_LEFT -> -distance
DIRECTION_RIGHT -> distance
else -> 0
}
data class Dimensions(val minimumRowIndex: Int, val maximumRowIndex: Int,
val minimumColumnIndex: Int, val maximumColumnIndex: Int) {
val height = maximumRowIndex - minimumRowIndex + 1
val width = maximumColumnIndex - minimumColumnIndex + 1
}
fun mergeDimensions(dimensions1: Dimensions, dimensions2: Dimensions): Dimensions {
return Dimensions(
min(dimensions1.minimumRowIndex, dimensions2.minimumRowIndex),
max(dimensions1.maximumRowIndex, dimensions2.maximumRowIndex),
min(dimensions1.minimumColumnIndex, dimensions2.minimumColumnIndex),
max(dimensions1.maximumColumnIndex, dimensions2.maximumColumnIndex)
)
}
class Grid(dimensions: Dimensions) {
private val height = dimensions.height + 2
private val width = dimensions.width + 2
private val originRowIndex = 1 - dimensions.minimumRowIndex
private val originColumnIndex = 1 - dimensions.minimumColumnIndex
private val cells: Array<Array<Byte>> = Array(height) { Array(width) { 0.toByte() } }
fun registerPath(path: String, number: Int) {
var rowIndex = originRowIndex
var columnIndex = originColumnIndex
path
.split(",")
.forEach {
val direction = it[0]
val distance = it.substring(1).toInt()
val verticalDistance =
calculateVerticalDistance(direction, distance)
val horizontalDistance =
calculateHorizontalDistance(direction, distance)
markCells(rowIndex, columnIndex, verticalDistance, horizontalDistance, number)
rowIndex += verticalDistance
columnIndex += horizontalDistance
}
}
private fun markCells(startRowIndex: Int, startColumnIndex: Int, verticalDistance: Int, horizontalDistance: Int,
number: Int) {
// https://stackoverflow.com/questions/9562605/in-kotlin-can-i-create-a-range-that-counts-backwards
val fromRowIndex = min(startRowIndex, startRowIndex + verticalDistance)
val toRowIndex = max(startRowIndex, startRowIndex + verticalDistance)
val fromColumnIndex = min(startColumnIndex, startColumnIndex + horizontalDistance)
val toColumnIndex = max(startColumnIndex, startColumnIndex + horizontalDistance)
for (rowIndex in fromRowIndex..toRowIndex) {
for (columnIndex in fromColumnIndex..toColumnIndex) {
cells[rowIndex][columnIndex] = cells[rowIndex][columnIndex] or (1 shl number).toByte()
}
}
}
fun findClosestDistance(): Int {
var closestDistance = Int.MAX_VALUE
val numberCrossing = ((1 shl NUMBER_PATH_1) or (1 shl NUMBER_PATH_2)).toByte()
for (rowIndex in 0 until height) {
for (columnIndex in 0 until width) {
if (cells[rowIndex][columnIndex] == numberCrossing && isNotOrigin(rowIndex, columnIndex)) {
val distance = abs(rowIndex - originRowIndex) + abs(columnIndex - originColumnIndex)
closestDistance = min(closestDistance, distance)
}
}
}
return closestDistance
}
private fun isNotOrigin(rowIndex: Int, columnIndex: Int): Boolean =
rowIndex != originRowIndex || columnIndex != originColumnIndex
}
| 0 | Kotlin | 0 | 1 | fd67b87608bcbb5299d6549b3eb5fb665d66e6b5 | 6,146 | advent-of-code-2019 | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2023/day11/Image.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.day11
import com.github.michaelbull.advent2023.iteration.combinationPairs
import com.github.michaelbull.advent2023.math.Vector2
import com.github.michaelbull.advent2023.math.manhattanDistance
private typealias Dimension = (Vector2) -> Int
private typealias Axis = (Int) -> Vector2
fun Sequence<String>.toImage(): Image {
val galaxies = buildSet {
for ((y, line) in this@toImage.withIndex()) {
for ((x, char) in line.withIndex()) {
if (char == '#') {
add(Vector2(x, y))
} else if (char != '.') {
throw IllegalArgumentException("$this is not a pixel")
}
}
}
}
return Image(galaxies)
}
data class Image(
val galaxies: Set<Vector2>,
) {
private val horizontalGalaxies = galaxies.sortedBy(::horizontal)
private val verticalGalaxies = galaxies.sortedBy(::vertical)
fun sumShortestPathLengths(): Long {
return galaxies.toList()
.combinationPairs()
.sumOf { (from, to) -> manhattanDistance(from, to).toLong() }
}
fun expand(factor: Int): Image {
return expand(factor, factor)
}
fun expand(horizontalFactor: Int, verticalFactor: Int): Image {
return expandHorizontally(horizontalFactor).expandVertically(verticalFactor)
}
private fun expandHorizontally(factor: Int): Image {
return copy(galaxies = horizontalGalaxies.expand(factor, ::horizontal, ::horizontal))
}
private fun expandVertically(factor: Int): Image {
return copy(galaxies = verticalGalaxies.expand(factor, ::vertical, ::vertical))
}
private fun List<Vector2>.expand(factor: Int, dimension: Dimension, axis: Axis): Set<Vector2> {
val first = first()
val pairs = zipWithNext()
return buildSet {
add(first)
var expansion = Vector2.ZERO
val multiplicand = factor - 1
for ((a, b) in pairs) {
val delta = dimension(b) - dimension(a)
val emptyCount = delta - 1
if (emptyCount > 0) {
expansion += axis(emptyCount * multiplicand)
}
add(b + expansion)
}
}
}
private fun horizontal(vector: Vector2) = vector.x
private fun horizontal(x: Int) = Vector2(x, 0)
private fun vertical(vector: Vector2) = vector.y
private fun vertical(y: Int) = Vector2(0, y)
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 2,529 | advent-2023 | ISC License |
src/main/kotlin/solutions/Day21MonkeyMath.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import utils.Input
import utils.Solution
// run only this day
fun main() {
Day21MonkeyMath()
}
class Day21MonkeyMath : Solution() {
init {
begin("Day 21 - Monkey Math")
val input = Input.parseLines(filename = "/d21_monkey_shouts.txt")
val numYellers = mutableMapOf<String, Long>()
val resultYellers = mutableMapOf<String, MutableList<String>>()
val numYellers2 = mutableMapOf<String, Long>()
val resultYellers2 = mutableMapOf<String, MutableList<String>>()
input.forEach {
val (name, yell) = it.split(": ")
try {
val n = yell.toLong()
numYellers[name] = n
numYellers2[name] = n
} catch (e: Exception) {
resultYellers[name] = yell.split(" ").toMutableList()
resultYellers2[name] = yell.split(" ").toMutableList()
}
}
val sol1 = findRootNumber(numYellers, resultYellers)
output("root's Number", sol1)
val sol2 = findRootNumber2(numYellers2, resultYellers2)
output("root's Correct Number", sol2)
}
private fun findRootNumber(
numYellers: MutableMap<String, Long>,
resultYellers: MutableMap<String, MutableList<String>>
): Long {
while (resultYellers.isNotEmpty()) {
val converted = mutableMapOf<String, Long>()
numYellers.forEach { ny ->
val matches = resultYellers.filter { it.value.contains(ny.key) }
matches.forEach { m ->
if (m.value[0] == ny.key)
m.value[0] = ny.value.toString()
else m.value[2] = ny.value.toString()
try {
val a = m.value[0].toLong()
val b = m.value[2].toLong()
val c = when (m.value[1]) {
"+" -> a + b
"-" -> a - b
"/" -> a / b
else -> a * b
}
converted[m.key] = c
} catch (_: Exception) {
}
}
}
converted.forEach {
numYellers[it.key] = it.value
resultYellers.remove(it.key)
}
}
return numYellers["root"]!!
}
private fun findRootNumber2(
numYellers: MutableMap<String, Long>,
resultYellers: MutableMap<String, MutableList<String>>
): Long {
resultYellers["root"]!![1] = "="
resultYellers["humn"] = mutableListOf("x")
numYellers.remove("humn")
var filtered = resultYellers.filterNot { it.value.contains("humn") }
while (filtered.isNotEmpty()) {
val converted = mutableMapOf<String, Long>()
numYellers.forEach { ny ->
val matches = resultYellers.filter { it.value.contains(ny.key) }
matches.forEach { m ->
if (m.value[0] == ny.key)
m.value[0] = ny.value.toString()
else m.value[2] = ny.value.toString()
try {
val a = m.value[0].toLong()
val b = m.value[2].toLong()
val c = when (m.value[1]) {
"+" -> a + b
"-" -> a - b
"/" -> a / b
else -> a * b
}
converted[m.key] = c
} catch (_: Exception) {
}
}
}
converted.forEach {
numYellers[it.key] = it.value
resultYellers.remove(it.key)
}
val newFilter = resultYellers.filterNot { it.value.contains("humn") }
if (newFilter == filtered)
break
else filtered = newFilter
}
val equation = writeEquation(resultYellers["root"]!!, resultYellers, numYellers).dropLast(1).drop(1)
val humn = findHumn(equation)
return humn
}
private fun writeEquation(
start: List<String>,
resultYellers: Map<String, MutableList<String>>,
numYellers: MutableMap<String, Long>
): List<String> {
val eq = start.toMutableList()
start.forEach { item ->
val i = eq.indexOf(item)
try {
if (item == "humn")
eq[i] = "x"
else if (item != "+" && item != "-" && item != "*" && item != "/" && item != "=")
item.toLong()
} catch (_: Exception) {
numYellers[item]?.let {
eq[i] = it.toString()
} ?: run {
val sub = writeEquation(resultYellers[item]!!, resultYellers, numYellers)
eq.removeAt(i)
eq.addAll(i, sub)
}
}
}
return eq.apply {
add(0, "(")
add(")")
}
}
private fun findHumn(eq: List<String>): Long {
val i = eq.indexOf("=")
val sLeft = eq.subList(0, i).toMutableList()
val sRight = eq.subList(i + 1, eq.size).toMutableList()
var root =
if ("x" in sLeft) sRight.first().toLong()
else sLeft.first().toLong()
val exp = if ("x" in sLeft) sLeft else sRight
while (exp.size > 1) {
// remove parentheses
exp.apply {
removeFirst()
removeLast()
}
val doFront = exp.first() != "(" && exp.first() != "x"
if (doFront) {
val op = exp.take(2)
when (op.last()) {
"+" -> root -= op.first().toLong()
"-" -> root = -1 * (root - op.first().toLong())
"/" -> root = op.first().toLong() / root
else -> root /= op.first().toLong()
}
exp.removeFirst()
exp.removeFirst()
} else {
val op = exp.takeLast(2)
when (op.first()) {
"+" -> root -= op.last().toLong()
"-" -> root += op.last().toLong()
"/" -> root *= op.last().toLong()
else -> root /= op.last().toLong()
}
exp.removeLast()
exp.removeLast()
}
}
return root
}
} | 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 6,689 | advent-of-code-2022 | MIT License |
src/main/kotlin/com/hopkins/aoc/day14/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day14
import java.io.File
const val debug = true
const val part = 2
val cache = mutableMapOf<String, Int>()
val loadFactorLookup = mutableMapOf<Int, Int>()
/** Advent of Code 2023: Day 14 */
fun main() {
// Read the file input
val lines: List<String> = File("input/input14.txt").readLines()
val numLines = lines.size
if (debug) {
println("Num lines: $numLines")
println("Input")
println("=====")
lines.take(10).forEach { println(it) }
}
// Calculate the lines after tilting
val output = lines.map { it.toCharArray().toMutableList() }.toMutableList()
val directionList =
if (part == 1) {
listOf(Direction.RIGHT)
} else {
listOf(Direction.UP, Direction.LEFT, Direction.DOWN, Direction.RIGHT)
}
val numCycles = if (part == 1) 1 else 10000
var cycleStart = 0
var cycleEnd = 0
for (cycle in 0 until numCycles) {
val key = buildCacheKey(output)
if (cache.containsKey(key)) {
println("Cycle found cycle=$cycle orig=${cache[key]!!}")
cycleStart = cache[key]!!
cycleEnd = cycle
break;
}
cache[key] = cycle
for (direction in directionList) {
calculateAfterTilt(output, direction)
}
loadFactorLookup[cycle] = calculateLoadFactor(output)
}
val afterTilt = output.map { it.joinToString(separator = "") }.toList()
if (debug) {
println("After Tilt")
println("==========")
afterTilt.take(10).forEach { println(it) }
}
if (part == 1) {
val totalLoad = loadFactorLookup[0]
println("Total Load: $totalLoad") // 106648
} else {
val cycleLength = cycleEnd - cycleStart
val target = 1_000_000_000
val numCycles = (target - cycleStart) / cycleLength
val offset = target - (numCycles * cycleLength) - 1
if (debug) {
println("Cycle start=$cycleStart end=$cycleEnd length=$cycleLength")
println("Target target=$target numCycles=$numCycles offset=$offset")
}
val totalLoad = loadFactorLookup[offset]
println("Total Load: $totalLoad")
}
}
fun calculateLoadFactor(data: MutableList<MutableList<Char>>): Int {
val numLines = data.size
return data.mapIndexed { index, line ->
val factor = numLines - index
countRoundRocks(line) * factor
}.sum()
}
fun buildCacheKey(data: MutableList<MutableList<Char>>): String =
data.joinToString(separator = "\n") { it.joinToString(separator = "") }
fun calculateAfterTilt(data: MutableList<MutableList<Char>>, direction: Direction) {
val width = data[0].size
val height = data.size
val ybounds = 0 until height
val xbounds = 0 until width
val yrange = if (direction == Direction.UP) 0 until height else height-1 downTo 0
val xrange = if (direction == Direction.LEFT) 0 until width else width-1 downTo 0
yrange.forEach { y ->
xrange.forEach { x ->
val c = data[y][x]
if (c == '.') {
var dy = -direction.delta.y
var dx = -direction.delta.x
while (y+dy in ybounds &&
x+dx in xbounds &&
data[y+dy][x+dx] == '.') {
dy -= direction.delta.y
dx -= direction.delta.x
}
if (y+dy in ybounds &&
x+dx in xbounds &&
data[y+dy][x+dx] == 'O') {
data[y][x] = 'O'
data[y+dy][x+dx] = '.'
}
}
}
}
}
fun countRoundRocks(chars: List<Char>): Int {
return chars.count { it == 'O' }
}
fun countRoundRocks(line: String): Int {
return line.count { it == 'O' }
}
enum class Direction(val delta: Point) {
UP(Point(0, -1)),
DOWN(Point(0, 1)),
LEFT(Point(-1, 0)),
RIGHT(Point(1, 0)),
}
class Point(val x: Int, val y: Int) | 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 4,033 | aoc2023 | MIT License |
Kotlin/days/src/day10.kt | dukemarty | 224,307,841 | false | null | import java.io.BufferedReader
import java.io.FileReader
import java.lang.StringBuilder
import kotlin.math.*
data class Coordinate(val x: Int, val y: Int)
data class Asteroid(val Coord: Coordinate, var WatchCount: Int = 0, var Angle: Double = -1.0, var VaporIndex: Int = -1) {
fun distance(other: Asteroid): Double {
return sqrt((Coord.x - other.Coord.x).toDouble().pow(2) + (Coord.y - other.Coord.y).toDouble().pow(2))
}
}
data class AsteroidMap(val rawMap: List<String>) {
val asteroids: HashSet<Asteroid> = listAsteroids()
init {
}
fun calcThetasRelativeTo(root: Asteroid) {
// println("Relative to root=$root:")
for (ast in asteroids) {
if (ast == root) continue
val reversedFrac = atan2(ast.Coord.y.toDouble() - root.Coord.y, ast.Coord.x.toDouble() - root.Coord.x)
ast.Angle = ((reversedFrac + PI / 2.0) + 2.0 * PI) % (2.0 * PI)
// println(" $ast")
}
}
private fun listAsteroids(): HashSet<Asteroid> {
var res = HashSet<Asteroid>()
for ((ri, row) in rawMap.withIndex()) {
for ((ci, column) in row.withIndex()) {
if (column == '#') {
res.add(Asteroid(Coordinate(ci, ri)))
}
}
}
return res
}
override fun toString(): String {
val sb = StringBuilder()
sb.appendln("Image:")
sb.appendln(rawMap.joinToString(separator = "\n") { it })
sb.appendln("\nAsteroids:")
sb.appendln("$asteroids")
return sb.toString()
}
}
fun main(args: Array<String>) {
println("--- Day 10: Monitoring Station ---");
val br = BufferedReader(FileReader("puzzle_input/day10-input1.txt"))
val map = AsteroidMap(br.readLines())
println("Loaded map:\n$map")
val stationAsteroid = day10partOne(map)
if (stationAsteroid != null) {
day10partTwo(map, stationAsteroid)
} else {
println("Skipped part two because no station was found. :)")
}
}
fun day10partOne(map: AsteroidMap): Asteroid? {
println("\n--- Part One ---")
countAsteroidsInSight(map)
println("Processed asteroids:\n${map.asteroids}")
val optimalAsteroid = map.asteroids.maxBy { it.WatchCount }
println("Optimal position: $optimalAsteroid")
return optimalAsteroid
}
private fun countAsteroidsInSight(map: AsteroidMap) {
for (ast in map.asteroids) {
// println("Calculating for $ast")
var potential = HashSet<Asteroid>(map.asteroids)
var checked = HashSet<Asteroid>()
potential.remove(ast)
while (!potential.isEmpty()) {
val next = potential.first()
// println(" Comparing next=$next")
val dirX = ast.Coord.x - next.Coord.x
val dirY = ast.Coord.y - next.Coord.y
val sightLine =
if (dirX == 0) {
potential.filter { ast.Coord.x == it.Coord.x && (ast.Coord.y - it.Coord.y) * dirY > 0 }
} else if (dirY == 0) {
potential.filter { ast.Coord.y == it.Coord.y && (ast.Coord.x - it.Coord.x) * dirX > 0 }
} else {
potential.filter {
if (it.Coord.y != ast.Coord.y) {
val dx = ast.Coord.x - it.Coord.x
val dy = ast.Coord.y - it.Coord.y
val diff = abs(dx.toFloat() / dy.toFloat() - dirX.toFloat() / dirY.toFloat())
// println(" Compare: $ast with $it -> $diff")
dx * dirX > 0 && dy * dirY > 0 && diff < 0.0001
} else {
false
}
}
}
// println(" Asteroids in line: $sightLine")
val closest = sightLine.minBy { abs(ast.Coord.x - it.Coord.x) + abs(ast.Coord.y - it.Coord.y) }!!
// println(" Closest of those: $closest")
checked.add(closest)
potential.removeAll(sightLine)
}
ast.WatchCount = checked.size
}
}
fun day10partTwo(map: AsteroidMap, station: Asteroid) {
println("\n--- Part Two ---")
map.calcThetasRelativeTo(station)
shootAsteroids(map, station)
if (map.asteroids.size < 200) {
println("Not enough asteroids there for part two puzzle?!")
return
}
val resAsteroid = map.asteroids.first { it.VaporIndex == 200 }
if (resAsteroid != null) {
println("Found result asteroid which is vaporized as 200th: $resAsteroid")
println("Puzzle solution: ${resAsteroid.Coord.x * 100 + resAsteroid.Coord.y}")
}
}
fun shootAsteroids(map: AsteroidMap, station: Asteroid) {
var ordered = map.asteroids.sortedBy { it.Angle }.drop(1)
var vi = 1
var shootAngle = 0.0
while (vi < ordered.size) {
val potTargetIndex = ordered.indexOfFirst { it.VaporIndex < 0 && it.Angle >= shootAngle }
if (potTargetIndex < 0) {
shootAngle = 0.0
continue
}
shootAngle = ordered[potTargetIndex].Angle
var target = ordered.filter { it.VaporIndex < 0 && (it.Angle - shootAngle) < 0.0001 }.minBy { station.distance(it) }
if (target != null) {
target.VaporIndex = vi
++vi
}
shootAngle += 0.001
}
// println("${map.asteroids.sortedBy { it.VaporIndex }}")
// println("${ordered.sortedBy { it.VaporIndex }}")
} | 0 | Kotlin | 0 | 0 | 6af89b0440cc1d0cc3f07d5a62559aeb68e4511a | 5,636 | dukesaoc2019 | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem221/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem221
/**
* LeetCode page: [221. Maximal Square](https://leetcode.com/problems/maximal-square/);
*/
class Solution {
/* Complexity:
* Time O(MN) and Space O(N) where M and N are the number of rows and columns of matrix;
*/
fun maximalSquare(matrix: Array<CharArray>): Int {
/* Here the dp is collapsed into one row whose full size will be the same as the matrix size.
* For full size, the state dp[row][column] is the maxSize of square with cell(row, column) in
* its lower right corner. The value of state is related to matrix[row][column] and the three
* neighbour states(top, left, top left).
*/
val dp = IntArray(matrix[0].size) { column -> matrix[0][column] - '0' }
val hasOne = dp.any { it == 1 }
var maxSize = if (hasOne) 1 else 0
for (row in 1..matrix.lastIndex) {
var dpTopLeft = dp[0]
dp[0] = matrix[row][0] - '0'
for (column in 1..matrix[0].lastIndex) {
val cannotFormSquare = matrix[row][column] == '0'
val newValue = if (cannotFormSquare) 0 else 1 + minOf(dp[column], dp[column - 1], dpTopLeft)
dpTopLeft = dp[column]
dp[column] = newValue
}
maxSize = maxOf(maxSize, dp.max()!!)
}
return maxSize * maxSize
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,403 | hj-leetcode-kotlin | Apache License 2.0 |
kotlin/1288-remove-covered-intervals.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | // Time complexity O(nlogn) and space complexity O(n)
// Find solution with optimized space complexity below
class Solution {
fun removeCoveredIntervals(intervals: Array<IntArray>): Int {
intervals.sortWith(compareBy({ it[0] }, { -it[1] }))
val res = LinkedList<IntArray>().apply { add(intervals[0]) }
for ((l, r) in intervals) {
val (prevL, prevR) = res.peekLast()
if (prevL <= l && prevR >= r)
continue
res.addLast(intArrayOf(l, r))
}
return res.size
}
}
// Time complexity O(nlogn) and space complexity O(1)
class Solution {
fun removeCoveredIntervals(intervals: Array<IntArray>): Int {
intervals.sortWith(compareBy({ it[0] }, { -it[1] }))
var prev = intervals[0]
var res = 1
for (interval in intervals) {
if (prev[0] <= interval[0] && prev[1] >= interval[1])
continue
prev = interval
res++
}
return res
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,051 | leetcode | MIT License |
src/year2022/day03/Day03.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day03
import readInputFileByYearAndDay
import readTestFileByYearAndDay
fun main() {
fun Char.toPriority(): Int {
if (this.code >= 'A'.code && this.code < 'a'.code)
return this.code - 'A'.code + 27
else if (this.code >= 'a'.code && this.code <= 'z'.code)
return this.code - 'a'.code + 1
return 0
}
infix fun String.intersect(other: String): String = (this.toSet() intersect other.toSet()).joinToString("")
fun part1(input: List<String>): Int =
input.asSequence()
.map { it.substring(0, it.length / 2) to it.substring(it.length / 2) }
.map { it.first intersect it.second }
.map { it.first() }
.sumOf { it.toPriority() }
fun part2(input: List<String>): Int =
input.chunked(3)
.map { it.reduce { acc, s -> acc intersect s } }
.map { it[0] }
.sumOf { it.toPriority() }
val testInput = readTestFileByYearAndDay(2022, 3)
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInputFileByYearAndDay(2022, 3)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 1,184 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/AppealSum.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
/**
* 2262. Total Appeal of A String
* @see <a href="https://leetcode.com/problems/total-appeal-of-a-string/">Source</a>
*/
fun interface AppealSum {
operator fun invoke(s: String): Long
}
class AppealSumDP : AppealSum {
override operator fun invoke(s: String): Long {
var res: Long = 0
var cur: Long = 0
val prev = LongArray(ALPHABET_LETTERS_COUNT)
for (i in s.indices) {
cur += i + 1 - prev[s[i] - 'a']
prev[s[i] - 'a'] = (i + 1).toLong()
res += cur
}
return res
}
}
class AppealSumDPKt : AppealSum {
override operator fun invoke(s: String): Long {
var cur: Long = 0
val prev = LongArray(ALPHABET_LETTERS_COUNT)
return s.mapIndexed { index, c ->
cur += index + 1 - prev[c - 'a']
prev[c - 'a'] = index.toLong() + 1
cur
}.sum()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,606 | kotlab | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem79/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem79
/**
* LeetCode page: [79. Word Search](https://leetcode.com/problems/word-search/);
*/
class Solution {
/* Complexity:
* Time O(|board| * |word|) and Space O(|board|);
*/
fun exist(board: Array<CharArray>, word: String): Boolean {
val visited = List(board.size) { row -> BooleanArray(board[row].size) }
for (row in board.indices) {
for (column in board[row].indices) {
val hasValidPath = dfs(row, column, 0, word, board, visited)
if (hasValidPath) return true
}
}
return false
}
private fun dfs(
row: Int, column: Int,
currWordIndex: Int, word: String,
board: Array<CharArray>, visited: List<BooleanArray>
): Boolean {
val isInvalidPath =
isOutOfBoard(row, column, board) || visited[row][column] || board[row][column] != word[currWordIndex]
if (isInvalidPath) return false
val hasFoundLastChar = currWordIndex == word.lastIndex
if (hasFoundLastChar) return true
visited[row][column] = true
val neighbours = listOf(
Pair(row - 1, column), Pair(row, column - 1),
Pair(row + 1, column), Pair(row, column + 1)
)
val hasValidPath = neighbours.any { (nextRow, nextColumn) ->
dfs(nextRow, nextColumn, currWordIndex + 1, word, board, visited)
}
visited[row][column] = false
return hasValidPath
}
private fun isOutOfBoard(row: Int, column: Int, board: Array<CharArray>): Boolean {
return row !in board.indices || column !in board[row].indices
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,683 | hj-leetcode-kotlin | Apache License 2.0 |
2023/src/main/kotlin/Day11.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day11 {
private data class Pos(val x: Int, val y: Int)
fun sumPairwisePaths(input: String, expansionSize: Long): Long {
val image = input.splitNewlines()
val emptyRows = image.indices.filter { y -> image[y].all { it == '.' } }
val emptyCols = image[0].indices.filter { x -> image.all { it[x] == '.' } }
val galaxies = image.flatMapIndexed { y, row ->
row.indices.filter { x -> row[x] == '#' }.map { x -> Pos(x, y) }
}
// Maaanhaaattaaan distance
return galaxies.withIndex().sumOf { (index, start) ->
galaxies.drop(index + 1).sumOf { end ->
val xRange = absIntRange(start.x, end.x)
val yRange = absIntRange(start.y, end.y)
val manhattanDistance = xRange.last - xRange.first + yRange.last - yRange.first
val numExpansions = emptyCols.count { it in xRange } + emptyRows.count { it in yRange }
(manhattanDistance - numExpansions) + (expansionSize * numExpansions)
}
}
}
private fun absIntRange(a: Int, b: Int) = if (a < b) a..b else b..a
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,046 | advent-of-code | MIT License |
src/main/kotlin/Day9.kt | pavittr | 317,532,861 | false | null | import java.io.File
import java.math.BigInteger
import java.nio.charset.Charset
fun main() {
val testDocs = File("test/day9").readLines(Charset.defaultCharset()).map{it.toBigInteger()}
val puzzles = File("puzzles/day9").readLines(Charset.defaultCharset()).map{it.toBigInteger()}
fun lastNumIsValid(input: List<BigInteger>) : Boolean {
val target = input.last()
val preamble = input.dropLast(1)
return preamble.filterIndexed { index, i -> val needed = target - i; preamble.filterIndexed { innerIndex, innerI -> innerIndex != index && innerI == needed }.isNotEmpty() }.isNotEmpty()
}
println(testDocs.windowed(6,1,false).filter { !lastNumIsValid(it) }.map { it.last() })
println(puzzles.windowed(26,1,false).filter { !lastNumIsValid(it) }.map { it.last() })
fun findList(input: List<BigInteger>, target: BigInteger) : List<BigInteger> {
for (dropFirst in 0..input.size) {
val firstDrop = input.drop(dropFirst)
for (dropLast in 0..input.size) {
val rangeToTest = input.dropLast(dropLast).intersect(firstDrop)
if (rangeToTest.sumOf { it } == target) {
return rangeToTest.toList()
}
}
}
return listOf()
}
val testRange = findList(testDocs, BigInteger.valueOf(127))
println(testRange.minOrNull()?.plus(testRange.maxOrNull()!!))
val realRange = findList(puzzles, BigInteger.valueOf(375054920))
println(realRange.minOrNull()?.plus(realRange.maxOrNull()!!))
}
| 0 | Kotlin | 0 | 0 | 3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04 | 1,561 | aoc2020 | Apache License 2.0 |
src/main/kotlin/com/sk/set5/581. Shortest Unsorted Continuous Subarray.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set5
import java.util.Stack
private fun findUnsortedSubarray2(nums: IntArray): Int {
var l = nums.size
var r = 0
for (i in 0 until nums.size - 1) {
for (j in i + 1 until nums.size) {
if (nums[j] < nums[i]) {
r = maxOf(r, j)
l = minOf(l, i)
}
}
}
return if (r - l < 0) 0 else r - l + 1
}
private fun findUnsortedSubarray3(nums: IntArray): Int {
val copy = nums.clone()
copy.sort()
var start = copy.size
var end = 0
for (i in copy.indices) {
if (copy[i] != nums[i]) {
start = Math.min(start, i)
end = Math.max(end, i)
}
}
return if (end - start >= 0) end - start + 1 else 0
}
private fun findUnsortedSubarray4(nums: IntArray): Int {
val stack = Stack<Int>()
var l = nums.size
var r = 0
for (i in nums.indices) {
while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) {
l = minOf(l, stack.pop())
}
stack.push(i)
}
stack.clear()
for (i in nums.indices.reversed()) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
r = maxOf(r, stack.pop())
}
stack.push(i)
}
return if (r - l > 0) r - l + 1 else 0
}
private fun findUnsortedSubarray5(nums: IntArray): Int {
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
var flag = false
for (i in 1 until nums.size) {
if (nums[i] < nums[i - 1]) flag = true
if (flag) min = minOf(min, nums[i])
}
flag = false
for (i in nums.size - 2 downTo 0) {
if (nums[i] > nums[i + 1]) flag = true
if (flag) max = maxOf(max, nums[i])
}
var l = 0
while (l < nums.size) {
if (min < nums[l]) break
l++
}
var r = nums.size - 1
while (r >= 0) {
if (max > nums[r]) break
r--
}
return if (r - l < 0) 0 else r - l + 1
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,952 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/de/nosswald/aoc/days/Day10.kt | 7rebux | 722,943,964 | false | {"Kotlin": 34890} | package de.nosswald.aoc.days
import de.nosswald.aoc.Day
import kotlin.math.ceil
// https://adventofcode.com/2023/day/10
object Day10 : Day<Int>(10, "Pipe Maze") {
data class Point(val x: Int, val y: Int)
override fun partOne(input: List<String>): Int {
val start = Point(
x = input.first { it.contains("S") }.indexOf("S"),
y = input.indexOfFirst { it.contains("S") }
)
val seen = mutableSetOf(start)
val queue = ArrayDeque<Point>()
queue.addFirst(start)
while (queue.isNotEmpty()) {
val (r, c) = queue.removeLast()
val ch = input[r][c]
if (r > 0 && ch in "S|JL" && input[r - 1][c] in "|7F" && !seen.contains(Point(r - 1, c))) {
seen.add(Point(r - 1, c))
queue.addFirst(Point(r - 1, c))
}
if (r < input.size - 1 && ch in "S|7F" && input[r + 1][c] in "|JL" && !seen.contains(Point(r + 1, c))) {
seen.add(Point(r + 1, c))
queue.addFirst(Point(r + 1, c))
}
if (c > 0 && ch in "S-J7" && input[r][c - 1] in "-LF" && !seen.contains(Point(r, c - 1))) {
seen.add(Point(r, c - 1))
queue.addFirst(Point(r, c - 1))
}
if (c < input[r].length - 1 && ch in "S-LF" && input[r][c + 1] in "-J7" && !seen.contains(Point(r, c + 1))) {
seen.add(Point(r, c + 1))
queue.addFirst(Point(r, c + 1))
}
}
return ceil(seen.size / 2.0).toInt()
}
override fun partTwo(input: List<String>): Int {
return 0
}
override val partOneTestExamples: Map<List<String>, Int> = mapOf(
listOf(
".....",
".S-7.",
".|.|.",
".L-J.",
".....",
) to 4,
listOf(
"..F7.",
".FJ|.",
"J.L7",
"|F--J",
"J...",
) to 8
)
override val partTwoTestExamples: Map<List<String>, Int>
get() = TODO("Not yet implemented")
}
| 0 | Kotlin | 0 | 1 | 398fb9873cceecb2496c79c7adf792bb41ea85d7 | 2,109 | advent-of-code-2023 | MIT License |
src/Day12.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
data class Input(
val grid: List<List<Int>>,
val start: Pair<Int, Int>,
val end: Pair<Int, Int>
)
fun parseInput(input: List<String>): Input {
val grid = mutableListOf<List<Int>>()
var start = Pair(0, 0)
var end = Pair(0, 0)
for ((i, v) in input.withIndex()) {
val row = MutableList(v.length) { 0 }
val characters = v.toCharArray()
for ((i1, v1) in characters.withIndex()) {
when (v1) {
'S' -> {
start = Pair(i, i1)
row[i1] = 1
}
'E' -> {
end = Pair(i, i1)
row[i1] = 'z' - 'a' + 1
}
else -> row[i1] = v1 - 'a' + 1
}
}
grid.add(row)
}
return Input(
grid = grid,
start = start,
end = end
)
}
data class Explorer(
var location: Pair<Int, Int>,
var steps: Int = 0
)
fun move(
grid: List<List<Int>>,
visited: MutableList<MutableList<Boolean>>,
explorer: Explorer,
newLocation: Pair<Int, Int>
): Explorer? {
if (newLocation.first < 0 || newLocation.first >= grid.size || newLocation.second < 0 || newLocation.second >= grid[0].size)
return null
if (visited[newLocation.first][newLocation.second]) {
return null
}
if (grid[newLocation.first][newLocation.second] > grid[explorer.location.first][explorer.location.second] + 1) {
return null
}
visited[newLocation.first][newLocation.second] = true
return Explorer(
location = newLocation,
steps = explorer.steps + 1
)
}
fun moveDown(
grid: List<List<Int>>,
visited: MutableList<MutableList<Boolean>>,
explorer: Explorer,
newLocation: Pair<Int, Int>
): Explorer? {
if (newLocation.first < 0 || newLocation.first >= grid.size || newLocation.second < 0 || newLocation.second >= grid[0].size)
return null
if (visited[newLocation.first][newLocation.second]) {
return null
}
if (grid[newLocation.first][newLocation.second] < grid[explorer.location.first][explorer.location.second] - 1) {
return null
}
visited[newLocation.first][newLocation.second] = true
return Explorer(
location = newLocation,
steps = explorer.steps + 1
)
}
fun part1(input: List<String>): Int {
val data = parseInput(input)
val visited = MutableList(data.grid.size) { MutableList(data.grid[0].size) { false } }
visited[data.start.first][data.start.second] = true
val queue = mutableListOf<Explorer>()
queue.add(Explorer(location = data.start))
while (queue.isNotEmpty()) {
val explorer = queue.removeFirst()
if (explorer.location == data.end) {
return explorer.steps
}
val up = move(data.grid, visited, explorer, Pair(explorer.location.first - 1, explorer.location.second))
if (up != null) queue.add(up)
val down = move(data.grid, visited, explorer, Pair(explorer.location.first + 1, explorer.location.second))
if (down != null) queue.add(down)
val left = move(data.grid, visited, explorer, Pair(explorer.location.first, explorer.location.second - 1))
if (left != null) queue.add(left)
val right = move(data.grid, visited, explorer, Pair(explorer.location.first, explorer.location.second + 1))
if (right != null) queue.add(right)
}
return 0
}
fun part2(input: List<String>): Int {
val data = parseInput(input)
val visited = MutableList(data.grid.size) { MutableList(data.grid[0].size) { false } }
visited[data.end.first][data.end.second] = true
val queue = mutableListOf<Explorer>()
queue.add(Explorer(location = data.end))
while (queue.isNotEmpty()) {
val explorer = queue.removeFirst()
if (data.grid[explorer.location.first][explorer.location.second] == 1) {
return explorer.steps
}
val up = moveDown(data.grid, visited, explorer, Pair(explorer.location.first - 1, explorer.location.second))
if (up != null) queue.add(up)
val down =
moveDown(data.grid, visited, explorer, Pair(explorer.location.first + 1, explorer.location.second))
if (down != null) queue.add(down)
val left =
moveDown(data.grid, visited, explorer, Pair(explorer.location.first, explorer.location.second - 1))
if (left != null) queue.add(left)
val right =
moveDown(data.grid, visited, explorer, Pair(explorer.location.first, explorer.location.second + 1))
if (right != null) queue.add(right)
}
return 0
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 5,372 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/advent/of/code/hjk/Day23.kt | h-j-k | 427,964,167 | false | {"Java": 46088, "Kotlin": 26804} | package com.advent.of.code.hjk
object Day23 {
private fun process(input: List<String>, initial: Map<String, Int>): Int {
val copy = input.toMutableList()
val registers = initial.toMutableMap()
var i = 0
while (i < copy.size) {
val values = copy[i].split(" ")
i++
when (values[0]) {
"cpy" -> values[2].takeIf { it in "abcd" }?.let { registers[it] = parseOrGet(values[1], registers) }
"inc" -> registers.compute(values[1]) { _, v -> v!! + 1 }
"dec" -> registers.compute(values[1]) { _, v -> v!! - 1 }
"jnz" -> {
var value = parseOrGet(values[1], registers)
val offset = parseOrGet(values[2], registers)
if (value > 0) {
val current = i - 1
i = current + offset
if (values[1] in "abcd") {
val loopOffset =
copy.subList(i, current).indexOfFirst { it.matches("(inc|dec) ${values[1]}".toRegex()) }
if (loopOffset < 0) continue
val multiplier: Int
val loopIndex: Int
if (offset == -2) {
multiplier = 1
loopIndex = if (loopOffset == 0) i + 1 else i
} else {
val inner = copy.subList(i, i + loopOffset)
val innerLoopOffset = inner.indexOfFirst { it.matches("jnz.*-2".toRegex()) }
val key = copy[i + innerLoopOffset].split(" ")[1]
val from = inner.singleOrNull { it.matches("cpy . $key".toRegex()) } ?: continue
multiplier = value
value = registers.getValue(from.split(" ")[1])
val temp = copy.subList(i, i + innerLoopOffset)
.indexOfFirst { it.matches("(inc|dec) $key".toRegex()) }
loopIndex = if (temp + 1 == innerLoopOffset) i + temp - 1 else i + temp
}
val (loopInstruction, loopVariable) = copy[loopIndex].split(" ")
if (loopInstruction == "inc") {
registers.compute(loopVariable) { _, v -> v!! + value * multiplier }
registers[values[1]] = 0
} else {
registers.compute(loopVariable) { _, v -> v!! - value * multiplier }
registers[values[1]] = 0
}
i = current + 1
}
}
}
"tgl" -> {
val target = i - 1 + parseOrGet(values[1], registers)
if (target < copy.size && target >= 0) {
val newInstruction = when (copy[target].count { it == ' ' }) {
1 -> if (copy[target].startsWith("inc")) "dec" else "inc"
2 -> if (copy[target].startsWith("jnz")) "cpy" else "jnz"
else -> values[0]
}
copy[target] = copy[target].replaceRange(0, 3, newInstruction)
}
}
}
}
return registers.getValue("a")
}
private fun parseOrGet(value: String, registers: Map<String, Int>) = try {
value.toInt()
} catch (e: NumberFormatException) {
registers.getValue(value)
}
fun part1(input: List<String>) = process(input, mapOf("a" to 7, "b" to 0, "c" to 0, "d" to 0))
fun part2(input: List<String>) = process(input, mapOf("a" to 12, "b" to 0, "c" to 0, "d" to 0))
} | 0 | Java | 0 | 0 | 5ffa381e97cbcfe234c49b5a5f8373641166db6c | 4,021 | advent16 | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day03.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2022
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
open class Part3A : PartSolution() {
internal lateinit var rucksacks: List<String>
override fun parseInput(text: String) {
rucksacks = text.trim().split("\n")
}
override fun compute(): Int {
var sum = 0
for (rucksack in rucksacks) {
val compartment1 = rucksack.take(rucksack.length / 2).toSet()
val compartment2 = rucksack.takeLast(rucksack.length / 2).toSet()
val both = compartment1.intersect(compartment2)
if (both.isNotEmpty()) {
val char = both.first()
sum += convertToNum(char)
}
}
return sum
}
internal fun convertToNum(char: Char): Int {
if (char.isUpperCase()) {
return char - 'A' + 27
}
return char - 'a' + 1
}
override fun getExampleAnswer(): Int {
return 157
}
}
class Part3B : Part3A() {
override fun getExampleAnswer(): Int {
return 70
}
override fun compute(): Int {
var sum = 0
for (i in rucksacks.indices step 3) {
val rucksack1 = rucksacks[i].toSet()
val rucksack2 = rucksacks[i + 1].toSet()
val rucksack3 = rucksacks[i + 2].toSet()
var badge = rucksack1.intersect(rucksack2)
badge = badge.intersect(rucksack3)
if (badge.isNotEmpty()) {
sum += convertToNum(badge.first())
}
}
return sum
}
}
fun main() {
Day(2022, 3, Part3A(), Part3B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 1,656 | advent-of-code-kotlin | MIT License |
2022/Day02/problems.kt | moozzyk | 317,429,068 | false | {"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794} | import java.io.File
fun main(args: Array<String>) {
val lines = File(args[0]).readLines()
problem1(lines)
problem2(lines)
}
fun problem1(lines: List<String>) {
println(calculateScore(lines))
}
fun problem2(lines: List<String>) {
println(
calculateScore(
lines.map {
// Input:
// A - Rock; B - Paper; C - Scissors
// X - Lose; Y - Draw; Z - Win
// Output:
// A, X - Rock; B, Y - Paper; C, Z: Scissors
when (it) {
"A X" -> "A Z"
"A Y" -> "A X"
"A Z" -> "A Y"
"B X" -> "B X"
"B Y" -> "B Y"
"B Z" -> "B Z"
"C X" -> "C Y"
"C Y" -> "C Z"
"C Z" -> "C X"
else -> ""
}
}
)
)
}
fun calculateScore(lines: List<String>): Int {
val results =
lines.map {
when (it) {
// A, X - Rock; B, Y - Paper; C, Z: Scissors
"A X" -> 4
"A Y" -> 8
"A Z" -> 3
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 7
"C Y" -> 2
"C Z" -> 6
else -> 0
}
}
return results.sum()
}
| 0 | Rust | 0 | 0 | c265f4c0bddb0357fe90b6a9e6abdc3bee59f585 | 1,658 | AdventOfCode | MIT License |
src/Day08.kt | KliminV | 573,758,839 | false | {"Kotlin": 19586} | fun main() {
fun part1(input: Array<Array<Int>>): Int {
val topView = Array(input.size) { Array(input[0].size) { 0 } }
val leftView = Array(input.size) { Array(input[0].size) { 0 } }
val bottomView = Array(input.size) { Array(input[0].size) { 0 } }
val rightView = Array(input.size) { Array(input[0].size) { 0 } }
for (i in input.indices) {
for (j in input[0].indices) {
leftView[i][j] = if (j == 0) input[i][j] else leftView[i][j - 1].coerceAtLeast(input[i][j])
topView[i][j] = if (i == 0) input[i][j] else topView[i - 1][j].coerceAtLeast(input[i][j])
}
}
for (i in input.size - 1 downTo 0) {
for (j in input[0].size - 1 downTo 0) {
rightView[i][j] =
if (j == input[0].size - 1) input[i][j] else rightView[i][j + 1].coerceAtLeast(input[i][j])
bottomView[i][j] = if (i == input.size - 1) input[i][j] else bottomView[i + 1][j].coerceAtLeast(input[i][j])
}
}
var result = (input.size ) * 2 + (input[0].size ) * 2 - 4
for (i in input.indices) {
for (j in input[0].indices) {
if (i == 0 || j == 0 || i == input.size - 1 || j == input[0].size - 1) {
continue
}
if (input[i][j] > leftView[i][j - 1] ||
input[i][j] > rightView[i][j + 1] ||
input[i][j] > topView[i - 1][j] ||
input[i][j] > bottomView[i + 1][j]
) {
result += 1
}
}
}
return result
}
fun part2(input: Array<Array<Int>>): Int {
var top = 0
for (i in input.indices) {
for (j in input[0].indices) {
if (i == 0 || j == 0 || i == input.size - 1 || j == input[0].size - 1) {
continue
}
val current = input[i][j]
var leftIterator = i-1
var rightIterator = i+1
while (leftIterator > 0) {
if (input[leftIterator][j] < current) leftIterator-- else break
}
while (rightIterator < input.size-1) {
if (input[rightIterator][j] < current) rightIterator++ else break
}
var topIterator = j-1
var bottomIterator = j+1
while (topIterator > 0) {
if (input[i][topIterator] < current) topIterator-- else break
}
while (bottomIterator < input[0].size-1) {
if (input[i][bottomIterator] < current) bottomIterator++ else break
}
val score = (i - leftIterator) * (rightIterator - i) * (j - topIterator) * (bottomIterator - j)
top =
top.coerceAtLeast(score)
}
}
return top
}
fun build2DArray(input: List<String>): Array<Array<Int>> {
val result = Array(input.size) { Array(input.first().length) { 0 } }
for (i in input.indices) {
input[i].toCharArray()
.mapIndexed { j, it ->
result[i][j] = it.digitToInt()
}
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = build2DArray(readInput("Day08_test"))
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = build2DArray(readInput("Day08"))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 542991741cf37481515900894480304d52a989ae | 3,662 | AOC-2022-in-kotlin | Apache License 2.0 |
src/me/bytebeats/algo/kt/Solution13.kt | bytebeats | 251,234,289 | false | null | package me.bytebeats.algo.kt
import me.bytebeats.algs.ds.TreeNode
import kotlin.math.absoluteValue
import kotlin.math.min
/**
* @Author bytebeats
* @Email <<EMAIL>>
* @Github https://github.com/bytebeats
* @Created on 2021/9/7 19:30
* @Version 1.0
* @Description TO-DO
*/
class Solution13 {
fun minimumSwitchingTimes(source: Array<IntArray>, target: Array<IntArray>): Int {
val sm = map(source)
val tm = map(target)
sm.forEach { (t, u) ->
if (tm.containsKey(t)) {
tm[t] = (tm[t]!! - u).absoluteValue
} else {
tm[t] = u
}
}
return tm.values.sum() / 2
}
private fun map(src: Array<IntArray>): MutableMap<Int, Int> {
val map = mutableMapOf<Int, Int>()
for (ints in src) {
for (i in ints) {
map.compute(i) { _, v -> if (v == null) 1 else v + 1 }
}
}
return map
}
fun maxmiumScore(cards: IntArray, cnt: Int): Int {
val evens = mutableListOf<Int>()
val odds = mutableListOf<Int>()
for (card in cards) {
if (card and 1 == 0) {
evens.add(card)
} else {
odds.add(card)
}
}
evens.sort()
odds.sort()
if (cnt > evens.size && (cnt - evens.size) and 1 == 0 || evens.isEmpty() && cnt and 1 == 1) {
println("$cnt, ${cnt - evens.size}")
return 0
}
var sum = 0
var i = 0
while (i < cnt) {
if (odds.size > 1) {
val odd = odds.takeLast(2).sum()
if (evens.isEmpty()) {
i += 2
sum += odd
odds.removeAt(odds.lastIndex)
odds.removeAt(odds.lastIndex)
} else {
val even = evens.last()
if (even >= odd) {
sum += even
evens.removeAt(evens.lastIndex)
i++
} else {
i += 2
sum += odd
odds.removeAt(odds.lastIndex)
odds.removeAt(odds.lastIndex)
}
}
} else {
sum += evens.removeAt(evens.lastIndex)
i++
}
}
return sum
}
fun numColor(root: TreeNode?): Int {
val set = mutableSetOf<Int>()
traversal(root, set)
return set.size
}
private fun traversal(node: TreeNode?, colors: MutableSet<Int>) {
if (node == null) return
colors.add(node.`val`)
if (node.left != null) {
traversal(node.left, colors)
}
if (node.right != null) {
traversal(node.right, colors)
}
}
fun reformatNumber(number: String): String {//1694
val num = number.replace(" ", "").replace("-", "")
val count = num.length
val sb = StringBuilder()
val rem = num.length % 3
val firstN = if (rem == 0) count - 3 else if (rem == 1) count - 4 else count - 2
val lastM = count - firstN
for (i in 0 until firstN) {
sb.append(num[i])
if (i % 3 == 2) {
sb.append("-")
}
}
sb.append(num.takeLast(lastM))
if (lastM == 4) {
sb.insert(sb.length - 2, "-")
}
return sb.toString()
}
fun countStudents(students: IntArray, sandwiches: IntArray): Int {//1700
val counts = IntArray(2)
for (student in students) {
counts[student] += 1
}
val n = sandwiches.size
for (i in 0 until n) {
if (counts[sandwiches[i]] > 0) {
counts[sandwiches[i]] -= 1
} else {
return n - i
}
}
return 0
}
fun largestAltitude(gain: IntArray): Int {//1732
var max = 0
var h = 0
for (i in gain.indices) {
h += gain[i]
if (h > max) {
max = h
}
}
return max
}
fun totalMoney(n: Int): Int {//1716
val weeks = n / 7
val mod = n % 7
return 28 * weeks + 7 * weeks * (weeks - 1) / 2 + weeks * mod + mod * (mod + 1) / 2
}
private val memo = mutableMapOf<Int, Int>()
fun integerReplacement(n: Int): Int {//397
if (n == 1) return 0
if (!memo.containsKey(n)) {
if (n and 1 == 0) {
memo[n] = 1 + integerReplacement(n / 2)
} else {
memo[n] = 2 + min(integerReplacement(n / 2), integerReplacement(n / 2 + 1))
}
}
return memo[n]!!
}
fun mergeAlternately(word1: String, word2: String): String {//1768
val result = StringBuilder()
val S1 = word1.length
val S2 = word2.length
var i = 0
var j = 0
while (i < S1 && j < S2) {
if (i > j) {
result.append(word2[j])
j++
} else {
result.append(word1[i])
i++
}
}
while (i < S1) {
result.append(word1[i])
i++
}
while (j < S2) {
result.append(word2[j])
j++
}
return result.toString()
}
fun maxAscendingSum(nums: IntArray): Int {//1800
var maxSum = Int.MIN_VALUE
val S = nums.size
var i = 0
while (i < S) {
var subSum = nums[i]
var j = i + 1
while (j < S && nums[j - 1] < nums[j]) {
subSum += nums[j]
j++
}
if (maxSum < subSum) {
maxSum = subSum
}
i = j
}
return maxSum
}
fun secondHighest(s: String): Int {//1796
val digitals = s.filter { it.isDigit() }.toSortedSet().toList()
return if (digitals.size > 1) {
digitals[digitals.size - 2] - '0'
} else {
-1
}
}
/**
* 构建大顶堆的过程
*/
fun buildMaxHeap(tree: IntArray, p: Int, size: Int) {
//只有发生交换时才会继续循环, 以被交换的子结点作为父节点继续向下重构
var tmp = 0
var pp = p//完全二 X 树非叶节点的坐标,
var i = p * 2 + 1//非叶结点左子结点的坐标
while (i < size) {
//找到左右子结点中值相对较大的子结点
if (i + 1 < size && tree[i] < tree[i + 1]) {
i += 1 //右子结点值更大
}
//如果子结点中较大的结点值大于父结点, 则交换
if (tree[i] > tree[pp]) {
tmp = tree[i]
tree[i] = tree[pp]
tree[pp] = tmp
pp = i//被交换子结点作为父结点重复以上交换的过程
} else {//如果父结点比子节点值大, 直接退出即可, 因为是从底层调整到上层的
break
}
i = i * 2 + 1//处理被交换的子结点作为交结点之后的再交换
}
}
fun heapSort(tree: IntArray) {
//Step a: 将无序数组作为完全二 X 树处理, 构建大顶堆
val size = tree.size
//p指向父结点, 从最后一个非叶子结点, 调整到根结点
var p = size / 2 - 1//size / 2 -1 是完全二 X 树的最后一个非叶子结点
//将完全二 X 树的非叶节点从后往前进行调整交换, 构建最大堆
while (p >= 0) {
buildMaxHeap(tree, p, size)
p--
}
//大顶堆在构建完成后进行堆排序
//交换根和尾结点, 缩小堆尺寸, 重构大顶堆. 重复这个过程, 直到尺寸减少为1
var tmp = 0
var s = size
while (s > 1) {
//将头结点和最后结点进行交换, 此时最后的结点值即为最大值.
tmp = tree[0]
tree[0] = tree[s - 1]
tree[s - 1] = tmp
s--//缩小尺寸
buildMaxHeap(tree, 0, s)
}
}
} | 0 | Kotlin | 0 | 1 | 7cf372d9acb3274003bb782c51d608e5db6fa743 | 8,338 | Algorithms | MIT License |
src/Day02.kt | KorneliuszBarwinski | 572,677,168 | false | {"Kotlin": 6042} | fun main() {
fun calculatePointsFirstStrategy(values: List<String>) : Int {
val me = values[1]
val opponent = values[0]
var pointsForRound = 0
when (me) {
"X" -> {
pointsForRound += 1
if (opponent == "A") pointsForRound += 3
if (opponent == "C") pointsForRound += 6
}
"Y" -> {
pointsForRound += 2
if (opponent == "B") pointsForRound += 3
if (opponent == "A") pointsForRound += 6
}
"Z" -> {
pointsForRound += 3
if (opponent == "C") pointsForRound += 3
if (opponent == "B") pointsForRound += 6
}
}
return pointsForRound
}
fun calculatePointsSecondStrategy(values: List<String>) : Int {
val opponent = values[0]
val result = values[1]
var pointsForRound = 0
when (opponent){
"A" -> {
when (result){
"X" -> {
pointsForRound += 0
pointsForRound += 3
}
"Y" -> {
pointsForRound += 3
pointsForRound += 1
}
"Z" -> {
pointsForRound += 6
pointsForRound += 2
}
}
}
"B" -> {
when (result){
"X" -> {
pointsForRound += 0
pointsForRound += 1
}
"Y" -> {
pointsForRound += 3
pointsForRound += 2
}
"Z" -> {
pointsForRound += 6
pointsForRound += 3
}
}
}
"C" -> {
when (result){
"X" -> {
pointsForRound += 0
pointsForRound += 2
}
"Y" -> {
pointsForRound += 3
pointsForRound += 3
}
"Z" -> {
pointsForRound += 6
pointsForRound += 1
}
}
}
}
return pointsForRound
}
fun calculateTotalPointsFirstStrategy(input: String) = input.split("\r\n").sumOf { round -> calculatePointsFirstStrategy(round.split(" ")) }
fun calculateTotalPointsSecondStrategy(input: String) = input.split("\r\n").sumOf { round -> calculatePointsSecondStrategy(round.split(" ")) }
fun part1(input: String): Int {
return calculateTotalPointsFirstStrategy(input)
}
fun part2(input: String): Int {
return calculateTotalPointsSecondStrategy(input)
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d90175134e0c6482986fcf3c144282f189abc875 | 3,120 | AoC_2022 | Apache License 2.0 |
aoc2022/day22.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2022
import utils.InputRetrieval
fun main() {
Day22.execute()
}
object Day22 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: Pair<List<String>, List<Any>>): Int {
val (initialBoard, moves) = input
return processMoves(initialBoard, moves) { pos, board ->
when (pos.third) {
Direction.DOWN -> Triple(pos.first, board.map { it[pos.first] }.indexOfFirst { it != ' ' }, pos.third)
Direction.UP -> Triple(pos.first, board.map { it[pos.first] }.indexOfLast { it != ' ' }, pos.third)
Direction.RIGHT -> Triple(board[pos.second].indexOfFirst { it != ' ' }, pos.second, pos.third)
Direction.LEFT -> Triple(board[pos.second].indexOfLast { it != ' ' }, pos.second, pos.third)
}
}
}
private fun part2(input: Pair<List<String>, List<Any>>): Int {
val (initialBoard, moves) = input
return processMoves(initialBoard, moves) { _, _ -> TODO("Maybe I'll implement this next time") }
}
private fun processMoves(initialBoard: List<String>, moves: List<Any>, wrapFunction: (Triple<Int, Int, Direction>, List<String>) -> Triple<Int, Int, Direction>): Int {
// Pad board so we can do the wrap
val maxLength = initialBoard.maxOf { it.length }
val board = initialBoard.map { if (it.length < maxLength) it.padEnd(maxLength, ' ') else it }
var pos: Triple<Int, Int, Direction> = Triple(board.first().indexOfFirst { it == '.' }, 0, Direction.RIGHT)
moves.forEach { move ->
when (move) {
is Char -> pos = Triple(pos.first, pos.second, pos.third.rotate(move))
is Int -> {
for (i in 1..move) {
// board.printBoard(pos)
val prevPos = pos
pos = pos.applyDelta(board)
when (board[pos.second][pos.first]) {
'#' -> {
pos = prevPos
break // face a wall, skip this move
}
' ' -> {
// empty position, need to wrap
pos = wrapFunction(pos, board)
if (board[pos.second][pos.first] == '#') {
pos = prevPos
break // face a wall, skip this move
}
}
}
}
}
}
}
return pos.calcResult()
}
private fun List<String>.printBoard(pos: Triple<Int, Int, Direction>) {
for (y in this.indices) {
for (x in this[y].indices) {
if (x == pos.first && y == pos.second) {
print('X')
} else {
print(this[y][x])
}
}
println()
}
println("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-")
println("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-")
}
private fun Triple<Int, Int, Direction>.applyDelta(board: List<String>): Triple<Int, Int, Direction> {
val delta = when (this.third) {
Direction.DOWN -> 0 to 1
Direction.UP -> 0 to -1
Direction.RIGHT -> 1 to 0
Direction.LEFT -> -1 to 0
}
var newY = (this.second + delta.second) % board.size
if (newY < 0) {
newY = board.size - 1
}
var newX = (this.first + delta.first) % board[newY].length
if (newX < 0) {
newX = board[newY].length - 1
}
return Triple(newX, newY, this.third)
}
private fun Triple<Int, Int, Direction>.calcResult(): Int {
return ((this.first + 1) * 4) + ((this.second + 1) * 1000) + when (this.third) {
Direction.RIGHT -> 0
Direction.DOWN -> 1
Direction.LEFT -> 2
Direction.UP -> 3
}
}
enum class Direction {
DOWN, UP, RIGHT, LEFT;
fun rotate(rotation: Char): Direction {
return when (this) {
DOWN -> when (rotation) {
'R' -> LEFT
'L' -> RIGHT
else -> TODO("Invalid Option")
}
UP -> when (rotation) {
'R' -> RIGHT
'L' -> LEFT
else -> TODO("Invalid Option")
}
RIGHT -> when (rotation) {
'R' -> DOWN
'L' -> UP
else -> TODO("Invalid Option")
}
LEFT -> when (rotation) {
'R' -> UP
'L' -> DOWN
else -> TODO("Invalid Option")
}
}
}
}
fun readInput(): Pair<List<String>, List<Any>> {
val file = InputRetrieval.getFile(2022, 22).readLines()
val board = file.takeWhile { it.isNotEmpty() }
val parsedMoves = mutableListOf<Any>()
var number = ""
for (i in file.last()) {
if (i.isDigit()) {
number += i
} else {
if (number != "") {
parsedMoves.add(number.toInt())
number = ""
}
parsedMoves.add(i)
}
}
if (number != "") {
parsedMoves.add(number.toInt())
}
return board to parsedMoves
}
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 5,768 | Advent-Of-Code | MIT License |
src/main/kotlin/g2501_2600/s2597_the_number_of_beautiful_subsets/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2501_2600.s2597_the_number_of_beautiful_subsets
// #Medium #Array #Dynamic_Programming #Backtracking
// #2023_07_12_Time_194_ms_(100.00%)_Space_36.7_MB_(100.00%)
class Solution {
fun beautifulSubsets(nums: IntArray, k: Int): Int {
val map: MutableMap<Int, Int> = HashMap()
for (n in nums) {
map[n] = map.getOrDefault(n, 0) + 1
}
var res = 1
for (key in map.keys) {
if (!map.containsKey(key - k)) {
if (!map.containsKey(key + k)) {
res *= 1 shl map[key]!!
} else {
val freq: MutableList<Int?> = ArrayList()
var localKey = key
while (map.containsKey(localKey)) {
freq.add(map[localKey])
localKey += k
}
res *= helper(freq)
}
}
}
return res - 1
}
private fun helper(freq: List<Int?>): Int {
val n = freq.size
if (n == 1) {
return 1 shl freq[0]!!
}
val dp = IntArray(n)
dp[0] = (1 shl freq[0]!!) - 1
dp[1] = (1 shl freq[1]!!) - 1
if (n == 2) {
return dp[0] + dp[1] + 1
}
for (i in 2 until n) {
if (i > 2) {
dp[i - 2] += dp[i - 3]
}
dp[i] = (dp[i - 2] + 1) * ((1 shl freq[i]!!) - 1)
}
return dp[n - 1] + dp[n - 2] + dp[n - 3] + 1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,529 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/g1001_1100/s1027_longest_arithmetic_subsequence/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1001_1100.s1027_longest_arithmetic_subsequence
// #Medium #Array #Hash_Table #Dynamic_Programming #Binary_Search
// #2023_05_23_Time_330_ms_(100.00%)_Space_101.4_MB_(16.67%)
import java.util.Arrays
class Solution {
fun longestArithSeqLength(nums: IntArray): Int {
val max = maxElement(nums)
val min = minElement(nums)
val diff = max - min
val n = nums.size
val dp = Array(n) { IntArray(2 * diff + 2) }
for (d in dp) {
Arrays.fill(d, 1)
}
var ans = 0
for (i in 0 until n) {
for (j in i - 1 downTo 0) {
val difference = nums[i] - nums[j] + diff
val temp = dp[j][difference]
dp[i][difference] = Math.max(dp[i][difference], temp + 1)
if (ans < dp[i][difference]) {
ans = dp[i][difference]
}
}
}
return ans
}
private fun maxElement(arr: IntArray): Int {
var max = Int.MIN_VALUE
for (e in arr) {
if (max < e) {
max = e
}
}
return max
}
private fun minElement(arr: IntArray): Int {
var min = Int.MAX_VALUE
for (e in arr) {
if (min > e) {
min = e
}
}
return min
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,364 | LeetCode-in-Kotlin | MIT License |
src/Day11.kt | Cryosleeper | 572,977,188 | false | {"Kotlin": 43613} | fun main() {
fun part1(input: List<String>): Int {
val monkeys: Map<String, Monkey> = input.chunked(7) {
val monkey = Monkey(it)
monkey.id to monkey
}.toMap()
repeat(20) {
println("### ROUND $it BEGINS! ###\n")
monkeys.forEach { it.value.inspectAndThrowToOtherMonkeys(monkeys) }
}
return monkeys.values.map { it.thrownItems }.sortedByDescending { it }.run { get(0) * get(1) }
}
fun part2(input: List<String>): Long {
WorryModifierVeryWorried.reset()
val monkeys: Map<String, Monkey> = input.chunked(7) {
val monkey = Monkey(it, false)
monkey.id to monkey
}.toMap()
repeat(10000) {
println("### ROUND $it BEGINS! ###\n")
monkeys.forEach { it.value.inspectAndThrowToOtherMonkeys(monkeys) }
}
return monkeys.values.map { it.thrownItems }.sortedByDescending { it }.run { get(0).toLong() * get(1).toLong() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
private class Monkey(input: List<String>, unworry: Boolean = true) {
val id: String
private var _thrownItems = 0
val thrownItems: Int
get() = _thrownItems
private val items: MutableList<Item>
private val worryModifier: WorryModifier
private val strategy: (Item) -> String
init {
id = "\\d+".toRegex().find(input[0])!!.value
items = "\\d+".toRegex().findAll(input[1])
.mapIndexed { index, matchResult -> Item("$id $index", matchResult.value.toInt()) }.toMutableList()
val (first, second, operator) = readWorryModifiers(input[2])
val divider = "\\d+".toRegex().find(input[3])!!.value.toInt()
val trueMonkey = "\\d+".toRegex().find(input[4])!!.value
val falseMonkey = "\\d+".toRegex().find(input[5])!!.value
strategy = {
if (it.worryLevel % divider == 0) trueMonkey else falseMonkey
}
worryModifier = if (unworry) {
WorryModifierUnworried(first, second, operator)
} else {
WorryModifierVeryWorried(first, second, operator, divider)
}
}
private fun readWorryModifiers(input: String): Triple<Int?, Int?, WorryOperator> {
val worryModifications = input.substring(input.indexOf("=") + 2).split(" ")
val first: Int? = when (worryModifications[0]) {
"old" -> null
else -> worryModifications[0].toInt()
}
val second: Int? = when (worryModifications[2]) {
"old" -> null
else -> worryModifications[2].toInt()
}
val operator = WorryOperator.from(worryModifications[1])
return Triple(first, second, operator)
}
fun inspectAndThrowToOtherMonkeys(monkeys: Map<String, Monkey>) {
println("Monkey $id is inspecting items ${items.map { "(${it.id}, ${it.worryLevel})" }.joinToString(", ")}")
items.forEach { item ->
println("\tMonkey $id is inspecting item ${item.id} with worry level ${item.worryLevel}")
item.worryLevel = worryModifier.modify(item.worryLevel)
println("\t\tItem ${item.id} has worry level ${item.worryLevel} now")
monkeys[strategy(item).also { println("\t\tMonkey $id throws item ${item.id} to monkey $it") }]!!.receiveItem(
item
)
_thrownItems++
}
println("\tMonkey $id has thrown $thrownItems items")
println()
items.clear()
}
private fun receiveItem(item: Item) {
items.add(item)
}
}
private interface WorryModifier {
fun modify(currentWorry: Int): Int
}
private class WorryModifierUnworried(
private val first: Int?,
private val second: Int?,
private val operator: WorryOperator
) : WorryModifier {
override fun modify(currentWorry: Int): Int {
return ((operator.perform(first ?: currentWorry, second ?: currentWorry)) / 3).toInt()
}
}
private class WorryModifierVeryWorried(
private val first: Int?,
private val second: Int?,
private val operator: WorryOperator,
divider: Int
) : WorryModifier {
init {
WorryModifierVeryWorried.divider *= divider
}
override fun modify(currentWorry: Int): Int {
return ((operator.perform(first ?: currentWorry, second ?: currentWorry)) % divider).toInt()
}
companion object {
fun reset() {
divider = 1
}
private var divider: Long = 1
}
}
private enum class WorryOperator {
Add {
override fun perform(first: Int, second: Int) = first.toLong() + second.toLong()
},
Multiply {
override fun perform(first: Int, second: Int) = first.toLong() * second.toLong()
};
abstract fun perform(first: Int, second: Int): Long
companion object {
fun from(value: String) = when (value) {
"+" -> Add
"*" -> Multiply
else -> throw IllegalArgumentException("Unknown operator: $value")
}
}
}
private data class Item(val id: String, var worryLevel: Int) | 0 | Kotlin | 0 | 0 | a638356cda864b9e1799d72fa07d3482a5f2128e | 5,349 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/IsGraphBipartite.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
/**
* 785. Is Graph Bipartite?
* @see <a href="https://leetcode.com/problems/is-graph-bipartite/">Source</a>
*/
fun interface IsGraphBipartite {
fun isBipartite(graph: Array<IntArray>): Boolean
}
class IsGraphBipartiteDFS : IsGraphBipartite {
override fun isBipartite(graph: Array<IntArray>): Boolean {
val n: Int = graph.size
val colors = IntArray(n)
// This graph might be a disconnected graph. So check each unvisited node.
for (i in 0 until n) {
if (colors[i] == 0 && !validColor(graph, colors, 1, i)) {
return false
}
}
return true
}
private fun validColor(graph: Array<IntArray>, colors: IntArray, color: Int, node: Int): Boolean {
if (colors[node] != 0) {
return colors[node] == color
}
colors[node] = color
for (next in graph[node]) {
if (!validColor(graph, colors, -color, next)) {
return false
}
}
return true
}
}
class IsGraphBipartiteBFS : IsGraphBipartite {
override fun isBipartite(graph: Array<IntArray>): Boolean {
val len: Int = graph.size
val colors = IntArray(len)
for (i in 0 until len) {
if (colors[i] != 0) continue
val queue: Queue<Int> = LinkedList()
queue.offer(i)
colors[i] = 1 // Blue: 1; Red: -1.
while (queue.isNotEmpty()) {
val cur: Int = queue.poll()
for (next in graph[cur]) {
if (colors[next] == 0) { // If this node hasn't been colored;
colors[next] = -colors[cur] // Color it with a different color;
queue.offer(next)
} else if (colors[next] != -colors[cur]) {
// If it is colored and its color is different, return false
return false
}
}
}
}
return true
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,728 | kotlab | Apache License 2.0 |
Retos/Reto #1 - EL LENGUAJE HACKER [Fácil]/kotlin/robepe.kt | mouredev | 581,049,695 | false | {"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | import java.lang.StringBuilder
import java.util.Scanner
/*
* Escribe un programa que reciba un texto y transforme lenguaje natural a
* "lenguaje hacker" (conocido realmente como "leet" o "1337"). Este lenguaje
* se caracteriza por sustituir caracteres alfanuméricos.
* - Utiliza esta tabla (https://www.gamehouse.com/blog/leet-speak-cheat-sheet/)
* con el alfabeto y los números en "leet".
* (Usa la primera opción de cada transformación. Por ejemplo "4" para la "a")
*/
/*
* Variable global de tipo 'mapOf' para definir los valores 'leet' para cada carácter del abecedario
* natural y cada número.
*/
val abecedario = mapOf<Char, String>('a' to "4", 'b' to "I3", 'c' to "[", 'd' to ")",
'e' to "3", 'f' to "|=", 'g' to "&", 'h' to "#", 'i' to "1", 'j' to ",_|", 'k' to ">|",
'l' to "1", 'm' to "/\\/\\", 'n' to "^/", 'o' to "0", 'p' to "|*", 'q' to "(_,)", 'r' to "I2",
's' to "5", 't' to "7", 'u' to "(_)", 'v' to "\\/", 'w' to "\\/\\/", 'x' to "><", 'y' to "j",
'z' to "2", '0' to "o", '1' to "L", '2' to "R", '3' to "E", '4' to "A", '5' to "S", '6' to "b",
'7' to "T", '8' to "B", '9' to "g",)
/*
* Función destinada a traducir un 'String' formado con números/letras naturales
* a su versión en lenguaje 'leet'
*
* @param cadena: 'String' introducido por teclado
*/
fun naturalToLeet(cadena : String) {
// Instanciamos un objeto 'StringBuilder' para construir la cadena resultante posteriormente
val sb = StringBuilder()
// Bucle 'for' para recorrer cada caracter presente en la cadena proporcionada
for (caracter in cadena){
// Obtenemos y almacenamos el valor asignado para cada clave presente en la cadena en 'leetChar' (En caso de no existir, retornamos el valor introducido. Ej: 'ñ')
val leetChar = abecedario.getOrDefault(caracter.toLowerCase(), caracter.toString())
// Añadimos cada caracter leet obtenido al StringBuilder
sb.append(leetChar)
}
// Imprimimos por pantalla el resultante, convirtiendolo a 'String'
println(sb.toString())
}
/*
* Método de entrada al programa (Método Main)
*/
fun main() {
do {
val sc = Scanner(System.`in`)
println("\nIntroduzca una cadena en lenguaje natural: \n('*' Para finalizar el programa)")
val cadena = sc.nextLine()
naturalToLeet(cadena)
} while (!cadena.equals("*"))
println("\nHasta la vista :)")
}
| 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 2,424 | retos-programacion-2023 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day09.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
import utils.Coordinates
class Day09(val size: Int) {
var positions = Array(size) { Coordinates(0,0) }
val visited = mutableSetOf(tail)
private var head: Coordinates
get() = positions.first()
set(c) { positions[0] = c }
private val tail: Coordinates
get() = positions.last()
fun moveHead(dir: Char) {
when(dir) {
'U' -> head = head.dY(1)
'D' -> head = head.dY(-1)
'L' -> head = head.dX(-1)
'R' -> head = head.dX(1)
}
updateTail()
visited.add(tail)
}
private fun updateTail() {
repeat(size - 1) { updatePair(it) }
}
private fun Coordinates.follow(other: Coordinates): Coordinates {
if (isTouching(other)) return this
return this + (other - this).sign()
}
private fun updatePair(idx: Int) {
positions[idx + 1] = positions[idx + 1].follow(positions[idx])
}
}
fun main() {
val testInput = """R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2""".split("\n")
fun simulateSnake(input: List<String>, n: Int): Int {
return input.fold(Day09(n)) { state, command ->
val (dir, dist) = command.split(" ")
repeat(dist.toInt()) {
state.moveHead(dir[0])
}
state
}.visited.size
}
fun part1(input: List<String>): Int = simulateSnake(input, 2)
fun part2(input: List<String>): Int = simulateSnake(input, 10)
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 13)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 9).toList()
println(part1(puzzleInput))
println(part2(puzzleInput))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 1,810 | aoc-2022-kotlin | Apache License 2.0 |
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day03.kt | justinhorton | 573,614,839 | false | {"Kotlin": 39759, "Shell": 611} | package xyz.justinhorton.aoc2022
/**
* https://adventofcode.com/2022/day/3
*/
class Day03(override val input: String) : Day() {
override fun part1(): String {
return input.trim()
.split("\n")
.asSequence()
.map { it.chunked(it.length / 2) }
.map { (half1, half2) ->
val seen = Array(52) { false }
half1.forEach { ch -> seen[ch.priority() - 1] = true }
half2.first { ch -> seen[ch.priority() - 1] }
}
.sumOf { it.priority() }
.toString()
}
override fun part2(): String {
return input.trim()
.split("\n")
.asSequence()
.chunked(3)
.sumOf { group ->
val freqs = Array(52) { 0 }
group.forEach { str ->
val thisFreqs = Array(52) { 0 }
str.forEach { thisFreqs[it.priority() - 1]++ }
thisFreqs.withIndex().filter { it.value != 0 }.forEach { freqs[it.index]++ }
}
val foundIndex = freqs.withIndex().first { it.value == 3 }.index
foundIndex + 1 // as priority
}.toString()
}
private fun Char.priority(): Int {
val isLower = isLowerCase()
return if (isLower) code - 'a'.code + 1 else code - 'A'.code + 27
}
}
| 0 | Kotlin | 0 | 1 | bf5dd4b7df78d7357291c7ed8b90d1721de89e59 | 1,394 | adventofcode2022 | MIT License |
advent-of-code-2021/src/code/day4/Main.kt | Conor-Moran | 288,265,415 | false | {"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733} | package code.day4
import code.common.getOrPut
import java.io.File
fun main() {
doIt("Day 4 Part 1: Test Input", "src/code/day4/test.input", part1);
doIt("Day 4 Part 1: Real Input", "src/code/day4/part1.input", part1);
doIt("Day 4 Part 2: Test Input", "src/code/day4/test.input", part2);
doIt("Day 4 Part 2: Real Input", "src/code/day4/part1.input", part2);
}
fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Int) {
val lines = arrayListOf<String>()
File(input).forEachLine { lines.add(it) };
println(String.format("%s: Ans: %d", msg , calc(lines)));
}
val part1: (List<String>) -> Int = { lines ->
val parsed = parse(lines)
playPt1(parsed.first, parsed.second)
}
val part2: (List<String>) -> Int = { lines ->
val parsed = parse(lines)
playPt2(parsed.first, parsed.second)
}
val parse: (List<String>) -> Pair<List<Board>, List<Int>> = { lines ->
val firstLine = lines[0];
val callNums = firstLine.split(",").map { Integer.parseInt(it) }
val boards = mutableListOf<Board>()
var curBoardIndex = 0
var rowCounter = 0;
for (i in 1 until lines.size) {
if (!lines[i].isNullOrBlank()) {
rowCounter = if (rowCounter < 4) rowCounter + 1 else 0
val curBoard = boards.getOrPut(curBoardIndex, Board(5))
curBoard.parseRow(lines[i])
if (rowCounter == 0) {
curBoardIndex++
};
}
}
Pair<List<Board,>, List<Int>>(boards, callNums)
}
val playPt1: (List<Board>, List<Int>) -> Int = { boards, callNums ->
var out: Pair<Board?, Int> = play(boards, callNums, true);
if (out.first != null) out.first!!.sumUnmarked() * out.second else 0
}
val playPt2: (List<Board>, List<Int>) -> Int = { boards, callNums ->
var out: Pair<Board?, Int> = play(boards, callNums, false);
if (out.first != null) out.first!!.sumUnmarked() * out.second else 0
}
fun play(boards: List<Board>, callNums: List<Int>, firstWin: Boolean): Pair<Board?, Int> {
var winningBoard: Board? = null;
var winningNum: Int? = null;
loop@ for (num in callNums) {
for (board in boards) {
board.sendNum(num)
if (!board.isCounted && board.isWinning()) {
winningBoard = board;
winningNum = num
board.setCounted()
if (firstWin) break@loop
}
}
}
return Pair(winningBoard, winningNum ?: 0)
}
class Cell(val intValue: Int, var marked: Boolean) {
fun mark() {
this.marked = true;
}
override fun toString(): String {
return "Cell($intValue, $marked)"
}
fun sendNum(num: Int) {
if (intValue == num) {
mark()
}
}
}
class Seq(data: List<Cell>): ArrayList<Cell>() {
fun sendNum(num: Int) {
for (cell in this) {
cell.sendNum(num)
}
}
init {
this.addAll(data)
}
fun isWinning(): Boolean {
var isWinning = true;
for (cell in this) {
if (!cell.marked) {
isWinning = false;
break;
}
}
return isWinning
}
}
class Board(size: Int): ArrayList<Seq>(size) {
var isFinished = false;
var isCounted = false;
var winNum: Int? = null;
fun parseRow(line: String) {
this.add(Seq(line.trim().split(Regex(" +")).map { Cell(Integer.parseInt(it), false) }))
}
private fun fill() {
for (i in 1 .. 5) {
this.add(Seq(MutableList(5) { Cell(0, false) }))
}
}
fun sendNum(num: Int) {
if (!isFinished) {
for (row in this) {
row.sendNum(num)
}
if (isWinning()) {
isFinished = true;
winNum = num
}
}
}
fun setCounted() {
isCounted = true
}
fun isWinning(): Boolean {
return isRowsWinning() || trans().isRowsWinning()
}
private fun isRowsWinning(): Boolean {
var isWinning = false;
for (row in this) {
if (row.isWinning()) {
isWinning = true;
break;
}
}
return isWinning
}
fun trans(): Board {
val transpose = Board(5)
transpose.fill()
for (i in 0 until size) {
for (j in 0 until size) {
transpose.set(j, i, this[i][j])
}
}
return transpose;
}
private fun set(i: Int, j: Int, cell: Cell) {
this[i][j] = cell;
}
fun sumUnmarked(): Int {
var sum = 0;
for(i in 0 until 5) {
for(j in 0 until 5) {
val cell = this[i][j]
if (!cell.marked) {
sum += cell.intValue
}
}
}
return sum
}
}
| 0 | Kotlin | 0 | 0 | ec8bcc6257a171afb2ff3a732704b3e7768483be | 4,903 | misc-dev | MIT License |
src/Day17.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | import kotlin.math.max
private const val EMPTY = 0
private const val BLOCKED = 1
private val DOWN = 0 to -1
private val SHIFT = mapOf('>' to (1 to 0), '<' to (-1 to 0))
private val MINUS = listOf(0 to 0, 1 to 0, 2 to 0, 3 to 0)
private val PLUS = listOf(0 to 1, 1 to 1, 1 to 0, 1 to 2, 2 to 1)
private val CORNER = listOf(0 to 0, 1 to 0, 2 to 0, 2 to 1, 2 to 2)
private val STAND = listOf(0 to 0, 0 to 1, 0 to 2, 0 to 3)
private val SQUARE = listOf(0 to 0, 0 to 1, 1 to 1, 1 to 0)
private val SHAPES = listOf(MINUS, PLUS, CORNER, STAND, SQUARE)
private class Field2(private val wind: String, val maxY: Int = 2022 * 4) {
enum class MoveResultState { MOVED, BLOCKED, FREE }
inner class MoveResult(val state: MoveResultState, val newPoint: Pair<Int, Int>? = null)
inner class ShapeMoveResult(val state: MoveResultState, val newShape: List<Pair<Int, Int>>? = null)
val minY = 0
val minX = -1
val maxX = 7
val field = MutableList(maxX - minX + 1) { MutableList(maxY - minY + 1) { EMPTY } }
var currentMaxHeight = 0
var fallen = 0
var windInd = 0
init {
for (x in minX..maxX) {
field[x - minX][0] = BLOCKED
}
for (y in minY..maxY) {
field[0][y] = BLOCKED
field[8][y] = BLOCKED
}
}
private fun canMove(from: Pair<Int, Int>, dir: Pair<Int, Int>): MoveResult {
val newPoint = from + dir
if (field[newPoint] == BLOCKED) return MoveResult(MoveResultState.BLOCKED)
return MoveResult(MoveResultState.MOVED, newPoint)
}
private fun shapeCanMove(from: List<Pair<Int, Int>>, dir: Pair<Int, Int>): ShapeMoveResult {
return ShapeMoveResult(MoveResultState.MOVED, from.map {this.canMove(it, dir).newPoint ?: return ShapeMoveResult(MoveResultState.BLOCKED)})
}
fun dropNextForm() {
var figure = SHAPES[fallen % SHAPES.size].map {(x, y) -> x + 3 to currentMaxHeight + y + 3 + 1}
figure.forEach { assert(field[it] != BLOCKED); field[it] = BLOCKED }
while (true) {
figure.forEach { assert(field[it] == BLOCKED); field[it] = EMPTY }
val nextMove = shapeCanMove(figure, SHIFT[wind[windInd]]!!)
windInd = (windInd + 1) % wind.length
figure = nextMove.newShape ?: figure
val afterDown = shapeCanMove(figure, DOWN)
if (afterDown.state == MoveResultState.BLOCKED) {
figure.forEach { assert(field[it] != BLOCKED); field[it] = BLOCKED }
currentMaxHeight = max(currentMaxHeight, figure.maxOf { (_, y) -> y })
break
}
figure = afterDown.newShape!!
figure.forEach { assert(field[it] != BLOCKED); field[it] = BLOCKED }
}
fallen++
}
}
fun main() {
fun part1(input: List<String>): Int {
val field = Field2(input[0])
repeat(2022) {
field.dropNextForm()
}
return field.currentMaxHeight
}
fun findRepetition(numbers: List<Long>): Int {
for (k in 1..(numbers.size / 3)) {
var success = true
for (pos in numbers.lastIndex downTo(2*k)) {
if (numbers[pos] != numbers[pos - k]) {
success = false
break
}
}
if (success) {
return k
}
}
return -1
}
fun part2(input: List<String>): Long {
val ROCKS = 1000000000000
val iterationsAmount = input[0].length * 2
val innerLen = 2 * 3 * 5 * 7// * SHAPES.size
val tempResults = mutableListOf<Long>()
val field30k = Field2(input[0], innerLen * 4 * iterationsAmount)
var prevHeight = 0
repeat(iterationsAmount) {
repeat(innerLen) {
field30k.dropNextForm()
}
tempResults.add((field30k.currentMaxHeight - prevHeight).toLong())
prevHeight = field30k.currentMaxHeight
}
val cycleLen = findRepetition(tempResults)
if (cycleLen == -1) {
error("Cry")
}
val cycleHeight = tempResults.takeLast(cycleLen).sum()
val dropsToCycle = (cycleLen * innerLen).toLong()
val remainder = ROCKS % dropsToCycle
val fieldLast = Field2(input[0], (remainder + 3 * dropsToCycle).toInt() * 4)
repeat((remainder + 3 * dropsToCycle).toInt()) {
fieldLast.dropNextForm()
}
return fieldLast.currentMaxHeight.toLong() + cycleHeight * (ROCKS / dropsToCycle - 3)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day17_test")
check(part1(testInput) == 3068)
check(part2(testInput) == 1514285714288)
val input = readInput("Day17")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 4,861 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day07.kt | jamOne- | 573,851,509 | false | {"Kotlin": 20355} | import java.util.ArrayDeque
sealed class Entity {
class File(val name: String, val size: Int): Entity()
class Folder(val name: String, val parent: Folder?): Entity() {
val children = mutableMapOf<String, Entity>()
var size = 0
}
}
fun main() {
fun buildFileSystem(terminal: List<String>): Entity.Folder {
fun fixFolderSizes(folder: Entity.Folder): Int {
var size = 0
for (entity in folder.children.values) {
if (entity is Entity.File) {
size += entity.size
} else {
size += fixFolderSizes(entity as Entity.Folder)
}
}
folder.size = size
return size
}
val root = Entity.Folder("/", null)
var currentFolder = root
for (line in terminal) {
if (line == "$ cd /") {
currentFolder = root
} else if (line == "$ cd ..") {
currentFolder = currentFolder.parent!!
} else if (line.startsWith("$ cd")) {
val name = line.split(" ").last()
currentFolder = currentFolder.children[name] as Entity.Folder
} else if (line == "$ ls") {
// Do nothing.
} else if (line.startsWith("dir")) {
val dirName = line.split(" ").last()
val folder = Entity.Folder(dirName, currentFolder)
currentFolder.children[dirName] = folder
} else {
val (size, fileName) = line.split(" ")
val file = Entity.File(fileName, size.toInt())
currentFolder.children[fileName] = file
}
}
fixFolderSizes(root)
return root
}
fun visitAllFolders(folder: Entity.Folder, visitor: (folder: Entity.Folder) -> Unit) {
visitor(folder)
for (entity in folder.children.values) {
if (entity is Entity.Folder) {
visitAllFolders(entity, visitor)
}
}
}
fun part1(input: List<String>): Int {
val root = buildFileSystem(input)
var result = 0
visitAllFolders(root) { folder -> if (folder.size <= 100000) result += folder.size }
return result
}
fun part2(input: List<String>): Int {
val root = buildFileSystem(input)
val needToFree = 30000000 - (70000000 - root.size)
var result = Int.MAX_VALUE
visitAllFolders(root) { folder -> if (folder.size >= needToFree) result = Math.min(result, folder.size) }
return result
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 77795045bc8e800190f00cd2051fe93eebad2aec | 2,840 | adventofcode2022 | Apache License 2.0 |
src/Day16.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Int {
val releaseRates = parseReleaseRates(input)
val directNeighbors = parseDirectNeighbors(input)
val travelTimes = getTravelTimesBetweenValves(releaseRates.keys, directNeighbors)
val openableValves = releaseRates.filterValues { it > 0 }.keys.toMutableSet()
fun maxReleasablePressure(
startValve: ValveName,
timeLeft: Int,
releasedPressure: Int,
openableValves: Set<ValveName>
): Int {
if (openableValves.isEmpty()) return releasedPressure
return openableValves.maxOf { nextValve ->
val releaseRate = releaseRates[nextValve]!!
val travelTime = travelTimes[startValve]!![nextValve]!!
val newTimeLeft = timeLeft - travelTime - 1
if (newTimeLeft > 0) {
maxReleasablePressure(
nextValve,
newTimeLeft,
releasedPressure + newTimeLeft * releaseRate,
openableValves - nextValve)
} else {
releasedPressure
}
}
}
return maxReleasablePressure("AA", 30, 0, openableValves)
}
fun part2(input: List<String>): Int {
val releaseRates = parseReleaseRates(input)
val directNeighbors = parseDirectNeighbors(input)
val travelTimes = getTravelTimesBetweenValves(releaseRates.keys, directNeighbors)
val openableValves = releaseRates.filterValues { it > 0 }.keys.toMutableSet()
fun maxReleasablePressure(
startValve: ValveName,
startValve2: ValveName,
timeLeft: Int,
timeLeft2: Int,
releasedPressure: Int,
openableValves: Set<ValveName>
): Int {
if (openableValves.isEmpty()) return releasedPressure
if (openableValves.size == 1) {
val nextValve = openableValves.first()
val releaseRate = releaseRates[nextValve]!!
val travelTime = travelTimes[startValve]!![nextValve]!!
val travelTime2 = travelTimes[startValve2]!![nextValve]!!
val newTimeLeft = timeLeft - travelTime - 1
val newTimeLeft2 = timeLeft2 - travelTime2 - 1
return buildList {
add(releasedPressure)
if (newTimeLeft > 0) add(releasedPressure + newTimeLeft * releaseRate)
if (newTimeLeft2 > 0) add(releasedPressure + newTimeLeft2 * releaseRate)
}
.max()
}
return openableValves.maxOf { nextValve ->
(openableValves - nextValve).maxOf { nextValve2 ->
val releaseRate = releaseRates[nextValve]!!
val releaseRate2 = releaseRates[nextValve2]!!
val travelTime = travelTimes[startValve]!![nextValve]!!
val travelTime2 = travelTimes[startValve2]!![nextValve2]!!
val newTimeLeft = (timeLeft - travelTime - 1).coerceAtLeast(0)
val newTimeLeft2 = (timeLeft2 - travelTime2 - 1).coerceAtLeast(0)
if (newTimeLeft > 0 && newTimeLeft2 > 0) {
maxReleasablePressure(
nextValve,
nextValve2,
newTimeLeft,
newTimeLeft2,
releasedPressure + newTimeLeft * releaseRate + newTimeLeft2 * releaseRate2,
(openableValves - nextValve) - nextValve2)
} else {
releasedPressure + newTimeLeft * releaseRate + newTimeLeft2 * releaseRate2
}
}
}
}
return maxReleasablePressure("AA", "AA", 26, 26, 0, openableValves)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
assertEquals(1651, part1(testInput))
assertEquals(1707, part2(testInput))
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
private val linePattern =
Regex("Valve ([A-Z]{2}) has flow rate=(\\d+); tunnels? leads? to valves? ([A-Z,\\s]+)")
private fun parseReleaseRates(input: List<String>): Map<ValveName, Int> {
return input.associate { line ->
val (name, releaseRate, _) = linePattern.matchEntire(line)!!.groupValues.drop(1)
name to releaseRate.toInt()
}
}
private fun parseDirectNeighbors(input: List<String>): Map<ValveName, List<ValveName>> {
return input.associate { line ->
val (name, _, neighbors) = linePattern.matchEntire(line)!!.groupValues.drop(1)
name to neighbors.split(", ")
}
}
private fun getTravelTimesBetweenValves(
valves: Set<ValveName>,
neighbors: Map<ValveName, List<ValveName>>
): Map<ValveName, Map<ValveName, Int>> {
class Node(val name: String, var distanceFromStart: Int = Int.MAX_VALUE) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Node) return false
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
}
fun dijkstra(
start: ValveName,
target: ValveName,
): Int {
val visitedNodes = mutableSetOf<Node>()
val unvisitedNodes = mutableSetOf<Node>()
var currentNode = Node(start, 0)
while (true) {
for (nodeName in neighbors[currentNode.name]!!) {
val node = Node(nodeName)
if (node !in visitedNodes) {
unvisitedNodes.add(node)
val tentativeDistance = currentNode.distanceFromStart + 1
node.distanceFromStart = Integer.min(tentativeDistance, node.distanceFromStart)
}
}
visitedNodes.add(currentNode)
unvisitedNodes.remove(currentNode)
if (currentNode.name == target) {
break
}
val nodeWithLowestDistance = unvisitedNodes.minByOrNull { it.distanceFromStart }
if (nodeWithLowestDistance != null) {
currentNode = nodeWithLowestDistance
} else {
break
}
}
return visitedNodes.first { it.name == target }.distanceFromStart
}
return valves.associateWith { start ->
(valves - start).associateWith { target -> dijkstra(start, target) }
}
}
typealias ValveName = String
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 6,005 | aoc2022 | Apache License 2.0 |
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12912.kt | boris920308 | 618,428,844 | false | {"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407} | package main.kotlin.programmers.lv01
/**
*
* https://school.programmers.co.kr/learn/courses/30/lessons/12912
*
* 두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.
* 예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.
*
* 제한 조건
* a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요.
* a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다.
* a와 b의 대소관계는 정해져있지 않습니다.
* 입출력 예
* a b return
* 3 5 12
* 3 3 3
* 5 3 12
*
*/
fun main() {
solution(3, 5)
solution(3, 3)
solution(5, 3)
}
private fun solution(a: Int, b: Int): Long {
var answer: Long = 0
if (a > b) {
for (i in b..a) {
answer += i
}
} else {
for (i in a..b) {
answer += i
}
}
return answer
}
private fun secondSolution(a: Int, b: Int): Long {
val start : Long = (if(a>b) b else a).toLong()
val end : Long = (if(a>b) a else b).toLong()
return (start..end).sum()
} | 1 | Kotlin | 1 | 2 | 88814681f7ded76e8aa0fa7b85fe472769e760b4 | 1,130 | HoOne | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem241/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem241
/**
* LeetCode page: [241. Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/);
*
* TODO : Analyze the complexity of solution and may relate to the Catalan Numbers ([See Ref](https://people.math.sc.edu/howard/Classes/554b/catalan.pdf));
*/
class Solution {
private val operator = charArrayOf('+', '-', '*')
/* Complexity:
* Time O(???) and Space O(???);
*/
fun diffWaysToCompute(expression: String): List<Int> {
val memorizedIndexRangeResult = hashMapOf<IntRange, List<Int>>()
return diffWaysToComputeSubExpression(
indexRange = expression.indices,
fullExpression = expression,
memorizedResults = memorizedIndexRangeResult
)
}
private fun diffWaysToComputeSubExpression(
indexRange: IntRange,
fullExpression: String,
memorizedResults: MutableMap<IntRange, List<Int>>
): List<Int> {
return memorizedResults.getOrPut(indexRange) {
val result = mutableListOf<Int>()
var noOperator = true
for (index in indexRange) {
val char = fullExpression[index]
if (char !in operator) continue
noOperator = false
val leftRange = indexRange.first until index
val leftResult = diffWaysToComputeSubExpression(leftRange, fullExpression, memorizedResults)
val rightRange = index + 1..indexRange.last
val rightResult = diffWaysToComputeSubExpression(rightRange, fullExpression, memorizedResults)
val operation = getOperation(char)
val currResult = operate(leftResult, rightResult, operation)
result.addAll(currResult)
}
if (noOperator) result.add(fullExpression.slice(indexRange).toInt())
result
}
}
private fun getOperation(operatorChar: Char): (int1: Int, int2: Int) -> Int {
return when (operatorChar) {
'+' -> { int1: Int, int2: Int -> int1 + int2 }
'-' -> { int1: Int, int2: Int -> int1 - int2 }
'*' -> { int1: Int, int2: Int -> int1 * int2 }
else -> throw IllegalArgumentException()
}
}
private fun operate(left: List<Int>, right: List<Int>, operation: (int1: Int, int2: Int) -> Int): List<Int> {
val result = mutableListOf<Int>()
for (int1 in left) {
for (int2 in right) {
result.add(operation(int1, int2))
}
}
return result
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,644 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day03.kt | vitind | 578,020,578 | false | {"Kotlin": 60987} |
fun main() {
val ARRAY_SIZE = 52
val ARRAY_OFFSET = 26
fun getIndexedCharArray(s: String) : Array<Int> {
val indexedCharArray = Array<Int>(ARRAY_SIZE){0}
s.forEach {
val index = if (it.isLowerCase()) {
it.minus('a')
} else { // is upper case
it.minus('A') + ARRAY_OFFSET
}
indexedCharArray[index] += 1
}
return indexedCharArray
}
fun part1(input: List<String>): Int {
var totalPriority = 0
input.forEach { line ->
val halfLength = line.length / 2
val firstCompartment = line.slice(0 until halfLength)
val secondCompartment = line.slice(halfLength until line.length)
val firstCount = getIndexedCharArray(firstCompartment)
val secondCount = getIndexedCharArray(secondCompartment)
for (index in 0 until ARRAY_SIZE) {
if ((firstCount[index] > 0) && (secondCount[index] > 0)) {
totalPriority += (index + 1)
}
}
}
return totalPriority
}
fun part2(input: List<String>): Int {
var totalPriority = 0
val LINE_GROUPS = 3
for (index in input.indices step LINE_GROUPS) {
val firstCount = getIndexedCharArray(input[index])
val secondCount = getIndexedCharArray(input[index + 1])
val thirdCount = getIndexedCharArray(input[index + 2])
for (countIndex in 0 until ARRAY_SIZE) {
if ((firstCount[countIndex] > 0) && (secondCount[countIndex] > 0) && (thirdCount[countIndex] > 0)) {
totalPriority += (countIndex + 1)
}
}
}
return totalPriority
}
val input = readInput("Day03")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | 2698c65af0acd1fce51525737ab50f225d6502d1 | 1,888 | aoc2022 | Apache License 2.0 |
2021/src/main/kotlin/day10.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import java.math.BigDecimal
fun main() {
Day10.run()
}
object Day10 : Solution<List<String>>() {
override val name = "day10"
override val parser = Parser.lines
fun validate(str: String): Char? {
val stack = ArrayDeque<Char>()
for (char in str) {
when (char) {
'(', '[', '{', '<' -> stack.add(char)
else -> {
if (stack.removeLast() != char.opening) {
return char
}
}
}
}
// we still might have chars in the stack here
return null
}
fun complete(str: String): BigDecimal {
val stack = ArrayDeque<Char>()
for (char in str) {
when (char) {
'(', '[', '{', '<' -> stack.add(char)
else -> {
if (stack.removeLast() != char.opening) {
return BigDecimal(0)
}
}
}
}
var completionPts = BigDecimal(0)
while (stack.isNotEmpty()) {
val char = stack.removeLast()
completionPts *= BigDecimal(5)
completionPts += BigDecimal(char.completionPts)
}
return completionPts
}
val Char.opening: Char get() =
when (this) {
')' -> '('
']' -> '['
'}' -> '{'
'>' -> '<'
else -> 'a'
}
val Char.score: Int get() =
when (this) {
')' -> 3
']' -> 57
'}' -> 1197
'>' -> 25137
else -> 0
}
val Char.completionPts: Int get() =
when (this) {
'(' -> 1
'[' -> 2
'{' -> 3
'<' -> 4
else -> 0
}
override fun part1(input: List<String>): Int {
return input.mapNotNull { validate(it) }.sumOf { it.score }
}
override fun part2(input: List<String>): BigDecimal {
val nums = input.map { complete(it) }.filter { it > BigDecimal(0) }.sorted()
return nums[nums.size / 2]
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,833 | aoc_kotlin | MIT License |
src/Day03.kt | JaydenPease | 574,590,496 | false | {"Kotlin": 11645} | fun main() {
// fun part1(input: List<String>): Int {
// return input.size
// }
//
// fun part2(input: List<String>): Int {
// return input.size
// }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
//println(Day03_part1(testInput))
//println(Day03_part2(testInput))
val input = readInput("Day03")
//println(Day03_part1(input))
println(Day03_part2(input))
}
fun Day03_part1(input : List<String>) : Int {
val alphabet: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var firstCompartment: String = ""
var secondCompartment: String = ""
var totalPriority: Int = 0
for(i in input.indices) {
firstCompartment = input[i].substring(0, (input[i].length / 2))
secondCompartment = input[i].substring((input[i].length / 2))
for (j in firstCompartment.indices) {
if (secondCompartment.indexOf(firstCompartment.substring(j, j + 1)) != -1) {
totalPriority += alphabet.indexOf(firstCompartment.substring(j, j + 1), 0, false) + 1
break
}
}
}
return totalPriority
}
fun Day03_part2(input : List<String>) : Int {
val alphabet: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var totalPriority: Int = 0
for(i in input.indices) {
if(i % 3 != 0) {continue}
for(j in input[i].indices) {
if(input[i+1].indexOf(input[i].substring(j, j+1)) != -1 && input[i+2].indexOf(input[i].substring(j, j+1)) != -1) {
totalPriority += alphabet.indexOf(input[i].substring(j, j+1)) + 1
break
}
}
}
return totalPriority
}
| 0 | Kotlin | 0 | 0 | 0a5fa22b3653c4b44a716927e2293fc4b2ed9eb7 | 1,777 | AdventOfCode-2022 | Apache License 2.0 |
src/main/kotlin/days/Day04.kt | irmakcelebi | 573,174,392 | false | {"Kotlin": 6258} | package days
import Day
fun main() {
val day = Day04()
day.test1(2)
day.test2(4)
day.run()
}
class Day04 : Day() {
override fun solve1(lines: List<String>) = lines
.map { it.split(',') }
.count { (elf1, elf2) ->
val section1 = Section.from(elf1)
val section2 = Section.from(elf2)
section2.isCoveredBy(section1) || section1.isCoveredBy(section2)
}
override fun solve2(lines: List<String>) = lines
.map { it.split(',') }
.count { (elf1, elf2) ->
val section1 = Section.from(elf1)
val section2 = Section.from(elf2)
section1.isOverlappingWith(section2)
}
}
class Section(private val start: Int, private val to: Int) {
fun isCoveredBy(other: Section): Boolean {
return other.start <= this.start && other.to >= this.to
}
fun isOverlappingWith(other: Section) = other.toList().intersect(this.toList()).isNotEmpty()
private fun toList(): List<Int> = (start..to).toList()
companion object {
fun from(elf: String): Section {
val startEnd = elf.split('-').map { it.toInt() }
return Section(startEnd[0], startEnd[1])
}
}
}
| 0 | Kotlin | 0 | 0 | fe20c7fd574c505423a9d9be449a42427775ec76 | 1,251 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/days/Day2.kt | teunw | 573,164,590 | false | {"Kotlin": 20073} | package days
class Day2 : Day(2) {
private val wins = mapOf(
0 to 1,
1 to 2,
2 to 0
)
private fun getMatchResultPartOne(opponent: Int, me: Int): Int {
if (opponent == me) {
return 3
}
val didIWin = wins[opponent] == me
return if (didIWin) 6 else 0
}
private fun getChoicePartTwo(opponent: Int, outcome: Int) =
when (outcome) {
0 -> wins.entries.find { it.value == opponent }!!.key
1 -> opponent + 3
2 -> wins[opponent]!! + 6
else -> throw Exception("Invalid move")
} + 1
override fun partOne(): Int {
return inputList
.sumOf {
val chars = it.split(' ').map { it[0] }
val opponent = chars[0].minus('A')
val me = chars[1].minus('X')
getMatchResultPartOne(opponent, me) + (me + 1)
}
}
override fun partTwo(): Int {
return inputList
.sumOf { line ->
val chars = line.split(' ').map { it[0] }
val opponent = chars[0].minus('A')
val outcome = chars[1].minus('X')
getChoicePartTwo(opponent, outcome)
}
}
}
| 0 | Kotlin | 0 | 0 | 149219285efdb1a4d2edc306cc449cce19250e85 | 1,265 | advent-of-code-22 | Creative Commons Zero v1.0 Universal |
src/Day05.kt | A55enz10 | 573,364,112 | false | {"Kotlin": 15119} | fun main() {
fun part1(input: List<String>): String {
val supplies = getInitialStacks(input)
val instructions = getInstructions(input)
instructions.forEach {
val quantity = it[0]
val fromStack = it[1]-1
val toStack = it[2]-1
for (i in 1..quantity) {
supplies[toStack].add(supplies[fromStack].removeLast())
}
}
var ret = ""
supplies.forEach {
ret += it.removeLast()
}
return ret
}
fun part2(input: List<String>): String {
val supplies = getInitialStacks(input)
val instructions = getInstructions(input)
instructions.forEach {
val quantity = it[0]
val fromStack = it[1]-1
val toStack = it[2]-1
val buffer = ArrayDeque<String>()
for (i in 1..quantity) {
buffer.add(supplies[fromStack].removeLast())
}
for (i in 1..quantity) {
supplies[toStack].add(buffer.removeLast())
}
}
var ret = ""
supplies.forEach {
ret += it.removeLast()
}
return ret
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
fun getInitialStacks(input: List<String>): List<ArrayDeque<String>> {
val stackBlock =
input.subList(0, input.indexOf("") - 1)
.map{ row ->
row.chunked(4).map {
it.trim().replace("[", "").replace("]", "")
}
}
val stackSize = input[input.indexOf("")-1].replace(" ", "").length
val stacks = List(stackSize) {ArrayDeque<String>()}
for (i in stackBlock.size - 1 downTo 0) {
stackBlock[i].forEachIndexed { j, s ->
if (s.isNotEmpty()) stacks[j].add(s)
}
}
return stacks
}
fun getInstructions(input: List<String>): List<List<Int>> {
return input
.subList(input.indexOf("") + 1, input.size)
.map { row ->
row.replace("move ", "")
.replace("from ", "")
.replace("to ", "")
.split(" ")
.map { it.toInt() }
}
} | 0 | Kotlin | 0 | 1 | 8627efc194d281a0e9c328eb6e0b5f401b759c6c | 2,292 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/io/github/lunarwatcher/aoc/day8/Day8.kt | LunarWatcher | 160,042,659 | false | null | package io.github.lunarwatcher.aoc.day8
import io.github.lunarwatcher.aoc.commons.readFile
import java.util.*
data class Node(val children: List<Node>, val metadata: List<Int>){
val childCount: Int
get() = children.size
val hasChildren: Boolean
get() = children.size > 0
val hasMetadata: Boolean
get() = metadata.size > 0
}
fun day8part1processor(raw: List<String>) : Int{
val stack = loadStack(raw);
/*
Header (childrenCount, metadataCount) => children if childrenCount > 0 => metadata if metadataCount > 0
*/
val nodes = parseNodes(stack);
return nodes.map { sumNodePart1(it) }.sum()
}
fun day8part2processor(raw: List<String>) : Int {
val stack = loadStack(raw);
val nodes = parseNodes(stack)
return nodes.map { sumNodePart2(it) }.sum()
}
fun loadStack(raw: List<String>) = LinkedList<Int>().also {
raw.first().split(" ")
.forEach {str ->
it.add(str.toInt())
}
if(it.size == 0)
throw RuntimeException();
}
fun sumNodePart1(node: Node) : Int {
var sum = 0;
sum += node.metadata.sum()
if(node.children.isNotEmpty()){
for(child in node.children){
sum += sumNodePart1(child)
}
}
return sum;
}
fun sumNodePart2(node: Node) : Int {
var sum = 0;
if(node.hasChildren && node.hasMetadata){
val children = node.children;
val metadata = node.metadata;
for(index in metadata){
if(children.size <= index - 1)
continue;
val child = children[index - 1]
if(child.hasMetadata && child.hasChildren)
sum += sumNodePart2(child)
else sum += child.metadata.sum();
}
}
return sum;
}
fun parseNodes(stack: LinkedList<Int>, nested: Boolean = false) : List<Node> {
val baseNodes = mutableListOf<Node>()
while(stack.size > 0){
val childrenCount = stack.pollFirst()
val metadataCount = stack.pollFirst()
val children = if(childrenCount == 0) listOf<Node>() else {
val l = mutableListOf<Node>()
for(i in 0 until childrenCount) {
l.addAll(parseNodes(stack, true));
}
l
}
val metadata = if(metadataCount == 0) listOf<Int>() else {
val l = mutableListOf<Int>()
for(i in 0 until metadataCount){
l.add(stack.pollFirst());
}
l;
}
baseNodes.add(Node(children, metadata))
if(nested){
return baseNodes
}
}
return baseNodes;
}
fun day8(part: Boolean){
val data = readFile("day8.txt");
val res = if(!part) day8part1processor(data) else day8part2processor(data)
println(res);
} | 0 | Kotlin | 0 | 1 | 99f9b05521b270366c2f5ace2e28aa4d263594e4 | 2,790 | AoC-2018 | MIT License |
src/com/github/crunchynomnom/aoc2022/puzzles/Day03.kt | CrunchyNomNom | 573,394,553 | false | {"Kotlin": 14290, "Shell": 518} | package com.github.crunchynomnom.aoc2022.puzzles
import Puzzle
import java.io.File
class Day03 : Puzzle() {
override fun part1(input: File) {
println(input.readLines().sumOf { getPrio(findMatch(it)) })
}
override fun part2(input: File) {
println(input.readLines().chunked(3).sumOf { getPrio(getCommonFor3(it)) })
}
// returns common letter
private fun findMatch(backpack: String): Char {
val existsOnLeft = BooleanArray(53) { _ -> false}
for (i in 0 until backpack.length/2) {
existsOnLeft[getPrio(backpack[i])] = true
}
for (i in 0 until backpack.length/2) {
if (existsOnLeft[getPrio(backpack[backpack.length/2 + i])]) {
return backpack[backpack.length/2 + i]
}
}
return '!'
}
private fun getPrio(c: Char): Int {
if (c.isLowerCase()) return c.minus('`')
return c.minus('&')
}
private fun getCommonFor3(backpacks: List<String>): Char {
val b = backpacks.sortedBy { it.length }
val existsOnFirst = BooleanArray(53) { _ -> false}
val existsOnSecond = BooleanArray(53) { _ -> false}
for (l in b[0])
existsOnFirst[getPrio(l)] = true
for (l in b[1])
existsOnSecond[getPrio(l)] = true
for (l in b[2]) {
val ll = getPrio(l)
if (existsOnFirst[ll] and existsOnSecond[ll])
return l
}
return '!'
}
}
| 0 | Kotlin | 0 | 0 | 88bae9c0ce7f66a78f672b419e247cdd7374cdc1 | 1,500 | advent-of-code-2022 | Apache License 2.0 |
2021/src/test/kotlin/Day21.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import kotlin.math.max
import kotlin.math.min
import kotlin.test.Test
import kotlin.test.assertEquals
class Day21 {
class DeterministicDie {
var rolls: Int = 0
private set
private var outcome: Int = 0
fun roll(): Int {
outcome = if (outcome == 100) 1 else outcome.inc()
return outcome.also { rolls++ }
}
}
data class Board(var space: Int) {
fun move(times: Int): Int {
space = if (space + times > 10) (space + times) % 10 else space + times
if (space == 0) space = 10
return space
}
}
data class Universe(
val player1Board: Board,
val player2Board: Board,
var player1Score: Int = 0,
var player2Score: Int = 0
) {
fun copy() = this.copy(
player1Board = this.player1Board.copy(),
player2Board = this.player2Board.copy()
)
fun playTurnForPlayer1(outcome: Int) {
this.player1Score += this.player1Board.move(outcome)
}
fun playTurnForPlayer2(outcome: Int) {
this.player2Score += this.player2Board.move(outcome)
}
fun running() = this.player1Score < 21 && this.player2Score < 21
fun player1Wins() = this.player1Score > this.player2Score
}
@Test
fun `run part 01`() {
val (position1, position2) = getStartingPositions()
val die = DeterministicDie()
val (score1, score2) = playDeterministicGame(die, Board(position1), Board(position2))
val result = min(score1, score2) * die.rolls
assertEquals(679329, result)
}
private fun playDeterministicGame(
die: DeterministicDie,
board1: Board,
board2: Board
): Pair<Int, Int> {
var score1 = 0
var score2 = 0
while (true) {
score1 += playTurn(die, board1)
if (score1 >= 1000) break
score2 += playTurn(die, board2)
if (score2 >= 1000) break
}
return score1 to score2
}
private fun playTurn(die: DeterministicDie, board1: Board) = generateSequence {
die.roll()
}
.take(3)
.sum()
.let { board1.move(it) }
@Test
fun `run part 02`() {
val (position1, position2) = getStartingPositions()
val multiverse = mutableMapOf(Universe(Board(position1), Board(position2)) to 1L)
while (multiverse.any { (universe, _) -> universe.running() }) {
multiverse
.filter { (universe, _) -> universe.running() }
.flatMap { (universe, occurrences) ->
multiverse.remove(universe)
diracDieOutcomes()
.map { (outcome, times) ->
universe.copy().apply { playTurnForPlayer1(outcome) } to times * occurrences
}
.flatMap { (universe1, occurrences1) ->
if (universe1.running())
diracDieOutcomes()
.map { (outcome, times) ->
universe1.copy().apply { playTurnForPlayer2(outcome) } to times * occurrences1
}
else listOf(universe1 to occurrences1)
}
}
.forEach { (universe, occurrences) ->
multiverse[universe] = (multiverse[universe] ?: 0) + occurrences
}
}
val maxWins = max(
multiverse.filter { it.key.player1Wins() }.values.sum(),
multiverse.filter { !it.key.player1Wins() }.values.sum()
)
assertEquals(433315766324816, maxWins)
}
/*
1 2 3
1 2 3 1 2 3 1 2 3
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
'outcome' to 'number of occurrences'
*/
private fun diracDieOutcomes() = listOf(3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1)
private fun getStartingPositions() =
Util.getInputAsListOfString("day21-input.txt")
.map { it.split(':').last().trim().toInt() }
.let { it.first() to it.last() }
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 4,367 | adventofcode | MIT License |
src/Day02/Day02.kt | hectdel | 573,376,349 | false | {"Kotlin": 5426} | package Day02
import java.io.File
fun main() {
fun playResult(play: String): Int {
val splitPlay = play.split(" ")
val play = Play(splitPlay[0], splitPlay[1]);
return play.selScore() + play.resScore()
}
fun playResultPart2(play: String): Int {
val splitPlay = play.split(" ")
val play = Play(splitPlay[0], splitPlay[1]);
return play.selAndEndScore()
}
fun part1(input: String): Int {
return input
.lines()
.fold(0) { acc, play -> acc + playResult(play) }
}
fun part2(input: String): Int {
return input
.lines()
.fold(0) { acc, play -> acc + playResultPart2(play) }
}
// test if implementation meets criteria from the description, like:
val testInput = File("src/Day02/Day02_test.txt").readText()
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = File("src/Day02/data.txt").readText()
println(part1(input))
println(part2(input))
}
class Play(val opponent: String, val you: String) {
fun selScore(): Int {
return when (you) {
in "X" -> 1
in "Y" -> 2
in "Z" -> 3
else -> 0
}
}
fun resScore(): Int {
return when (you) {
in "X" -> when (opponent) {
"A" -> 3
"B" -> 0
else -> 6
}
in "Y" -> when (opponent) {
"A" -> 6
"B" -> 3
else -> 0
}
else -> when (opponent) {
"A" -> 0
"B" -> 6
else -> 3
}
}
}
fun recScore(op: String, you: String): Int {
val play = Play(op, you);
return return play.selScore() + play.resScore()
}
fun selAndEndScore(): Int {
return when (opponent) {
in "A" -> when (you) {
"X" -> recScore("A", "Z")
"Y" -> recScore("A", "X")
else -> recScore("A", "Y")
}
in "B" -> when (you) {
"X" -> recScore("B", "X")
"Y" -> recScore("B", "Y")
else -> recScore("B", "Z")
}
else -> when (you) {
"X" -> recScore("C", "Y")
"Y" -> recScore("C", "Z")
else -> recScore("C", "X")
}
}
}
}
| 0 | Kotlin | 0 | 0 | cff5677a654a18ceb199cc52fdd1c865dea46e1e | 2,474 | aco-kotlin-2022 | Apache License 2.0 |
src/test/kotlin/ch/ranil/aoc/aoc2022/Day16.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2022
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.test.Ignore
import kotlin.test.assertEquals
object Day16 : AbstractDay() {
@Test
fun part1Test() {
assertEquals(1651, compute1(testInput))
}
@Test
fun part1Puzzle() {
assertEquals(1653, compute1(puzzleInput))
}
@Test
@Ignore
fun part2Test() {
assertEquals(1, compute2(testInput))
}
@Test
@Ignore
fun part2Puzzle() {
assertEquals(1, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Int {
val valves = parse(input)
val shortestPaths: Map<Valve, Map<Valve, Int>> = valves.values.associateWith {
findShortestPaths(it)
}
return findHighestFlow(
openValves = emptySet(),
shortestPaths = shortestPaths,
currentValve = valves.getValue("AA"),
remainingMinutes = 30,
)
}
private fun findHighestFlow(
openValves: Set<Valve>,
shortestPaths: Map<Valve, Map<Valve, Int>>,
currentValve: Valve,
remainingMinutes: Int
): Int {
if (remainingMinutes <= 0) {
return 0
}
var maxFlow = 0
val nextValves = shortestPaths
.getValue(currentValve)
.filterNot { currentValve == it.key }
.filterNot { openValves.contains(it.key) }
nextValves.forEach { (nextValve, distance) ->
val timeUntilValveIsOn = distance + 1
val flow = findHighestFlow(
openValves = openValves + currentValve,
shortestPaths = shortestPaths,
currentValve = nextValve,
remainingMinutes = remainingMinutes - timeUntilValveIsOn,
)
if (flow > maxFlow) {
maxFlow = flow
}
}
return remainingMinutes * currentValve.flow + maxFlow
}
private fun findShortestPaths(startValve: Valve): Map<Valve, Int> {
val shortestDistances = mutableMapOf(startValve to 0)
val unsettled = mutableSetOf(startValve)
val settled = mutableSetOf<Valve>()
while (unsettled.isNotEmpty()) {
val currentValve = unsettled.minBy { shortestDistances[it] ?: Int.MAX_VALUE }
unsettled.remove(currentValve)
currentValve.nextValves.forEach { nextValve ->
if (!settled.contains(nextValve)) {
val distanceToSource = shortestDistances.getValue(currentValve)
val nextDistance = shortestDistances[nextValve] ?: Int.MAX_VALUE
if (distanceToSource + 1 < nextDistance) {
shortestDistances.computeIfAbsent(nextValve) { _ -> distanceToSource + 1 }
}
unsettled.add(nextValve)
}
}
settled.add(currentValve)
}
return shortestDistances
.filter { (valve, _) -> valve.hasFlow() }
}
private fun compute2(input: List<String>): Int {
parse(input).hashCode()
TODO()
}
private fun parse(input: List<String>): Map<String, Valve> {
val nodesLookup = mutableMapOf<String, Valve>()
val regex = "^Valve ([A-Z][A-Z]) has flow rate=([0-9]+); tunnels? leads? to valves? (.*)$".toRegex()
input.forEach { line ->
val matches = regex.find(line) ?: throw IllegalArgumentException("Unexpected input: $line")
val name = matches.groupValues[1].trim()
val valve = nodesLookup.getOrPut(name, Valve(name))
val flow = matches.groupValues[2].toInt()
val otherValves = matches.groupValues[3]
.split(",")
.map { it.trim() }
.map { otherName ->
nodesLookup.getOrPut(otherName, Valve(otherName))
}
valve.flow = flow
valve.add(otherValves)
}
return nodesLookup
.filter { it.value.hasFlow() || it.key == "AA" }
}
data class Valve(
val name: String
) {
var flow: Int = 0
val nextValves: MutableSet<Valve> = mutableSetOf()
fun add(other: List<Valve>) = nextValves.addAll(other)
fun hasFlow() = flow != 0
override fun toString(): String {
return "$name ($flow)"
}
}
private fun <K, V> MutableMap<K, V>.getOrPut(key: K, ifMissing: V): V {
val v = get(key)
return if (v == null) {
put(key, ifMissing)
ifMissing
} else {
v
}
}
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 4,700 | aoc | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec07.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2020
import org.elwaxoro.advent.PuzzleDayTester
class Dec07 : PuzzleDayTester(7, 2020) {
override fun part1(): Int {
val tree = Node("shiny gold")
val bags = parse()
var oldTreeSize: Int
// TODO filter the bags or something shit man have some pride
do {
oldTreeSize = tree.puzzle1().size
bags.forEach { bag ->
tree.find(bag.first)?.addBag(bag.second)
}
} while (oldTreeSize != tree.puzzle1().size)
return (tree.puzzle1().size - 1)
}
override fun part2(): Int {
val tree = Node("shiny gold")
val bags = parse2()
var inserts: Int
do {
inserts = 0
bags.forEach { bag ->
tree.findAll(bag.first).forEach { found ->
if (!found.values.map { it.key }.contains(bag.second.first)) {
found.addBag(bag.second.first, bag.second.second)
// oh fuck yea count inserts that's way better dumbass
inserts++
}
}
}
} while (inserts > 0)
return (tree.puzzle2() - 1)
}
// Inverted pair: inner bag to outer bag, ignore the shiny gold outer bag
private fun parse(): List<Pair<String, String>> = load().filter { !it.startsWith("shiny gold") }.map { raw ->
raw.split(" bags contain ").let { outer ->
val outerBag = outer[0].trim()
val innerBags =
outer[1].replace("bags", "").replace("bag", "").replace(".", "").split(", ").map { it.drop(2).trim() }
innerBags.map { it to outerBag }
}
}.flatten().toMutableList()
// Lets do a whole crap ton of processing here for no good reason and return something incomprehensible
// Pairs are outer bag to inner bag + inner bag count
// Multiple Pairs if outer bag has multiple inner bags
// Ignore empty bags
private fun parse2(): List<Pair<String, Pair<String, Int>>> =
load().filter { !it.contains("no other bags") }.map { raw ->
raw.split(" bags contain ").let { outer ->
val outerBag = outer[0].trim()
val innerBags = outer[1].replace("bags", "").replace("bag", "").replace(".", "").split(", ").map {
it.drop(2).trim() to Character.getNumericValue(it[0])
}
innerBags.map { outerBag to it }
}
}.flatten().toMutableList()
/**
* LETS MAKE A TREE WHAT A DUMB IDEA AHHH
*/
private data class Node(val key: String, val count: Int = 1, val values: MutableList<Node> = mutableListOf()) {
// for puzzle 1: find the single key matching
fun find(searchKey: String): Node? =
if (searchKey == key) {
this
} else {
values.mapNotNull { it.find(searchKey) }.firstOrNull()
}
// for puzzle 2: find ALL matching keys
fun findAll(searchKey: String): List<Node> =
if (searchKey == key) {
listOf(this)
} else {
values.map { it.findAll(searchKey) }.flatten()
}
fun addBag(newBag: String, count: Int = 1) {
values.add(Node(newBag, count))
}
fun puzzle1(): Set<String> = values.map { it.puzzle1() }.flatten().plus(key).toSet()
fun puzzle2(): Int =
if (values.isEmpty()) {
count
} else {
values.map { it.puzzle2() }.sum() * count + count
}
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 3,650 | advent-of-code | MIT License |
src/Lesson6Sorting/Distinct.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} |
import java.util.Arrays
import java.util.HashSet
/**
* Scores 100/100
* @param A
* @return
*/
fun solution(A: IntArray?): Int {
return Arrays.stream(A).distinct().toArray().size
}
/**
* Manual solution
*/
fun solution2(A: IntArray): Int {
val unique: HashSet<Int> = HashSet<Int>()
for (i in A.indices) {
unique.add(A[i])
}
return unique.size
}
/**
* Write a function
*
* class Solution { public int solution(int[] A); }
*
* that, given an array A consisting of N integers, returns the number of distinct values in array A.
*
* For example, given array A consisting of six elements such that:
*
* A[0] = 2 A[1] = 1 A[2] = 1
* A[3] = 2 A[4] = 3 A[5] = 1
* the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [0..100,000];
* each element of array A is an integer within the range [−1,000,000..1,000,000].
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 1,033 | Codility-Kotlin | Apache License 2.0 |
src/main/kotlin/aoc2023/Day25.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2023
import readInput
import java.util.*
object Day25 {
@JvmInline
private value class GroupId(val value: Int)
private data class Component(val name: String) {
var groupId: GroupId? = null
val connections = mutableSetOf<Component>()
}
private fun parseComponents(input: List<String>): Map<String, Component> {
val components = input.flatMap { it.replace(":", "").split(" ") }.map { Component(it) }
.associateBy { it.name }
input.forEach { line ->
val split = line.split(": ")
val component =
components[split.first()] ?: throw IllegalArgumentException("Component ${split.first()} not found")
val connections = split.last().split(" ")
.map { components[it] ?: throw IllegalArgumentException("Component $it not found") }
component.connections.addAll(connections)
connections.forEach { it.connections.add(component) }
}
return components
}
/**
* @param components all the [Component]s
* @param edgeCutCount the number of edges to cut
* @param groupCount the number of component groups to need after the cut
* @return a partitioning of the initial [Component]s into [groupCount] distinct groups
*/
private tailrec fun findMinCutSets(
components: Collection<Component>,
edgeCutCount: Int = 3,
groupCount: Int = 2
): Map<GroupId, Collection<Component>> {
val source = components.filter { it.groupId != null }.random()
val target = components.filter { it.groupId == null }.randomOrNull()
return if (target == null) {
components.groupBy { it.groupId!! }
} else {
val distinctPaths = findNumberOfDistinctPaths(source, target, shortcut = edgeCutCount)
if (distinctPaths > edgeCutCount) {
target.groupId = source.groupId
} else {
target.groupId = GroupId((source.groupId!!.value + 1) % groupCount)
}
findMinCutSets(components)
}
}
/**
* @param shortcut a shortcut value to immediately return if that many paths are found
* @return the number of distinct paths between [source] & [target] (at most [shortcut] + 1)
*/
private fun findNumberOfDistinctPaths(source: Component, target: Component, shortcut: Int = 3): Int {
val alreadyTaken = mutableSetOf<Pair<Component, Component>>()
var path = findPath(source, target, alreadyTaken)
var pathsFound = 0
while (path != null && pathsFound <= shortcut) {
pathsFound++
alreadyTaken.addAll(path)
path = findPath(source, target, alreadyTaken)
}
return pathsFound
}
/**
* @return a path from [source] to [target] consisting of pairs of [Component]s, avoiding all the edges given in
* [alreadyTaken] or null, if no such path exists
*/
private fun findPath(
source: Component,
target: Component,
alreadyTaken: Set<Pair<Component, Component>>
): List<Pair<Component, Component>>? {
val queue: Queue<Pair<Component, List<Pair<Component, Component>>>> = LinkedList()
queue.add(source to emptyList())
val alreadyVisited = mutableSetOf<Component>()
alreadyVisited.add(source)
while (queue.isNotEmpty()) {
val (current, currentPath) = queue.poll()
alreadyVisited.add(current)
val connections = current.connections.asSequence()
.filter { it !in alreadyVisited }
.filter { (current to it) !in alreadyTaken }
.filter { (current to it) !in currentPath }
.filter { (it to current) !in alreadyTaken }
.filter { (it to current) !in currentPath }
.toList()
if (connections.contains(target)) {
return currentPath + (current to target)
} else {
connections.forEach { next -> queue.add(next to (currentPath + (current to next))) }
}
}
return null
}
fun part1(input: List<String>): Int {
val components = parseComponents(input)
val minConnections = components.values.minOf { it.connections.size }
return when (minConnections) {
0, 1, 2 -> throw IllegalArgumentException("Expected assumption not fulfilled: Component with only $minConnections connections found")
3 -> components.size - 1 // 2 groups: 1 with single component, one with the rest
else -> {
components.values.random().groupId = GroupId(1) // assign random element to first group
val partitions = findMinCutSets(components.values)
partitions[GroupId(0)]!!.size * partitions[GroupId(1)]!!.size
}
}
}
fun part2(input: List<String>): Int {
return 0
}
}
fun main() {
val testInput = readInput("Day25_test", 2023)
check(Day25.part1(testInput) == 54)
check(Day25.part2(testInput) == 0)
val input = readInput("Day25", 2023)
println(Day25.part1(input))
println(Day25.part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 5,251 | adventOfCode | Apache License 2.0 |
src/main/kotlin/algorithm/base.kt | Tiofx | 175,697,373 | false | null | package algorithm
interface IOperator {
val C: Set<String>
val R: Set<String>
}
val IOperator.V get() = C union R
interface IGroupOperator : IOperator {
val operators: List<IOperator>
override val C get() = operators.flatMap(IOperator::C).toSet()
override val R get() = operators.flatMap(IOperator::R).toSet()
}
inline val IGroupOperator.indices get() = operators.indices
inline val IGroupOperator.lastIndex get() = operators.lastIndex
inline val IGroupOperator.size get() = operators.size
fun IGroupOperator.C(i: Int) = operators[i].C
fun IGroupOperator.R(i: Int) = operators[i].R
fun IGroupOperator.V(i: Int) = operators[i].V
fun IGroupOperator.C(p: Pair<Int, Int>) = operators.subList(p.first, p.second + 1).flatMap(IOperator::C).toSet()
fun IGroupOperator.R(p: Pair<Int, Int>) = operators.subList(p.first, p.second + 1).flatMap(IOperator::R).toSet()
interface Relations : IGroupOperator {
fun isStrongDependency(i: Int, j: Int): Boolean {
assert(i in indices && j in indices)
assert(i < j)
val base = C(i) intersect R(j)
return if (i + 1 == j)
base.isNotEmpty()
else
base !in C(i + 1 to j - 1)
}
fun isWeekDependency(i: Int, j: Int): Boolean {
assert(i in indices && j in indices)
assert(i < j)
if (isStrongDependency(i, j)) return true
for (k in i + 1 until j) {
if (isStrongDependency(i, k) && isWeekDependency(k, j)) return true
}
return false
}
fun isWeekIndependency(i: Int, j: Int): Boolean {
assert(i in indices && j in indices)
// assert(i <= j)
if (i == j) return true
val noInfoDep = (C(i) intersect R(j)).isEmpty()
val noCompetitiveDep = (R(i) intersect C(j)).isEmpty()
return noInfoDep && noCompetitiveDep && !isWeekDependency(i, j)
}
fun isStrongIndependency(i: Int, j: Int): Boolean {
assert(i in indices && j in indices)
assert(i <= j)
if (i == j) return true
return (C(i) intersect V(j)).isEmpty() && (V(i) intersect C(j)).isEmpty() && !isWeekDependency(i, j)
}
}
| 0 | Kotlin | 0 | 0 | 32c1cc3e95940e377ed9a99293eccc871ce13864 | 2,163 | CPF | The Unlicense |
src/main/kotlin/day5/solver.kt | derekaspaulding | 317,756,568 | false | null | package day5
import java.io.File
import kotlin.math.pow
fun getSeatId(seat: Pair<Int, Int>) = seat.first * 8 + seat.second
fun getSeatLocation(seatDescription: String): Pair<Int, Int> {
var row = 0
var column = 0
for ((index, char) in seatDescription.substring(0, 7).reversed().withIndex()) {
if (char == 'B') {
row += 2.0.pow(index).toInt()
}
}
for((index, char) in seatDescription.substring(7).reversed().withIndex()) {
if (char == 'R') {
column += 2.0.pow(index).toInt()
}
}
return Pair(row, column)
}
fun findHighestSeatId(seatDescriptions: List<String>) = seatDescriptions
.map { getSeatId(getSeatLocation(it)) }
.reduce { acc, i -> if (i > acc) { i } else { acc} }
fun findMissingSeat(seatDescriptions: List<String>): Int {
val seatIds = seatDescriptions.map { getSeatId(getSeatLocation(it)) }.sorted()
for ((index, seat) in seatIds.withIndex()) {
val nextSeat = seat + 1
if (index + 1 < seatIds.size && seatIds[index + 1] != nextSeat) {
return nextSeat
}
}
return -1
}
fun main() {
val seatDescriptions = File("src/main/resources/day5/input.txt")
.useLines{ it.toList() }
println("Greatest Seat ID: ${findHighestSeatId(seatDescriptions)}")
println("Your Seat: ${findMissingSeat(seatDescriptions)}")
} | 0 | Kotlin | 0 | 0 | 0e26fdbb3415fac413ea833bc7579c09561b49e5 | 1,383 | advent-of-code-2020 | MIT License |
AdventOfCodeDay20/src/nativeMain/kotlin/Day20.kt | bdlepla | 451,523,596 | false | {"Kotlin": 153773} | import kotlin.math.sqrt
class Day20(lines: List<String>) {
val tiles = mutableListOf<Tile>()
init {
var currentTile = 0
val tileLines = mutableListOf<String>()
lines.forEach {
if (it.trim().isNotEmpty()) {
if (it.startsWith("Tile")) {
if (currentTile != 0 && tileLines.isNotEmpty()) {
tiles.add(Tile(currentTile.toLong(), tileLines))
currentTile = 0
tileLines.clear()
}
currentTile = it.substring(5..8).toInt()
}
else
{
tileLines.add(it)
}
}
}
if (currentTile != 0 && tileLines.isNotEmpty())
{
tiles.add(Tile(currentTile.toLong(), tileLines))
}
}
fun findMatches(): Map<Long, Int> {
val result = tiles.associate { it.id to 0 }.toMutableMap()
val count = tiles.count()
for (i in 0 until count) {
for (j in i+1 until count) {
val tile1 = tiles[i]
val tile2 = tiles[j]
if (tile1.anySideMatches(tile2)) {
result[tile1.id] = 1 + result[tile1.id]!!
result[tile2.id] = 1 + result[tile2.id]!!
}
}
}
return result
}
private fun buildMatches(): List<Match> {
val count = tiles.count()
val pairsOfTiles = (0 until count-1).flatMap {
i -> (i+1 until count).map {
j -> Pair(i, j)
}
}
val result2 = pairsOfTiles.flatMap {
val tile1 = tiles[it.first]
val tile2 = tiles[it.second]
val match = tile1.getMatch(tile2)
if (match != null) {
val match2 = tile2.getMatch(tile1)
listOf(match, match2)
}
else listOf<Match>()
}.filterNotNull()
return result2
}
fun solvePart1(): Long {
println("Starting solve part 1...")
val matches = findMatches()
//println("matches = $matches")
val corners = matches.filter {it.value == 2}
println("found $corners corners")
val result = corners.keys.multiply()
println("Finished solve part 1")
return result
}
fun solvePart2(): Int {
println("Starting solve part 2...")
val matches = buildMatches()
//val groups = matches.groupBy { it.tileId }
//val corners = groups.filter {it.value.count() == 2}
//println("corners = $corners")
val numSide = sqrt(tiles.count().toDouble()).toInt()
println("building $numSide x $numSide grid")
val grid = Grid(numSide, numSide)
grid.arrange(tiles, matches)
val combinedMatrix = grid.mergeTiles()
val dragonStrings =
"""
#
# ## ## ###
# # # # # #
""".trimIndent().split("\n")
val dragonMatrix = Matrix2.create(dragonStrings)
//println(dragonMatrix.print())
//val dragonPoints = dragonMatrix.getTruePoints()
//println(dragonPoints)
val dragonMatches = Tile.buildTransformations.map {
val transMatrix = combinedMatrix.transform(it)
val count = transMatrix.containsDragon(dragonMatrix)
Pair(count, transMatrix)
}.filter {it.first != 0}
val matched = dragonMatches.first().second
val matchedWithoutDragonMatches = matched.removeDragons(dragonMatrix)
val ret = matchedWithoutDragonMatches.getTruePoints().count()
println("Finished solve part 2")
return ret
}
} | 0 | Kotlin | 0 | 0 | 043d0cfe3971c83921a489ded3bd45048f02ce83 | 3,808 | AdventOfCode2020 | The Unlicense |
src/Day01.kt | henryjcee | 573,492,716 | false | {"Kotlin": 2217} | fun main() {
fun part1(input: List<String>): Int {
return input.joinToString("\n")
.split("\n\n")
.map { it.split("\n") }
.map { it.fold(0) { acc, i -> acc + i.toInt() } }
.max()
}
fun part2(input: List<String>): Int {
return input.joinToString("\n")
.split("\n\n")
.map { it.split("\n") }
.map { it.fold(0) { acc, i -> acc + i.toInt() } }
.sorted()
.takeLast(3)
.sum()
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2fde9f3db7454583ac9c47cfca524cfa6a16eb61 | 770 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/cc/stevenyin/leetcode/_0027_RemoveElement.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.leetcode
/**
* https://leetcode.com/problems/remove-element/
* Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Custom Judge:
The judge will test your solution with the following code:
<code>
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
</code>
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
*/
class _0027_RemoveElement {
fun removeElement(nums: IntArray, `val`: Int): Int {
var j = 0;
for (index in nums.indices) {
if (nums[index] != `val`) {
nums[j++] = nums[index];
}
}
return j;
}
fun removeElement2(nums: IntArray, `val`: Int): Int {
if (nums.size == 0) {
return 0
}
var i = 0;
var j = nums.size - 1;
while (i < j) {
if (nums[i] != `val`) {
i ++;
} else {
swap(nums, i, j--);
}
}
var length = 0;
for (index in nums.size - 1 downTo 0) {
if (nums[index] != `val`) {
break;
} else {
length ++;
}
}
return nums.size - length;
}
private fun swap(nums: IntArray, i: Int, j: Int) {
val temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
fun main() {
_0027_RemoveElement().removeElement(intArrayOf(0,1,2,2,3,0,4,2), 2)
} | 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 3,194 | kotlin-demo-code | MIT License |
src/Day12.kt | diego09310 | 576,378,549 | false | {"Kotlin": 28768} | fun main() {
data class Coor(var x: Int, var y: Int, var steps: Int)
fun isReachable(coor1: Coor, coor2: Coor, map: MutableList<MutableList<Char>>, stepMap: Array<Array<Int>>): Boolean {
return ((map[coor2.x][coor2.y].code <= map[coor1.x][coor1.y].code + 1 && map[coor2.x][coor2.y] != 'E') || (map[coor1.x][coor1.y].code >= 'y'.code && map[coor2.x][coor2.y] == 'E'))
}
fun examineCoor(toVisit: ArrayDeque<Coor>, map: MutableList<MutableList<Char>>, stepMap: Array<Array<Int>>): Int {
val coor = toVisit.removeFirst()
if (stepMap[coor.x][coor.y] < coor.steps) {
return -1
}
if (map[coor.x][coor.y] == 'E') {
return coor.steps
}
stepMap[coor.x][coor.y] = coor.steps
for (i in -1..1) {
for (j in -1..1) {
if ((i == 0 || j == 0) && !(i == 0 && j == 0)) {
val nCoor = Coor(coor.x + i, coor.y + j, coor.steps + 1)
if (coor.x + i >= 0 && coor.x + i < map.size
&& coor.y + j >= 0 && coor.y + j < map[0].size
&& isReachable(coor, nCoor, map, stepMap)
&& !toVisit.contains(nCoor)) {
toVisit.add(nCoor)
}
}
}
}
return -1
}
fun part1(input: List<String>): Int {
val map: MutableList<MutableList<Char>> = mutableListOf()
input.forEach{ line -> map.add(line.toCharArray().map{it} as MutableList<Char>) }
val toVisit = ArrayDeque<Coor>()
val stepMap = Array(map.size) { Array(map[0].size) { Int.MAX_VALUE} }
val start = Coor(-1, -1, 0)
start@ for (i in 0 until map.size) {
for (j in 0 until map[0].size) {
if (map[i][j] == 'S') {
start.x = i
start.y = j
map[i][j] = 'a'
break@start
}
}
}
toVisit.add(start)
while(toVisit.isNotEmpty()) {
// println("===========")
// toVisit.forEach{println(it)}
// for (i in stepMap) {
// i.forEach { print(it.toString().padStart(3, ' ')) }
// println()
// }
val steps = examineCoor(toVisit, map, stepMap)
if (steps != -1) {
return steps
}
}
return 0
}
fun examineCoor2(toVisit: ArrayDeque<Coor>, map: MutableList<MutableList<Char>>, stepMap: Array<Array<Int>>): Int {
val coor = toVisit.removeFirst()
if (stepMap[coor.x][coor.y] < coor.steps) {
return -1
}
if (map[coor.x][coor.y] == 'a') {
coor.steps = 0
}
if (map[coor.x][coor.y] == 'E') {
for (i in 0 until coor.steps) {
if (!stepMap.any{it.contains(i)}) {
return -1
}
}
return coor.steps
}
toVisit.filter{!(it.x == coor.x && it.y == coor.y && it.steps > coor.steps)}
stepMap[coor.x][coor.y] = coor.steps
for (i in -1..1) {
for (j in -1..1) {
if ((i == 0 || j == 0) && !(i == 0 && j == 0)) {
val nCoor = Coor(coor.x + i, coor.y + j, coor.steps + 1)
if (coor.x + i >= 0 && coor.x + i < map.size
&& coor.y + j >= 0 && coor.y + j < map[0].size
&& isReachable(coor, nCoor, map, stepMap)
&& !toVisit.contains(nCoor)) {
toVisit.add(nCoor)
}
}
}
}
return -1
}
fun part2(input: List<String>): Int {
val map: MutableList<MutableList<Char>> = mutableListOf()
input.forEach{ line -> map.add(line.replace('S', 'a').toCharArray().map{ it } as MutableList<Char>) }
val toVisit = ArrayDeque<Coor>()
val stepMap = Array(map.size) { Array(map[0].size) { Int.MAX_VALUE} }
val start = Coor(-1, -1, 0)
start@ for (i in 0 until map.size) {
for (j in 0 until map[0].size) {
if (map[i][j] == 'a') {
start.x = i
start.y = j
break@start
}
}
}
toVisit.add(start)
while(toVisit.isNotEmpty()) {
val steps = examineCoor2(toVisit, map, stepMap)
if (stepMap.any{it.contains(5)}) {
// println("########################")
// for (i in stepMap) {
// i.forEach { print(it.toString().padStart(11, ' ')) }
// println()
// }
}
if (steps != -1) {
return steps
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("../../12linput")
check(part1(testInput) == 31)
val input = readInput("../../12input")
println(part1(input))
check(part2(testInput) == 29)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 644fee9237c01754fc1a04fef949a76b057a03fc | 5,232 | aoc-2022-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.