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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2023/day04-25/src/main/kotlin/Day18.kt | CakeOrRiot | 317,423,901 | false | {"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417} | import java.io.File
import kotlin.math.abs
class Day18 {
fun solve1() {
val input = File("inputs/18.txt").inputStream().bufferedReader().lineSequence().toList().map {
val split = it.split(' ')
val direction = when (split[0][0]) {
'R' -> Direction.RIGHT
'D' -> Direction.DOWN
'L' -> Direction.LEFT
'U' -> Direction.UP
else -> throw Exception()
}
Instruction(direction, split[1].toLong())
}
var curPoint = Point(0, 0)
val vertices = listOf(Vertex(input[0].direction, Point(0, 0))).toMutableList()
input.forEach { instruction ->
curPoint += when (instruction.direction) {
Direction.RIGHT -> Point(0, 1) * instruction.distance
Direction.DOWN -> Point(1, 0) * instruction.distance
Direction.LEFT -> Point(0, -1) * instruction.distance
Direction.UP -> Point(-1, 0) * instruction.distance
}
vertices.add(Vertex(instruction.direction, curPoint))
}
val area = calcArea(vertices)
val perimeter = calcPerimeter(vertices)
println(area + perimeter / 2 + 1)
}
fun solve2() {
val input = File("inputs/18.txt").inputStream().bufferedReader().lineSequence().toList().map {
val split = it.split(' ')
val color = split[2].drop(1).dropLast(1)
val direction = when (color.last()) {
'0' -> Direction.RIGHT
'1' -> Direction.DOWN
'2' -> Direction.LEFT
'3' -> Direction.UP
else -> throw Exception()
}
val distance = color.drop(1).dropLast(1).toLong(16)
Instruction(direction, distance)
}
var curPoint = Point(0, 0)
val vertices = listOf(Vertex(input[0].direction, Point(0, 0))).toMutableList()
input.forEach { instruction ->
curPoint += when (instruction.direction) {
Direction.RIGHT -> Point(0, 1) * instruction.distance
Direction.DOWN -> Point(1, 0) * instruction.distance
Direction.LEFT -> Point(0, -1) * instruction.distance
Direction.UP -> Point(-1, 0) * instruction.distance
}
vertices.add(Vertex(instruction.direction, curPoint))
}
val area = calcArea(vertices)
val perimeter = calcPerimeter(vertices)
println(area.toLong() + perimeter / 2 + 1)
}
data class Point(val x: Long, val y: Long) {
operator fun plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
operator fun times(scale: Long): Point {
return Point(x * scale, y * scale)
}
}
enum class Direction {
UP, DOWN, LEFT, RIGHT
}
data class Instruction(val direction: Direction, val distance: Long)
data class Vertex(val direction: Direction, val point: Point)
fun calcArea(vertices: List<Vertex>): Double {
var area = 0.0
for (i in vertices.indices) {
val p = if (i == 0) vertices.last.point else vertices[i - 1].point
val q = vertices[i].point
area += (p.x - q.x) * (p.y + q.y)
}
return abs(area / 2.0)//.toInt()
}
fun calcPerimeter(vertices: List<Vertex>): Long {
var perimeter = 0L
for (i in 1..<vertices.size) {
perimeter += abs(vertices[i - 1].point.x - vertices[i].point.x) + abs(vertices[i - 1].point.y - vertices[i].point.y)
}
return perimeter
}
} | 0 | Kotlin | 0 | 0 | 8fda713192b6278b69816cd413de062bb2d0e400 | 3,679 | AdventOfCode | MIT License |
src/Day23.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | private val northOffset = listOf(
Pair(1, -1),
Pair(0, -1),
Pair(-1, -1),
)
private val eastOffset = listOf(
Pair(1, -1),
Pair(1, 0),
Pair(1, 1),
)
private val southOffset = listOf(
Pair(1, 1),
Pair(0, 1),
Pair(-1, 1),
)
private val westOffset = listOf(
Pair(-1, -1),
Pair(-1, 0),
Pair(-1, 1),
)
private fun elves(input: List<String>): Set<Pair<Int, Int>> {
val elves = mutableSetOf<Pair<Int, Int>>()
for ((y, line) in input.withIndex()) {
for ((x, char) in line.withIndex()) {
if (char == '#') {
elves.add((Pair(x, y)))
}
}
}
return elves
}
private fun eightNeighbour(coordinate: Pair<Int, Int>): List<Pair<Int, Int>> {
return listOf(
Pair(coordinate.first + 1, coordinate.second + 1),
Pair(coordinate.first + 1, coordinate.second),
Pair(coordinate.first + 1, coordinate.second - 1),
Pair(coordinate.first, coordinate.second + 1),
Pair(coordinate.first, coordinate.second - 1),
Pair(coordinate.first - 1, coordinate.second + 1),
Pair(coordinate.first - 1, coordinate.second),
Pair(coordinate.first - 1, coordinate.second - 1),
)
}
private fun directionNeighbour(coordinate: Pair<Int, Int>, offset: List<Pair<Int, Int>>): List<Pair<Int, Int>> {
return offset.map {
Pair(coordinate.first + it.first, coordinate.second + it.second)
}
}
val considerationOrders = listOf(
listOf(northOffset, southOffset, westOffset, eastOffset),
listOf(southOffset, westOffset, eastOffset, northOffset),
listOf(westOffset, eastOffset, northOffset, southOffset),
listOf(eastOffset, northOffset, southOffset, westOffset),
)
private fun move(round: Int, elves: Set<Pair<Int, Int>>): Set<Pair<Int, Int>> {
val elvesDestinations = elves.toMutableSet()
val considerationOrder = considerationOrders[round % 4]
val destinationCount = mutableMapOf<Pair<Int, Int>, Int>()
val proposedMoves = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
// first half
for (elf in elves) {
if (eightNeighbour(elf).any { elves.contains(it) }) {
considerationOrder.firstOrNull() { consideration ->
directionNeighbour(elf, consideration).all { !elves.contains(it) }
}?.let { offset ->
val moveDirection = offset[1]
val proposedDestination = Pair(elf.first + moveDirection.first, elf.second + moveDirection.second)
destinationCount[proposedDestination] = destinationCount.getOrDefault(proposedDestination, 0) + 1
proposedMoves[elf] = proposedDestination
}
}
// otherwise no elves around, don't move
}
for ((elf, destination) in proposedMoves) {
if (destinationCount[destination] == 1) {
elvesDestinations.remove(elf)
elvesDestinations.add(destination)
}
}
return elvesDestinations
}
private fun part1(input: List<String>): Int {
var elves = elves(input)
for (round in 0 until 10) {
elves = move(round, elves)
}
val allX = elves.map { it.first }
val allY = elves.map { it.second }
return (allX.max() - allX.min() + 1) * (allY.max() - allY.min() + 1) - elves.size
}
private fun part2(input: List<String>): Int {
var elves = elves(input)
var round = 0
do {
val elvesNext = move(round, elves)
if (elvesNext == elves) {
return round + 1
}
elves = elvesNext
round++
} while (true)
}
fun main() {
val input = readInput("Day23")
// val input = readInput("Test")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 3,755 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | lonskiTomasz | 573,032,074 | false | {"Kotlin": 22055} | fun main() {
fun totalScoreOfGivenStrategy(input: List<String>): Int {
/**
* A for Rock, B for Paper, and C for Scissors
* X for Rock, Y for Paper, and Z for Scissors
*
* 1 for Rock, 2 for Paper, and 3 for Scissors
* 0 if you lost, 3 if the round was a draw, and 6 if you won
*/
val battleDictionary: HashMap<String, Int> = hashMapOf(
"A X" to 1 + 3,
"A Y" to 2 + 6,
"A Z" to 3 + 0,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 1 + 6,
"C Y" to 2 + 0,
"C Z" to 3 + 3,
)
var totalScore = 0
input.forEach { line ->
totalScore += battleDictionary[line] ?: 0
}
return totalScore
}
fun totalScoreBasedOnRequiredOutput(input: List<String>): Int {
/**
* A for Rock, B for Paper, and C for Scissors
* X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win
*
* 1 for Rock, 2 for Paper, and 3 for Scissors
* 0 if you lost, 3 if the round was a draw, and 6 if you won
*/
val battleDictionary: HashMap<String, Int> = hashMapOf(
"A X" to 0 + 3, // rock > scissors
"A Y" to 3 + 1, // draw
"A Z" to 6 + 2, // rock < paper
"B X" to 0 + 1, // paper > rock
"B Y" to 3 + 2, // draw
"B Z" to 6 + 3, // paper < scissors
"C X" to 0 + 2, // scissors > paper
"C Y" to 3 + 3, // draw
"C Z" to 6 + 1, // scissors < rock
)
var totalScore = 0
input.forEach { line ->
totalScore += battleDictionary[line] ?: 0
}
return totalScore
}
val inputTest = readInput("day02/input_test")
val input = readInput("day02/input")
println(totalScoreOfGivenStrategy(inputTest))
println(totalScoreOfGivenStrategy(input))
println(totalScoreBasedOnRequiredOutput(inputTest))
println(totalScoreBasedOnRequiredOutput(input))
} | 0 | Kotlin | 0 | 0 | 9e758788759515049df48fb4b0bced424fb87a30 | 2,134 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/aoc2020/ex8.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | fun main() {
val input = readInputFile("aoc2020/input8")
val instructions = parseInput(input.lines())
//for (i in instructions.indices) {
println("$327")
val hackedInstrctions = hackInstruction(327, instructions)
val lines = mutableListOf<Int>()
val computer = Computer()
while (computer.currentLine !in lines) {
lines.add(computer.currentLine)
computer.operateInstruction(hackedInstrctions[computer.currentLine])
println("acc ${computer.accumulator}")
}
}
fun hackInstruction(i: Int, instructions: List<Instruction>): List<Instruction> {
val instruction = instructions[i]
return when (instruction) {
is Instruction.Accumulate -> instructions
is Instruction.Jump -> instructions.toMutableList().apply { set(i, Instruction.NoOp(instruction.lines)) }
is Instruction.NoOp -> instructions.toMutableList().apply { set(i, Instruction.Jump(instruction.amount)) }
}
}
class Computer {
var currentLine = 0
var accumulator = 0
fun operateInstruction(instruction: Instruction) {
when (instruction) {
is Instruction.Accumulate -> {
accumulator += instruction.amount
currentLine++
}
is Instruction.Jump -> currentLine += instruction.lines
is Instruction.NoOp -> currentLine++
}
}
}
sealed class Instruction {
data class NoOp(val amount: Int) : Instruction()
data class Accumulate(val amount: Int) : Instruction()
data class Jump(val lines: Int) : Instruction()
}
private fun parseInput(lines: List<String>): List<Instruction> {
return lines.map {
val splitted = it.split(" ")
require(splitted.size == 2)
val amount = splitted[1].toInt()
when (splitted[0]) {
"nop" -> Instruction.NoOp(amount)
"acc" -> Instruction.Accumulate(amount)
"jmp" -> Instruction.Jump(amount)
else -> error("cant")
}
}
} | 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 2,040 | AOC-2021 | MIT License |
src/main/kotlin/Day20.kt | clechasseur | 267,632,210 | false | null | import org.clechasseur.adventofcode2016.Day20Data
import kotlin.math.max
import kotlin.math.min
object Day20 {
private val input = Day20Data.input
fun part1(): Long = mergeBlockList(getBlockList()).sortedBy { it.first }[0].last + 1L
fun part2(): Long = 4294967296L - mergeBlockList(getBlockList()).map { it.last - it.first + 1 }.sum()
private fun getBlockList(): List<LongRange> = input.lines().map {
val (from, to) = it.split('-')
(from.toLong())..(to.toLong())
}
private fun mergeBlockList(blockList: List<LongRange>): List<LongRange> {
var curBlockList = blockList
val mergedBlockList = mutableListOf<LongRange>()
var mergedSomething = true
while (mergedSomething) {
mergedSomething = false
while (curBlockList.isNotEmpty()) {
val block = curBlockList[0]
val (toMerge, rest) = curBlockList.partition {
it.first in block || it.last in block ||
block.first in it || block.last in it ||
it.first == block.last + 1 || it.last == block.first - 1
}
mergedSomething = mergedSomething || toMerge.size > 1
val merged = toMerge.reduce { acc, r ->
min(acc.first, r.first)..max(acc.last, r.last)
}
mergedBlockList.add(merged)
curBlockList = rest
}
if (mergedSomething) {
curBlockList = mergedBlockList.toList()
mergedBlockList.clear()
}
}
return mergedBlockList
}
}
| 0 | Kotlin | 0 | 0 | 120795d90c47e80bfa2346bd6ab19ab6b7054167 | 1,670 | adventofcode2016 | MIT License |
src/Day13.kt | Totwart123 | 573,119,178 | false | null | fun main() {
fun getList(input: Iterator<Char>): List<Any> {
val output = mutableListOf<Any>()
var lastOneWasDiget = false
while (input.hasNext()){
val next = input.next()
if(next == ']'){
break
}
if(next == ','){
lastOneWasDiget = false
continue
}
if(next =='['){
lastOneWasDiget = false
output.add(getList(input))
}
else if(next.digitToIntOrNull() != null){
if(lastOneWasDiget){
output[output.size - 1] = output[output.size - 1] as Int * 10 + next.digitToInt()
}
else{
output.add(next.digitToInt())
}
lastOneWasDiget = true
}
}
return output
}
fun compareLists(left: Any?, right: Any?) : Int{
if(left is Int && right is Int){
return if(left < right){
1
} else if (left == right){
0
} else{
-1
}
}
if(left is List<*> && right is Int){
return compareLists(left, listOf(right))
}
if(left is Int && right is List<*>){
return compareLists(listOf(left), right)
}
if(left is List<*> && right is List<*>){
for (i in 0 until left.size){
if(right.size <= i){
return -1
}
val check = compareLists(left[i], right[i])
if(check != 0){
return check
}
}
return if(left.size == right.size) 0 else return 1
}
return 2
}
fun part1(input: List<String>): Int {
var result = 0
input.windowed(2, 3).forEachIndexed { index, pair ->
val lists = pair.map { line ->
getList(line.iterator()).first()
}
if(compareLists(lists.first(), lists.last()) == 1){
result += index + 1
}
}
return result
}
fun insertItem(result: MutableList<Any>, item: Any){
var inserted = false
if(result.isNotEmpty()){
for(i in 0 until result.size){
if(compareLists(item, result[i]) == 1){
result.add(i, item)
inserted = true
break
}
}
}
if(!inserted){
result.add(item)
}
}
fun part2(input: List<String>): Int {
val result = mutableListOf<Any>()
input.windowed(2, 3).forEachIndexed { index, pair ->
val lists = pair.map { line ->
getList(line.iterator()).first()
}
lists.forEach {
insertItem(result, it)
}
}
val divider1 = getList("[[2]]".iterator()).first()
val divider2 = getList("[[6]]".iterator()).first()
insertItem(result, divider1)
insertItem(result, divider2)
val index1 = result.indexOf(divider1) + 1
val index2 = result.indexOf(divider2) + 1
result.forEach { println(it) }
return index1 * index2
}
val testInput = readInput("Day13_test")
//check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 33e912156d3dd4244c0a3dc9c328c26f1455b6fb | 3,576 | AoC | Apache License 2.0 |
src/main/kotlin/Day5.kt | noamfreeman | 572,834,940 | false | {"Kotlin": 30332} | private val part1ExampleInput = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent()
fun main() {
println("day5")
println()
println("part1")
assertEquals(part1(part1ExampleInput), "CMZ")
println(part1(readInputFile("day5_input.txt")))
println()
println("part2")
assertEquals(part2(part1ExampleInput), "MCD")
println(part2(readInputFile("day5_input.txt")))
}
private fun part1(input: String): String {
val (columns, instructions) = parseInput(input)
val res = instructions.fold(columns) { cols, instruction ->
cols.executeInstruction(instruction, reversed = true)
}
return res.map { it.last() }.joinToString("")
}
private fun part2(input: String): String {
val (columns, instructions) = parseInput(input)
val res = instructions.fold(columns) { cols, instruction ->
cols.executeInstruction(instruction, reversed = false)
}
return res.map { it.last() }.joinToString("")
}
private fun <T> List<List<T>>.executeInstruction(instruction: Instruction, reversed: Boolean): MutableList<List<T>> {
val src = this[instruction.source]
val dest = this[instruction.dest]
return this.toMutableList().apply {
this[instruction.dest] = dest + src.takeLast(instruction.amount).run { if (reversed) reversed() else this }
this[instruction.source] = src.dropLast(instruction.amount)
}
}
private data class Instruction(val source: Int, val dest: Int, val amount: Int)
private fun parseInput(input: String): Pair<List<List<Char>>, List<Instruction>> {
val (crates, rawInstructions) = input.splitByEmptyLines()
val rows = crates.lines().dropLast(1).reversed().map { line ->
line.drop(1).chunked(4).map {
it[0].takeIf { it != ' ' }
}
}
val columns = rows.transpose().map {
it.removeTrailingNulls()
}
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
val instructions = rawInstructions.lines().map { rawInstruction ->
val match = regex.find(rawInstruction)!!.groupValues
Instruction(source = match[2].toInt() - 1, dest = match[3].toInt() - 1, amount = match[1].toInt())
}
return columns to instructions
}
private fun <T> List<List<T>>.transpose(): List<List<T>> {
val length = size
// assuming all inner list in the same size
val width = this[1].size
return List(width) { i -> List(length) { j -> this[j][i] } }
}
@Suppress("UNCHECKED_CAST")
private fun <T> List<T?>.removeTrailingNulls(): List<T> {
// assuming non-null until some tail.
val firstNull = indexOfFirst { it == null }
if (firstNull == -1) return this as List<T>
return subList(0, firstNull) as List<T>
} | 0 | Kotlin | 0 | 0 | 1751869e237afa3b8466b213dd095f051ac49bef | 2,786 | advent_of_code_2022 | MIT License |
simple-tic-tac-toe/Main.kt | aesdeef | 437,311,579 | false | {"Kotlin": 3274} | package tictactoe
import kotlin.math.abs
typealias Board = List<List<Char>>
enum class GameState {
IMPOSSIBLE,
X_WINS,
O_WINS,
DRAW,
NOT_FINISHED,
}
fun main() {
val input = "_________"
var board = input.chunked(3).map { it.toList() }
printBoard(board)
for (player in "XOXOXOXOX") {
board = promptForMove(board, player)
printBoard(board)
if (
evaluateState(board) in listOf(
GameState.X_WINS, GameState.O_WINS
)
) break
}
printState(board)
}
fun updateBoard(board: Board, newCharacter: Char, coordinates: Pair<Int, Int>): Board {
val (rowNumber, columnNumber) = coordinates
return board.mapIndexed { r, row ->
row.mapIndexed { c, square ->
if (r == rowNumber && c == columnNumber) newCharacter else square
}
}
}
fun parseCoordinates(board: Board, input: String): Pair<Int, Int> {
val (rowNumber, columnNumber) = try {
input.split(" ").map { it.toInt() - 1 }
} catch (e: Exception) {
throw Exception("You should enter numbers!")
}
if (rowNumber !in 0..2 || columnNumber !in 0..2) {
throw Exception("Coordinates should be from 1 to 3")
}
if (board[rowNumber][columnNumber] != '_') {
throw Exception("This cell is occupied!")
}
return Pair(rowNumber, columnNumber)
}
fun promptForMove(board: Board, player: Char): Board {
while (true) {
print("Enter the coordinates: ")
val input = readLine()!!
try {
val coordinates = parseCoordinates(board, input)
return updateBoard(board, player, coordinates)
} catch (e: Exception) {
println(e.message)
}
}
}
fun evaluateState(board: Board): GameState {
val countX = board.sumOf { row -> row.count { it == 'X' } }
val countO = board.sumOf { row -> row.count { it == 'O' } }
if (abs(countX - countO) > 1) return GameState.IMPOSSIBLE
val rows = board
val columns = board[0]
.indices.map { i ->
board.map { row -> row[i] }
}
val diagonals = listOf(
board.indices.map { board[it][it] },
board.indices.map { board[it][board.lastIndex - it] },
)
val lines = (rows + columns + diagonals)
.map { it.joinToString("") }
val winners = lines
.filter { it in listOf("XXX", "OOO") }
.map { it.first() }
.toSet()
return when (winners.size) {
0 -> if (countX + countO == 9) GameState.DRAW else GameState.NOT_FINISHED
1 -> if ('X' in winners) GameState.X_WINS else GameState.O_WINS
else -> GameState.IMPOSSIBLE
}
}
fun printState(board: Board) {
val state = evaluateState(board)
println(
when (state) {
GameState.IMPOSSIBLE -> "Impossible"
GameState.X_WINS -> "X wins"
GameState.O_WINS -> "O wins"
GameState.DRAW -> "Draw"
GameState.NOT_FINISHED -> "Game not finished"
}
)
}
fun printBoard(board: Board) {
println("---------")
board.forEach { row ->
val marks = row.map { if (it in "XO") it else ' ' }
println("| ${marks.joinToString(" ")} |")
}
println("---------")
}
| 0 | Kotlin | 0 | 0 | 1475a200591397ca3daebe1d66fae0fe0ed34d24 | 3,274 | kotlin-basics-projects | MIT License |
advent-of-code-2022/src/test/kotlin/Day 11 Monkey in the Middle Gold.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | import `Day 11 Monkey in the Middle Gold`.RNS.Companion.toRNS
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
/** 15:15 */
class `Day 11 Monkey in the Middle Gold` {
data class RNS(val primes: List<Int>, val values: List<Int>) {
fun divisibleBy(testDivisible: Int): Boolean {
val primeIndex = primes.indexOf(testDivisible)
return values[primeIndex] == 0
}
operator fun plus(right: Int): RNS {
val added =
values.mapIndexed { index, left ->
val prime = primes[index]
(left.plus(right.rem(prime))).rem(prime)
}
return copy(values = added)
}
operator fun times(right: RNS): RNS {
val added =
primes.mapIndexed { index, prime -> values[index].times(right.values[index]).rem(prime) }
return copy(values = added)
}
operator fun times(right: Int): RNS = times(right.toRNS(primes))
companion object {
fun String.toRNS(primes: List<Int>): RNS = toInt().toRNS(primes)
fun Int.toRNS(primes: List<Int>) = RNS(primes = primes, values = primes.map { rem(it) })
}
}
sealed class Operation : (RNS) -> RNS
data class Multiply(val value: Int) : Operation() {
override fun invoke(rns: RNS): RNS = rns * value
}
data class Add(val value: Int) : Operation() {
override fun invoke(rns: RNS): RNS = rns + value
}
object Square : Operation() {
override fun invoke(rns: RNS): RNS = rns * rns
}
data class Monkey(
val index: Int = 0,
val items: List<RNS>,
val operation: Operation,
val testDivisible: Int,
val pass: Int,
val fail: Int,
val inspections: Long = 0
)
@Test
fun goldTest() {
monkeyBusiness(parse(testInput), 10000) shouldBe 2713310158L
}
@Test
fun gold() {
monkeyBusiness(parse(loadResource("day11")), 10000) shouldBe 39109444654
}
private fun monkeyBusiness(monkeys: List<Monkey>, rounds: Int): Long =
generateSequence(monkeys) { round(it) }
.drop(1)
.take(rounds)
.last()
.asSequence()
.map { it.inspections }
.onEachIndexed { index, i -> println("Monkey $index inspected items $i times.") }
.sortedDescending()
.take(2)
.reduce { acc, inspections -> acc * inspections }
private fun round(monkeys: List<Monkey>): List<Monkey> {
return monkeys.fold(monkeys) { acc, monkey ->
val (mutatedMonkey, passes) = monkeyRound(acc[monkey.index])
acc.map { otherMonkey ->
if (otherMonkey.index == mutatedMonkey.index) mutatedMonkey
else {
val passedToThisMonkey =
passes.filter { it.index == otherMonkey.index }.map { it.value }
otherMonkey.copy(items = otherMonkey.items + passedToThisMonkey)
}
}
.also { check(acc.sumOf { it.items.size } == monkeys.sumOf { it.items.size }) }
}
}
data class Pass(val index: Int, val value: RNS)
private fun monkeyRound(monkey: Monkey): Pair<Monkey, List<Pass>> {
val passes =
monkey.items
.map { item -> monkey.operation(item) }
.map { item ->
Pass(
value = item,
index = if (item.divisibleBy(monkey.testDivisible)) monkey.pass else monkey.fail)
}
check(passes.size == monkey.items.size)
check(passes.none { it.index == monkey.index })
return monkey.copy(
items = emptyList(),
inspections = monkey.inspections + monkey.items.size,
) to passes
}
private fun parse(testInput: String): List<Monkey> {
val primes =
testInput
.lines()
.filter { it.contains(" Test: divisible by ") }
.map { it.substringAfterLast(" ").toInt() }
.sorted()
return testInput.split("\n\n").mapIndexed { index, string ->
val lines = string.lines()
val starting = lines[1].substringAfter(": ").split(", ").map { it.toRNS(primes) }
val operation =
lines[2].substringAfter("new = old ").let {
when {
it == "* old" -> Square
it.startsWith("*") -> Multiply(it.substringAfter("* ").toInt())
it.startsWith("+") -> Add(it.substringAfter("+ ").toInt())
else -> error("")
}
}
val test = lines[3].substringAfterLast(" ").toInt()
val pass = lines[4].substringAfter(" monkey ").toInt()
val fail = lines[5].substringAfter(" monkey ").toInt()
Monkey(index, starting, operation, test, pass, fail)
}
}
private val testInput =
"""
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
""".trimIndent()
}
| 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 5,289 | advent-of-code | MIT License |
src/main/kotlin/com/chriswk/aoc/advent2021/Day14.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
class Day14: AdventDay(2021, 14) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day14()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun parseInput(input: List<String>): Pair<String, Map<String, List<String>>> {
val template = input.first()
val transformations = input.drop(2).associate { r ->
val (from, to) = r.split(" -> ")
from to listOf("${from.first()}$to", "$to${from.last()}")
}
return template to transformations
}
fun score(template: String, transformations: Map<String, List<String>>, steps: Int): Long {
var state = template.zip(template.drop(1)) { a, b -> "$a$b" }.groupingBy { it }.eachCount().mapValues { it.value.toLong() }
repeat(steps) {
state = buildMap {
state.forEach { (k, n) ->
transformations.getValue(k).forEach { dst ->
put(dst, getOrElse(dst) { 0 } + n )
}
}
}
}
val counts = buildMap<Char, Long> {
put(template.first(), 1)
put(template.last(), getOrElse(template.last()) { 0 } + 1)
state.forEach { (pair, count) ->
pair.forEach { element ->
put(element, getOrElse(element) { 0 } + count)
}
}
}
return (counts.values.maxOrNull()!! - counts.values.minOrNull()!!) / 2
}
fun part1(): Long {
val (template, trans) = parseInput(inputAsLines)
return score(template, trans, 10)
}
fun part2(): Long {
val (template, trans) = parseInput(inputAsLines)
return score(template, trans, 40)
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 1,962 | adventofcode | MIT License |
src/main/kotlin/year2023/Day18.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2023
import utils.Direction
import utils.Point2D
class Day18 {
data class Move(val direction: Direction, val length: Int, val color: Int)
fun part1(input: String): Long {
val moves = parse(input)
val positions = moves.runningFold(Point2D.ORIGIN) { point, move ->
point.move(move.direction.dx * move.length, move.direction.dy * move.length)
}
val xs = positions.map { it.x }
val ys = positions.map { it.y }
val lx = xs.min()
val rx = xs.max()
val ly = ys.min()
val ry = ys.max()
val width = rx - lx + 1
val height = ry - ly + 1
val ox = -lx
val oy = -ly
val array = Array(height) { Array(width) { '.' } }
moves.fold(Point2D(ox, oy)) { startPoint, move ->
(0..<move.length).fold(startPoint) { currentPoint, _ ->
array[currentPoint.y][currentPoint.x] = '#'
currentPoint.move(move.direction)
}
}
array.forEachIndexed { rowIdx, row ->
row.forEachIndexed { colIdx, cell ->
if (cell == '.') {
if (!array.fill(colIdx, rowIdx, '.', 'o')) {
array.fill(colIdx, rowIdx, 'o', '#')
}
}
}
}
return array.map { it.count { it == '#' }.toLong() }.sum()
}
fun Array<Array<Char>>.fill(col: Int, row: Int, fromCh: Char, toCh: Char): Boolean {
val stack = ArrayDeque<Point2D>()
stack.add(Point2D(col, row))
var wasOnTheBorder = false
while (stack.isNotEmpty()) {
val point = stack.removeLast()
if (this[point.y][point.x] == fromCh) {
wasOnTheBorder =
wasOnTheBorder || point.x == 0 || point.y == 0 || point.x == this[0].size - 1 || point.y == this.size - 1
this[point.y][point.x] = toCh
if (point.x > 0 && this[point.y][point.x - 1] == fromCh) {
stack.add(point.move(-1, 0))
}
if (point.x < this[0].size - 1 && this[point.y][point.x + 1] == fromCh) {
stack.add(point.move(1, 0))
}
if (point.y > 0 && this[point.y - 1][point.x] == fromCh) {
stack.add(point.move(0, -1))
}
if (point.y < this.size - 1 && this[point.y + 1][point.x] == fromCh) {
stack.add(point.move(0, 1))
}
}
}
return wasOnTheBorder
}
fun part2(input: String): Long {
return 0L
}
fun parse(input: String): List<Move> = input.lines().map { line ->
val (part1, part2, part3) = line.split(' ')
val direction = Direction.byFirstLetter(part1[0])
val length = part2.toInt()
val color = part3.substring(2, 8).toInt(16)
Move(direction, length, color)
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 2,992 | aoc-2022 | Apache License 2.0 |
src/Day06.kt | sebokopter | 570,715,585 | false | {"Kotlin": 38263} | fun main() {
fun findFirstUniqueChars(input: String, uniqueChars: Int): Int {
for (i in (uniqueChars-1)..input.lastIndex) {
val lastFourChars = input.substring(i - (uniqueChars-1)..i)
fun areUnique(lastFourChars: String) = lastFourChars.toSet().size == uniqueChars
if (areUnique(lastFourChars)) return i + 1
}
error("No start-of-packet marker found")
}
fun part1(input: String): Int = findFirstUniqueChars(input, 4)
fun part2(input: String): Int = findFirstUniqueChars(input, 14)
readInput("Day06_test_part1").forEach { line ->
val (input,solution) = line.split(" ")
println("part1(testInput): " + part1(input))
check(part1(input) == solution.toInt())
}
readInput("Day06_test_part2").forEach { line ->
val (input,solution) = line.split(" ")
println("part2(testInput): " + part2(input))
check(part2(input) == solution.toInt())
}
val input = readTextInput("Day06")
println("part1(input): " + part1(input))
println("part2(input): " + part2(input))
}
| 0 | Kotlin | 0 | 0 | bb2b689f48063d7a1b6892fc1807587f7050b9db | 1,104 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | stevennoto | 573,247,572 | false | {"Kotlin": 18058} | import kotlin.math.*
fun main() {
val GRID_SIZE_X = 700
val GRID_SIZE_Y = 170
val SAND_ORIGIN = Pair(500, 0)
// Return list of all points along line between 2 coordinate points
fun getAllPointsBetween(x:Pair<Int, Int>, y:Pair<Int, Int>): List<Pair<Int, Int>> {
if (x.first == y.first) return (min(x.second, y.second)..max(x.second, y.second)).toList().map { Pair(x.first, it) }
else if (x.second == y.second) return (min(x.first, y.first)..max(x.first, y.first)).toList().map { Pair(it, x.second) }
else return listOf()
}
// Create grid from input lines like "498,4 -> 498,6 -> 496,6"
fun createGrid(input: List<String>): Array<BooleanArray> {
val grid = Array(GRID_SIZE_X) { BooleanArray(GRID_SIZE_Y) }
input.forEach {
val points = it.split(" -> ").map { Pair(it.substringBefore(',').toInt(), it.substringAfter(',').toInt()) }
points.windowed(2) {
getAllPointsBetween(it.first(), it.last()).forEach {
grid[it.first][it.second] = true
}
}
}
return grid
}
// Determine where sand will settle, attempting to fall straight down, then down-left, then down-right, or null if won't settle
fun getPointWhereSandWillSettle(grid: Array<BooleanArray>): Pair<Int, Int>? {
var curX = SAND_ORIGIN.first
var curY = SAND_ORIGIN.second
while(true) {
// Try to settle down, then down-left, then down-right, then repeat. But if none of those then it's settled.
if(!grid[curX][curY + 1]) { curY++ }
else if(!grid[curX - 1][curY + 1]) { curX--; curY++ }
else if(!grid[curX + 1][curY + 1]) { curX++; curY++ }
else return Pair(curX, curY)
// If fallen below bottom threshold, it won't settle
if(curY + 1 >= grid[0].size) return null
}
}
fun part1(input: List<String>): Int {
// Create grid, see where sand settles until it doesn't anymore, return amount of sand that settled
val grid = createGrid(input)
var numSettled = 0
while(true) {
val settle = getPointWhereSandWillSettle(grid)
if (settle == null) return numSettled
numSettled++
grid[settle.first][settle.second] = true
}
}
fun part2(input: List<String>): Int {
// Create grid, see where sand settles until it doesn't anymore, return amount of sand that settled
val grid = createGrid(input)
// Additionally create ground level at 2 spaces beyond highest Y cordinate
val floorLevel = input.maxOf { it.split(" -> ").maxOf { it.substringAfter(',').toInt() } } + 2
getAllPointsBetween(Pair(0, floorLevel), Pair(GRID_SIZE_X - 1, floorLevel)).forEach {
grid[it.first][it.second] = true
}
var numSettled = 0
while(true) {
val settle = getPointWhereSandWillSettle(grid)
if (settle == null) return numSettled
numSettled++
if (settle == SAND_ORIGIN) return numSettled
grid[settle.first][settle.second] = true
}
}
// read input
val testInput = readInput("Day14_test")
val input = readInput("Day14")
// part 1 test and solution
check(part1(testInput) == 24)
println(part1(input))
// part 2 test and solution
check(part2(testInput) == 93)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 42941fc84d50b75f9e3952bb40d17d4145a3036b | 3,487 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/asaad/DayFive.kt | Asaad27 | 573,138,684 | false | {"Kotlin": 23483} | package asaad
import java.io.File
class DayFive(filePath: String) {
private val file = File(filePath)
private val input = readInput(file)
private fun readInput(file: File): Pair<List<String>, List<String>> {
val lines = file.readLines()
return lines.takeWhile { it.isNotBlank() } to lines.takeLastWhile { it.isNotBlank() }
}
fun result() {
println("\tpart 1: ${solve(Stacks::applyMove)}")
println("\tpart 2: ${solve(Stacks::applyMove2)}")
}
private fun solve(func: Stacks.(Move) -> Unit): String {
val stacks = Stacks(input.first)
for (line in input.second)
stacks.func(Move(line))
return stacks.getTops()
}
class Move(input: String){
operator fun component1(): Int = x
operator fun component2(): Int = from
operator fun component3(): Int = to
private val x: Int
private val from : Int
private val to: Int
init {
val split = input.split(" ")
x = split[1].toInt()
from = split[3].toInt()-1
to = split[5].toInt()-1
}
}
class Stacks(
input: List<String>
){
private val stacks :List<MutableList<String>>
init {
val stackNumbers = input.last().trim().split("\\s+".toRegex()).map { it.toInt() }
val maxNumber = stackNumbers.max()
stacks = List(maxNumber) { mutableListOf() }
for (line in input.size-2 downTo 0){
val split = input[line].chunked(4).map { it.trimEnd().removeSurrounding("[", "]") }
for (number in split.indices){
if (split[number] == "")
continue
stacks[number].add(split[number])
}
}
}
fun applyMove(move: Move){
val (x, from, to) = move
repeat(x){
stacks[to].add(stacks[from].last())
stacks[from].removeLast()
}
}
fun applyMove2(move: Move){
val (x, from, to) = move
stacks[to].addAll(stacks[from].takeLast(x))
repeat(x){
stacks[from].removeLast()
}
}
fun getTops() = stacks.joinToString("") { it.last() }
}
}
| 0 | Kotlin | 0 | 0 | 16f018731f39d1233ee22d3325c9933270d9976c | 2,348 | adventOfCode2022 | MIT License |
src/Day06.kt | lukewalker128 | 573,611,809 | false | {"Kotlin": 14077} | fun main() {
val testInput = readInput("Day06_test")
checkEquals(7, part1(testInput))
checkEquals(19, part2(testInput))
val input = readInput("Day06")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
/**
* Returns the position of the first start-of-packet marker in the given datastream.
*/
private fun part1(input: List<String>): Int {
return findUniqueWindow(input.first(), 4) + 1
}
/**
* Returns the ending position of the first window in the input string that comprises completely unique characters.
*/
private fun findUniqueWindow(input: String, windowSize: Int): Int {
require(input.length >= windowSize)
val charCounts = mutableMapOf<Char, Int>()
fun add(char: Char) {
charCounts[char] = charCounts.getOrDefault(char, 0) + 1
}
fun remove(char: Char) {
if (charCounts[char] == 1) {
charCounts.remove(char)
} else {
charCounts[char] = charCounts[char]!! - 1
}
}
// populate counts for the first windowSize - 1 characters
input.substring(0 until windowSize - 1).forEach { add(it) }
for (i in windowSize - 1..input.lastIndex) {
if (i - windowSize >= 0) {
remove(input[i - windowSize])
}
add(input[i])
if (charCounts.size == windowSize) {
// all characters in the window are unique
return i
}
}
return -1
}
/**
* Returns the position of the first start-of-message marker in the given datastream.
*/
private fun part2(input: List<String>): Int {
return findUniqueWindow(input.first(), 14) + 1
}
| 0 | Kotlin | 0 | 0 | c1aa17de335bd5c2f5f555ecbdf39874c1fb2854 | 1,645 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2018/Day22.kt | tginsberg | 155,878,142 | false | null | /*
* Copyright (c) 2018 by <NAME>
*/
/**
* Advent of Code 2018, Day 22 - Mode Maze
*
* Problem Description: http://adventofcode.com/2018/day/22
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day22/
*/
package com.ginsberg.advent2018
import java.util.PriorityQueue
class Day22(rawInput: List<String>) {
private val depth: Int = rawInput.first().substring(7).toInt()
private val target: Point = Point.of(rawInput.drop(1).first().substring(8))
private val cave = LazyGrid(target, depth)
fun solvePart1(): Int =
cave.riskLevel()
fun solvePart2(): Int =
cave.cheapestPath()?.cost ?: throw IllegalStateException("No path?! Really?!")
private class LazyGrid(val target: Point, val depth: Int) {
private val erosionLevels = mutableMapOf<Point, Int>()
fun riskLevel(at: Point = target): Int =
(0..at.y).flatMap { y ->
(0..at.x).map { x ->
Point(x, y).erosionLevel() % 3
}
}.sum()
fun cheapestPath(to: Point = target): Traversal? {
val seenMinimumCost: MutableMap<Pair<Point, Tool>, Int> = mutableMapOf(Point.origin to Tool.Torch to 0)
val pathsToEvaluate = PriorityQueue<Traversal>().apply {
add(Traversal(Point.origin, Tool.Torch))
}
while (pathsToEvaluate.isNotEmpty()) {
val thisPath = pathsToEvaluate.poll()
// Found it, and holding the correct tool
if (thisPath.end == to && thisPath.holding == Tool.Torch) {
return thisPath
}
// Candidates for our next set of decisions
val nextSteps = mutableListOf<Traversal>()
// Move to each neighbor, holding the same tool.
thisPath.end.cardinalNeighbors(false).forEach { neighbor ->
// Add a Traversal for each if we can go there without changing tools
if (thisPath.holding in neighbor.validTools()) {
// Can keep the tool.
nextSteps += thisPath.copy(
end = neighbor,
cost = thisPath.cost + 1
)
}
}
// Stay where we are and switch tools to anything we aren't using (but can)
thisPath.end.validTools().minus(thisPath.holding).forEach { tool ->
nextSteps += Traversal(
end = thisPath.end,
holding = tool,
cost = thisPath.cost + 7
)
}
// Of all possible next steps, add the ones we haven't seen, or have seen and we can now do cheaper.
nextSteps.forEach { step ->
val key = Pair(step.end, step.holding)
if (key !in seenMinimumCost || seenMinimumCost.getValue(key) > step.cost) {
pathsToEvaluate += step
seenMinimumCost[key] = step.cost
}
}
}
return null // No path!? Come on...
}
private fun Point.erosionLevel(): Int {
if (this !in erosionLevels) {
val geo = when {
this in erosionLevels -> erosionLevels.getValue(this)
this in setOf(Point.origin, target) -> 0
y == 0 -> x * 16807
x == 0 -> y * 48271
else -> left.erosionLevel() * up.erosionLevel()
}
erosionLevels[this] = (geo + depth) % 20183
}
return erosionLevels.getValue(this)
}
private fun Point.validTools(): Set<Tool> =
when (this) {
Point.origin -> setOf(Tool.Torch)
target -> setOf(Tool.Torch)
else -> Terrain.byErosionLevel(erosionLevel()).tools
}
}
private data class Traversal(val end: Point, val holding: Tool, val cost: Int = 0) : Comparable<Traversal> {
override fun compareTo(other: Traversal): Int =
this.cost.compareTo(other.cost)
}
private enum class Tool {
Torch,
Climbing,
Neither
}
private enum class Terrain(val modVal: Int, val tools: Set<Tool>) {
Rocky(0, setOf(Tool.Climbing, Tool.Torch)),
Wet(1, setOf(Tool.Climbing, Tool.Neither)),
Narrow(2, setOf(Tool.Torch, Tool.Neither));
companion object {
val values = arrayOf(Rocky, Wet, Narrow)
fun byErosionLevel(level: Int): Terrain =
values.first { it.modVal == level % 3 }
}
}
}
| 0 | Kotlin | 1 | 18 | f33ff59cff3d5895ee8c4de8b9e2f470647af714 | 4,841 | advent-2018-kotlin | MIT License |
src/Day03.kt | imavroukakis | 572,438,536 | false | {"Kotlin": 12355} | fun main() {
fun Char.priority() = if (this.isUpperCase()) {
this.code - 38
} else {
this.code - 96
}
fun common(input: List<Set<Char>>) = input.reduce { acc, chars ->
if (acc.isEmpty()) {
chars
} else {
chars.intersect(acc)
}
}.first()
fun part1(input: List<String>): Int = input.map { line ->
line.toList().chunked(line.length / 2).map { it.toSet() }
}.sumOf { common(it).priority() }
fun part2(input: List<String>): Int = input.chunked(3).map { group ->
group.map { it.toSet() }
}.sumOf { common(it).priority() }
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
println(part1(readInput("Day03")))
check(part2(testInput) == 70)
println(part2(readInput("Day03")))
}
| 0 | Kotlin | 0 | 0 | bb823d49058aa175d1e0e136187b24ef0032edcb | 836 | advent-of-code-kotlin | Apache License 2.0 |
src/Day04.kt | RandomUserIK | 572,624,698 | false | {"Kotlin": 21278} | private fun String.toRanges(): Pair<IntRange, IntRange> =
substringBefore(",").toRange() to substringAfter(",").toRange()
private fun String.toRange(): IntRange = substringBefore("-").toInt()..substringAfter("-").toInt()
private infix fun IntRange.containsAll(other: IntRange): Boolean =
first <= other.first && last >= other.last
private infix fun IntRange.overlaps(other: IntRange): Boolean =
first <= other.last && last >= other.first
fun main() {
fun part1(input: List<String>): Int =
input
.map { it.toRanges() }
.fold(0) { acc, (left, right) ->
acc + when {
left containsAll right || right containsAll left -> 1
else -> 0
}
}
fun part2(input: List<String>): Int =
input
.map { it.toRanges() }
.fold(0) { acc, (left, right) ->
acc + when {
left overlaps right -> 1
else -> 0
}
}
val input = readInput("inputs/day04_input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | f22f10da922832d78dd444b5c9cc08fadc566b4b | 945 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/niemeyer/aoc2022/Day02.kt | stefanniemeyer | 572,897,543 | false | {"Kotlin": 175820, "Shell": 133} | /**
* Advent of Code 2022, Day 2: Rock Paper Scissors
* Problem Description: https://adventofcode.com/2022/day/2
*/
package de.niemeyer.aoc2022
import de.niemeyer.aoc.utils.Resources.resourceAsList
import de.niemeyer.aoc.utils.getClassName
fun main() {
fun part1(input: List<Pair<String, String>>): Int =
input.fold(0) { acc, op ->
acc + score(op.first, op.second)
}
fun part2(input: List<Pair<String, String>>): Int =
input.fold(0) { acc, op ->
acc + score(op.first, op.second)
}
val name = getClassName()
val testInput = resourceAsList(fileName = "${name}_test.txt").map { it.toPair() }
val puzzleInput = resourceAsList(fileName = "${name}.txt").map { it.toPair() }
check(part1(testInput) == 15)
println(part1(puzzleInput))
check(part1(puzzleInput) == 12156)
val testInput2 = resourceAsList(fileName = "${name}_test.txt").map { it.toPairByResult() }
val puzzleInput2 = resourceAsList(fileName = "${name}.txt").map { it.toPairByResult() }
check(part2(testInput2) == 12)
println(part2(puzzleInput2))
check(part2(puzzleInput2) == 10835)
}
fun String.toPair(): Pair<String, String> =
this.split(" ").let { it[0].toElfShape() to it[1].toElfShape() }
fun String.toPairByResult(): Pair<String, String> =
this.split(" ").let { it[0].toElfShape() to it[1].toShapeByResult(it[0].toElfShape()) }
fun String.toElfShape(): String = when (this) {
"X" -> "R"
"Y" -> "P"
"Z" -> "S"
"A" -> "R"
"B" -> "P"
"C" -> "S"
else -> throw IllegalArgumentException("Unknown shape: $this")
}
fun String.toShapeByResult(elf: String): String =
when (this) {
"Y" -> elf // draw
"X" -> when (elf) { // lose
"R" -> "S"
"P" -> "R"
"S" -> "P"
else -> throw IllegalArgumentException("Unknown shape: $elf")
}
"Z" -> when (elf) { // win
"R" -> "P"
"P" -> "S"
"S" -> "R"
else -> throw IllegalArgumentException("Unknown shape: $elf")
}
else -> throw IllegalArgumentException("Unknown result: $this")
}
fun shapeScore(shape: String) =
when (shape) {
"R" -> 1
"P" -> 2
"S" -> 3
else -> 0
}
fun score(elf: String, player: String): Int {
val baseScore = shapeScore(player)
if (elf == player) {
return 3 + baseScore
}
when (player) {
"R" -> if (elf == "S") return 6 + baseScore
"P" -> if (elf == "R") return 6 + baseScore
"S" -> if (elf == "P") return 6 + baseScore
}
return 0 + baseScore
}
// A, X Rock 1
// B, Y Paper 2
// C, Z Scissors 3
// X lose
// Y draw
// Z win
| 0 | Kotlin | 0 | 0 | ed762a391d63d345df5d142aa623bff34b794511 | 2,759 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/day16/part2/Part2.kt | bagguley | 329,976,670 | false | null | package day16.part2
import day16.data
fun main() {
val input = data
val rules = input[0].split("\n").map { parseRule(it) }
val myTicket = input[1].split("\n")[1].split(",").map { it.toInt() }
val nearBy = input[2].split("\n").drop(1).map{it.split(",").map { it.toInt() }}
val validTickets = nearBy.filter { isValid(it, rules) }
val ruleOptions = validTickets.first().map{ rules.toMutableList() }
validTickets.forEach { it.forEachIndexed{ index, num ->
ruleOptions[index].removeIf{ rule -> !rule.isInRange(num)}
} }
while(ruleOptions.filter { it.size != 1 }.flatten().isNotEmpty()) {
val single = ruleOptions.filter { it.size == 1 }.flatten()
ruleOptions.forEach { if (it.size > 1) it.removeAll(single) }
}
val departureOptions = ruleOptions.flatten().mapIndexed{index, rule -> Pair(index, rule.isDeparture())}.filter { it.second }
println(departureOptions.map { myTicket[it.first].toLong() }.reduce { acc, i -> acc * i})
}
fun isValid(list: List<Int>, rules:List<Rule>): Boolean{
return list.stream().allMatch{ t -> rules.stream().anyMatch { it.isInRange(t) } }
} | 0 | Kotlin | 0 | 0 | 6afa1b890924e9459f37c604b4b67a8f2e95c6f2 | 1,149 | adventofcode2020 | MIT License |
src/Day04.kt | vi-quang | 573,647,667 | false | {"Kotlin": 49703} |
fun main() {
class Elf(range: String) {
val sectionIdList = mutableSetOf<Int>()
init {
add(range)
}
fun add(range: String) {
val token = range.split("-")
val (rangeMin, rangeMax) = token[0].toInt() to token[1].toInt()
for (i in rangeMin .. rangeMax) {
sectionIdList.add(i)
}
}
}
fun Elf.fullyContainsOrIsFullyContained(other : Elf) : Boolean {
val intersection = this.sectionIdList.intersect(other.sectionIdList)
return (intersection.size == other.sectionIdList.size || intersection.size == this.sectionIdList.size)
}
fun Elf.hasIntersection(other : Elf) : Boolean {
val intersection = this.sectionIdList.intersect(other.sectionIdList)
return (intersection.isNotEmpty())
}
fun createElfPairList(input: List<String>) : MutableList<Pair<Elf, Elf>> {
val elfPairList = mutableListOf<Pair<Elf, Elf>>()
for (line in input) {
val token = line.split(",")
val pair = (Elf(token[0]) to Elf(token[1]))
elfPairList.add(pair)
}
return elfPairList
}
fun part1(input: List<String>): Int {
val elfPairList = createElfPairList(input)
val resultList = mutableListOf<Pair<Elf, Elf>>()
for (pair in elfPairList) {
if (pair.first.fullyContainsOrIsFullyContained(pair.second)) {
resultList.add(pair)
}
}
return resultList.size
}
fun part2(input: List<String>): Int {
val elfPairList = createElfPairList(input)
val resultList = mutableListOf<Pair<Elf, Elf>>()
for (pair in elfPairList) {
if (pair.first.hasIntersection(pair.second)) {
resultList.add(pair)
}
}
return resultList.size
}
val input = readInput(4)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | ae153c99b58ba3749f16b3fe53f06a4b557105d3 | 1,988 | aoc-2022 | Apache License 2.0 |
src/Day09.kt | benwicks | 572,726,620 | false | {"Kotlin": 29712} | import kotlin.math.abs
fun main() {
fun parseMoves(input: List<String>): List<Pair<Char, Int>> {
val headMoves = input.map {
val pair = it.split(" ").take(2)
Pair(pair[0][0], pair[1].toInt())
}
return headMoves
}
fun getLocationsVisitedFromMoves(headMoves: List<Pair<Char, Int>>): List<Pair<Int, Int>> {
val headLocationsVisited = mutableListOf(0 to 0)
for (move in headMoves) {
var previousHeadX = headLocationsVisited.last().first
var previousHeadY = headLocationsVisited.last().second
val spacesToMove = move.second
val directionToMove = move.first
for (step in 1..spacesToMove) {
val newHeadLocation: Pair<Int, Int> = when (directionToMove) {
'R' -> (previousHeadX + 1) to previousHeadY
'L' -> (previousHeadX - 1) to previousHeadY
'U' -> previousHeadX to (previousHeadY + 1)
else -> previousHeadX to (previousHeadY - 1)
}
previousHeadX = newHeadLocation.first
previousHeadY = newHeadLocation.second
headLocationsVisited += previousHeadX to previousHeadY
}
}
return headLocationsVisited
}
fun getTailLocationsVisited(headLocationsVisited: List<Pair<Int, Int>>): List<Pair<Int, Int>> {
val tailLocationsVisited = mutableListOf(0 to 0)
for (headLocation in headLocationsVisited) {
val tailLocation = tailLocationsVisited.last()
if (headLocation != tailLocation &&
(abs(tailLocation.first - headLocation.first) > 1 ||
abs(tailLocation.second - headLocation.second) > 1)
) {
// catch tail up
val newTailLocation = if (tailLocation.first == headLocation.first) {
// move vertically (up or down?)
val newTailY = if (headLocation.second > tailLocation.second) {
headLocation.second - 1
} else {
headLocation.second + 1
}
tailLocation.first to newTailY
} else if (tailLocation.second == headLocation.second) {
// move horizontally (left or right?)
val newTailX = if (headLocation.first > tailLocation.first) {
headLocation.first - 1
} else {
headLocation.first + 1
}
newTailX to tailLocation.second
} else {
// move diagonally
if (headLocation.first > tailLocation.first) { // move right
if (headLocation.second > tailLocation.second) { // move up
tailLocation.first + 1 to tailLocation.second + 1
} else { // move down
tailLocation.first + 1 to tailLocation.second - 1
}
} else { // move left
if (headLocation.second > tailLocation.second) { // move up
tailLocation.first - 1 to tailLocation.second + 1
} else { // move down
tailLocation.first - 1 to tailLocation.second - 1
}
}
}
tailLocationsVisited += newTailLocation
}
}
return tailLocationsVisited
}
fun part1(input: List<String>): Int {
val headMoves = parseMoves(input)
// Simulate your complete hypothetical series of motions.
// How many positions does the tail of the rope visit at least once?
val headLocationsVisited = getLocationsVisitedFromMoves(headMoves)
val tailLocationsVisited = getTailLocationsVisited(headLocationsVisited)
return tailLocationsVisited.toSet().size
}
fun part2(input: List<String>): Int {
val headMoves = parseMoves(input)
// Now there are 10 knots, not 2
var tailLocationsVisited = getTailLocationsVisited(getLocationsVisitedFromMoves(headMoves))
for (i in 2..9) {
tailLocationsVisited = getTailLocationsVisited(tailLocationsVisited)
}
return tailLocationsVisited.toSet().size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fbec04e056bc0933a906fd1383c191051a17c17b | 4,812 | aoc-2022-kotlin | Apache License 2.0 |
src/Day08.kt | konclave | 573,548,763 | false | {"Kotlin": 21601} | fun main() {
fun solve1(trees: List<String>): Int {
return trees.foldIndexed(0) {
rowIdx, total, row ->
if (rowIdx == 0 || rowIdx == trees.size - 1) {
total + row.length
} else {
total + row.foldIndexed(0) { colIdx, countCol, char ->
if (colIdx == 0 || colIdx == trees[rowIdx].length - 1) {
countCol + 1
} else {
var isVisibleTop = true
var isVisibleBottom = true
var isVisibleLeft = true
var isVisibleRight = true
for(idx in (colIdx - 1)downTo 0) {
if (row[idx] >= char) {
isVisibleLeft = false
break
}
}
for(idx in (colIdx + 1) until row.length) {
if (row[idx] >= char) {
isVisibleRight = false
break
}
}
for(idx in rowIdx - 1 downTo 0 ) {
if (trees[idx][colIdx] >= char) {
isVisibleTop = false
break
}
}
for(idx in (rowIdx + 1) until trees.size) {
if (trees[idx][colIdx] >= char) {
isVisibleBottom = false
break
}
}
countCol + if (isVisibleLeft || isVisibleRight || isVisibleTop || isVisibleBottom) 1 else 0
}
}
}
}
}
fun solve2(trees: List<String>): Int {
return trees.foldIndexed(0) {
rowIdx, totalScore, row ->
val rowScore = row.foldIndexed(0) { colIdx, colScore, char ->
var topScore = 0
var bottomScore = 0
var leftScore = 0
var rightScore = 0
if (colIdx > 0) {
leftScore = 1
for (idx in (colIdx - 1) downTo 0) {
if (row[idx] >= char) {
leftScore = colIdx - idx
break
}
leftScore = colIdx
}
}
if (colIdx < row.length - 1) {
rightScore = 1
for (idx in (colIdx + 1) until row.length) {
if (row[idx] >= char) {
rightScore = idx - colIdx
break
}
rightScore = row.length - colIdx - 1
}
}
if (rowIdx > 0) {
topScore = 1
for (idx in rowIdx - 1 downTo 0) {
if (trees[idx][colIdx] >= char) {
topScore = rowIdx - idx
break
}
topScore = rowIdx
}
}
if (rowIdx < trees.size - 1) {
bottomScore = 1
for (idx in (rowIdx + 1) until trees.size) {
if (trees[idx][colIdx] >= char) {
bottomScore = idx - rowIdx
break
}
bottomScore = trees.size - rowIdx - 1
}
}
colScore.coerceAtLeast(topScore * rightScore * bottomScore * leftScore)
}
rowScore.coerceAtLeast(totalScore)
}
}
val input = readInput("Day08")
println(solve1(input))
println(solve2(input))
}
| 0 | Kotlin | 0 | 0 | 337f8d60ed00007d3ace046eaed407df828dfc22 | 4,243 | advent-of-code-2022 | Apache License 2.0 |
AdventOfCode/Challenge2023Day12.kt | MartinWie | 702,541,017 | false | {"Kotlin": 90565} | import java.io.File
import kotlin.test.Test
import kotlin.test.assertEquals
class Challenge2023Day12 {
private fun solve1(lines: List<String>): Int {
var result = 0
lines.forEach { line ->
val (springRow, controlRow) = line.split(" ")
val controlNumbers = controlRow.split(",").map { it.toInt() }
val totalSprings = controlNumbers.sum()
val unassignedSprings = totalSprings - springRow.count { it == '#' }
val possibleSpringPositions =
springRow.mapIndexedNotNull { index, char ->
if (char == '?') index else null
}
possibleSpringPositions.getCombinations(unassignedSprings).forEach {
val tmpLine = StringBuilder(springRow)
for (char in it) {
tmpLine[char] = '#'
}
if (isValidMap(tmpLine.toString(), controlNumbers)) {
result++
}
}
}
return result
}
private fun <T> List<T>.getCombinations(combLength: Int): Sequence<List<T>> {
if (combLength == 0) return sequenceOf(emptyList())
if (size <= combLength) return sequenceOf(this)
return sequence {
val head = take(1)
val tail = drop(1)
// All combinations with head
tail.getCombinations(combLength - 1).forEach { yield(head + it) }
// All combinations without head
tail.getCombinations(combLength).forEach { yield(it) }
}
}
private fun isValidMap(
springRow: String,
controlNumbers: List<Int>,
): Boolean {
val pattern = Regex("#+")
val matches = pattern.findAll(springRow)
if (matches.count() != controlNumbers.size) return false
matches.forEachIndexed {
index, matchResult ->
if (matchResult.value.length != controlNumbers[index]) {
return false
}
}
return true
}
@Test
fun test() {
val lines = File("./AdventOfCode/Data/Day12-1-Test-Data.txt").bufferedReader().readLines()
val exampleSolution1 = solve1(lines)
println("Example solution 1: $exampleSolution1")
assertEquals(21, exampleSolution1)
val realLines = File("./AdventOfCode/Data/Day12-1-Data.txt").bufferedReader().readLines()
val solution1 = solve1(realLines)
println("Solution 1: $solution1")
assertEquals(7407, solution1)
}
}
| 0 | Kotlin | 0 | 0 | 47cdda484fabd0add83848e6000c16d52ab68cb0 | 2,567 | KotlinCodeJourney | MIT License |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day17/Day17.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day17
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector3D
import net.olegg.aoc.utils.Vector4D
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 17](https://adventofcode.com/2020/day/17)
*/
object Day17 : DayOf2020(17) {
private val NEIGHBORS_3D =
(-1..1).flatMap { x ->
(-1..1).flatMap { y ->
(-1..1).map { z ->
Vector3D(x, y, z)
}
}
} - Vector3D()
private val NEIGHBORS_4D =
(-1..1).flatMap { x ->
(-1..1).flatMap { y ->
(-1..1).flatMap { z ->
(-1..1).map { w ->
Vector4D(x, y, z, w)
}
}
}
} - Vector4D()
override fun first(): Any? {
val items = lines.map { line -> line.map { it == '#' } }
val initialState = items
.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, value ->
if (value) Vector3D(x, y, 0) else null
}
}
.toSet()
val finalState = (0..<6).fold(initialState) { state, _ ->
val neighborCount = state.flatMap { it.neighbors3D() }
.groupingBy { it }
.eachCount()
val alive = state.filter { neighborCount[it] in 2..3 }
val born = neighborCount.filter { it.key !in state && it.value == 3 }.map { it.key }
return@fold (alive + born).toSet()
}
return finalState.size
}
override fun second(): Any? {
val items = lines.map { line -> line.map { it == '#' } }
val initialState = items
.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, value ->
if (value) Vector4D(x, y, 0, 0) else null
}
}
.toSet()
val finalState = (0..<6).fold(initialState) { state, _ ->
val neighborCount = state.flatMap { it.neighbors4D() }
.groupingBy { it }
.eachCount()
val alive = state.filter { neighborCount[it] in 2..3 }
val born = neighborCount.filter { it.key !in state && it.value == 3 }.map { it.key }
return@fold (alive + born).toSet()
}
return finalState.size
}
private fun Vector3D.neighbors3D(): List<Vector3D> {
return NEIGHBORS_3D.map { this + it }
}
private fun Vector4D.neighbors4D(): List<Vector4D> {
return NEIGHBORS_4D.map { this + it }
}
}
fun main() = SomeDay.mainify(Day17)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,320 | adventofcode | MIT License |
src/main/kotlin/net/wrony/aoc2023/a2/Main.kt | kopernic-pl | 727,133,267 | false | {"Kotlin": 52043} | package net.wrony.aoc2023.a2
import kotlin.io.path.Path
import kotlin.io.path.readText
data class Draw(val reds: Int, val greens: Int, val blues: Int) {
constructor(): this(0,0,0)
operator fun plus(other: Draw): Draw =
Draw(reds + other.reds, greens + other.greens, blues + other.blues)
fun power(): Int = reds * greens * blues
override fun toString(): String = "|r$reds, g$greens, b$blues|"
}
data class Game(val id: Int, val draws: List<Draw>) {
fun isPossible(reds: Int, greens: Int, blues: Int): Boolean {
return draws.all { it.reds<= reds && it.greens <= greens && it.blues <= blues}
}
fun fewestCubes(): Draw {
return Draw(draws.maxOf { it.reds }, draws.maxOf { it.greens }, draws.maxOf { it.blues })
}
}
fun lineToGameAndDraws(line: String) : Pair<Int, List<List<String>>> {
return line.split(": ")
.let { (gamePart, drawsPart) ->
gamePart.removePrefix("Game ").toInt() to drawsPart.split("; ").map { it.split(", ") }
}
}
fun parseDraw(draw: List<String>): Draw {
return draw.map {
val (count, color) = it.split(" ")
when (color) {
"red" -> Draw(count.toInt(), 0, 0)
"green" -> Draw(0, count.toInt(), 0)
"blue" -> Draw(0, 0, count.toInt())
else -> throw Exception("Unknown color $color")
}
}.fold(Draw()) { acc, d -> acc + d }
}
fun main() {
println (
Path("src/main/resources/2.txt").readText().lineSequence()
.map { lineToGameAndDraws(it) }
.map { (gameId, draws) -> Game(gameId, draws.map { parseDraw(it) }) }
.filter { it.isPossible(12, 13, 14) }
.sumOf { it.id }
)
//tried 279 - X
//tried 2416 - OK
println (
Path("src/main/resources/2.txt").readText().lineSequence()
.map { lineToGameAndDraws(it) }
.map { (gameId, draws) -> Game(gameId, draws.map { parseDraw(it) }) }
.map { it.fewestCubes() }
.sumOf { it.power() }
)
//tried 63307 - OK
} | 0 | Kotlin | 0 | 0 | 1719de979ac3e8862264ac105eb038a51aa0ddfb | 2,055 | aoc-2023-kotlin | MIT License |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day09.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
import at.mpichler.aoc.lib.Vector2i
import kotlin.math.absoluteValue
import kotlin.math.sign
open class Part9A : PartSolution() {
private lateinit var commands: MutableList<Command>
internal lateinit var pos: MutableList<Vector2i>
override fun parseInput(text: String) {
commands = mutableListOf()
for (line in text.trim().split("\n")) {
val parts = line.split(" ")
commands.add(Command(Direction(parts[0]), parts[1].toInt()))
}
}
override fun config() {
pos = MutableList(2) { Vector2i() }
}
override fun compute(): Int {
val positions = mutableListOf<Vector2i>()
var count = 0
for (command in commands) {
repeat(command.count) {
move(command.direction, pos)
if (!positions.contains(pos.last())) {
positions.add(pos.last())
count += 1
}
}
}
return count
}
private fun move(direction: Direction, pos: MutableList<Vector2i>) {
pos[0] = moveHead(direction, pos[0])
for (i in 1..<pos.size) {
pos[i] = moveTail(pos[i - 1], pos[i])
}
}
private fun moveHead(direction: Direction, pos: Vector2i): Vector2i {
return direction.dir + pos
}
private fun moveTail(headPos: Vector2i, tailPos: Vector2i): Vector2i {
val diff = headPos - tailPos
if (diff.x.absoluteValue > 1) {
if (headPos.y == tailPos.y) {
return Vector2i(tailPos.x + diff.x.sign, tailPos.y)
}
return Vector2i(tailPos.x + diff.x.sign, tailPos.y + diff.y.sign)
} else if (diff.y.absoluteValue > 1) {
if (headPos.x == tailPos.x) {
return Vector2i(tailPos.x, tailPos.y + diff.y.sign)
}
return Vector2i(tailPos.x + diff.x.sign, tailPos.y + diff.y.sign)
}
return tailPos
}
override fun getExampleAnswer(): Int {
return 13
}
override fun getExampleInput(): String? {
return """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent()
}
private data class Command(val direction: Direction, val count: Int)
private fun Direction(value: String): Direction {
return Direction.entries.first { it.value == value.first() }
}
private enum class Direction(val value: Char, val dir: Vector2i) {
UP('U', Vector2i(0, -1)),
DOWN('D', Vector2i(0, 1)),
LEFT('L', Vector2i(-1, 0)),
RIGHT('R', Vector2i(1, 0)),
}
}
class Part9B : Part9A() {
override fun config() {
pos = MutableList(10) { Vector2i() }
}
override fun getExampleAnswer(): Int {
return 1
}
}
fun main() {
Day(2022, 9, Part9A(), Part9B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 3,041 | advent-of-code-kotlin | MIT License |
Retos/Reto #28 - EXPRESIÓN MATEMÁTICA [Media]/kotlin/IsTheMartin.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} | /*
* Crea una función que reciba una expresión matemática (String)
* y compruebe si es correcta. Retornará true o false.
* - Para que una expresión matemática sea correcta debe poseer
* un número, una operación y otro número separados por espacios.
* Tantos números y operaciones como queramos.
* - Números positivos, negativos, enteros o decimales.
* - Operaciones soportadas: + - * / %
*
* Ejemplos:
* "5 + 6 / 7 - 4" -> true
* "5 a 6" -> false
*
* Algunos casos testeados:
* "5 + 6 / 7 - 4" -> true
* "5 a 6" -> false
* "-10.2.1 * 10" -> false
* "20.0 * -1.01" -> true
* "1.000001 * / 1000" -> false
* "*10 + 29" -> false
* "/ 10" -> false
* "-20 * 32 *" -> false
* "30 *" -> false
* "20 20" -> false
*/
private val operators = listOf("+", "-", "*", "/", "%")
private val separator = " "
fun main() {
val expression = "5 + 6 / 7 - 4"
val isValidExpression = mathExpression(expression)
println("Expresion valida? $expression -> $isValidExpression")
}
fun mathExpression(input: String): Boolean {
val splitExpression = input.split(separator)
return if (splitExpression.count() > 2 &&
!startsOrEndsWithOperator(splitExpression.first(), splitExpression.last())) {
var previousOperator = ""
var previousNumber = ""
var isValidExpression = true
splitExpression.forEach { expression ->
if(expression.isNumber() && previousNumber.isEmpty()) {
previousNumber = expression
previousOperator = ""
return@forEach
}
if (expression.isOperator() && previousOperator.isEmpty()) {
previousOperator = expression
previousNumber = ""
return@forEach
}
isValidExpression = false
}
isValidExpression
} else {
false
}
}
private fun startsOrEndsWithOperator(first: String, last: String): Boolean {
return operators.contains(first) || operators.contains(last)
}
private fun String.isNumber(): Boolean {
return try {
this.toDouble()
true
} catch (e: NumberFormatException) {
false
}
}
private fun String.isOperator(): Boolean {
return operators.contains(this)
}
| 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 2,274 | retos-programacion-2023 | Apache License 2.0 |
src/Day07.kt | SergeiMikhailovskii | 573,781,461 | false | {"Kotlin": 32574} | val suitableDirs = mutableListOf<NodeWithSize>()
var needSpace = 0
fun main() {
val inputList = readInput("Day07_test").filter { it != "\$ ls" && it != "\$ cd /" }
val root = Node("/")
var currentDir: Node? = root
inputList.forEach {
if (it.contains("dir")) {
val dirName = it.split(" ")[1]
val dir = Node(name = dirName)
currentDir?.addChild(dir)
} else if (it.contains("\$ cd")) {
val param = it.split(" ")[2]
if (param == "..") {
currentDir = currentDir?.parent
} else {
currentDir = currentDir?.children?.first { it.name == param }
}
} else {
val size = it.split(" ")[0].toInt()
val name = it.split(" ")[1]
currentDir?.addChild(Leaf(size, name))
}
}
needSpace = getNodeSize(root) - 40_000_000
suitableDirs.clear()
findAvailableDirs(root)
println(suitableDirs.minBy { it.size })
}
open class Node(
val name: String,
val children: MutableList<Node>? = mutableListOf(),
var parent: Node? = null,
) {
fun addChild(node: Node): Node {
node.parent = this
children?.add(node)
return node
}
}
fun getNodeSize(node: Node): Int {
var size = 0
node.children?.forEach {
size += if (it is Leaf) {
it.size
} else {
getNodeSize(it)
}
}
if (size > needSpace) {
suitableDirs.add(NodeWithSize(node, size))
}
return size
}
fun findAvailableDirs(node: Node) {
var size = 0
node.children?.forEach {
size += if (it is Leaf) {
it.size
} else {
getNodeSize(it)
}
}
}
class Leaf(
val size: Int,
name: String
) : Node(children = null, name = name)
data class NodeWithSize(
val node: Node,
val size: Int
) | 0 | Kotlin | 0 | 0 | c7e16d65242d3be6d7e2c7eaf84f90f3f87c3f2d | 1,912 | advent-of-code-kotlin | Apache License 2.0 |
src/Day03.kt | michaelYuenAE | 573,094,416 | false | {"Kotlin": 74685} | fun main() {
fun part1(input: List<String>): Int {
// val letterScoreMap = getMap()
// var sum = 0
// input.forEach {
// val firstCompartment = it.substring(0, (it.length/2)).toSet()
// val secondCompartment = it.substring((it.length/2), it.length).toSet()
// val intersect = firstCompartment.intersect(secondCompartment)
// val total = getScore(intersect, letterScoreMap)
// println("intersect, $intersect")
// println("total, $total")
// sum += total
// }
return input.size
}
val input = readInput("day3_input")
println(Day3(input).solvePart2())
}
class Day3(input: List<String>) {
private val priorities = let {
var priority = 1
(('a'..'z') + ('A'..'Z')).associateWith { priority++ }
}
private fun Char.priority() = priorities.getValue(this)
/**
* List of elf groups, each elf in each group have a rucksack with a set containing all items
* (ignoring the compartments)
*/
private val elfGroups = input.map { it.toSet() }.chunked(3)
fun solvePart2(): Int {
println(elfGroups)
return elfGroups.sumOf { it[0].intersect(it[1]).intersect(it[2]).first().priority() }
}
} | 0 | Kotlin | 0 | 0 | ee521263dee60dd3462bea9302476c456bfebdf8 | 1,280 | advent22 | Apache License 2.0 |
src/Day13.kt | l8nite | 573,298,097 | false | {"Kotlin": 105683} | class Node(var value: Int?, var isList: Boolean = false, val list: MutableList<Node> = mutableListOf()) {
fun withWrapper(op: ((Node) -> (Int))): Int {
if (isList) { throw Exception("Can't wrap a list node") }
isList = true
list.add(Node(value))
value = null
val result = op(this)
isList = false
value = list.first().value
list.clear()
return result
}
override fun toString(): String {
return if (!isList) {
value?.toString() ?: ""
} else {
"[${list.joinToString(",", transform = Node::toString)}]"
}
}
}
fun Regex.splitWithDelimiter(input: CharSequence) = Regex("((?<=%1\$s)|(?=%1\$s))".format(this.pattern)).split(input)
fun main() {
fun compareTwo(left: Node, right: Node): Int {
if (!left.isList && !right.isList) {
return left.value!!.compareTo(right.value!!)
}
if (left.isList && right.isList) {
left.list.indices.forEach { li ->
if (li > right.list.lastIndex) {
return 1
}
val result = compareTwo(left.list[li], right.list[li])
if (result == -1) {
return result
} else if (result == 1) {
return result
}
}
return if (left.list.size < right.list.size) {
-1
} else {
0
}
}
return if (!left.isList) {
left.withWrapper { compareTwo(it, right) }
} else {
right.withWrapper { compareTwo(left, it) }
}
}
fun parse(input: String): Node {
val stack = mutableListOf<Node>()
var last: Node? = null
"[\\[\\],]".toRegex().splitWithDelimiter(input).forEach {
val x = it.toIntOrNull()
if (it == "[") {
val node = Node(null, true)
if (stack.lastOrNull() != null) {
stack.last().list.add(node)
}
stack.add(node)
}
else if (x != null) {
stack.last().list.add(Node(x))
}
else if (it == ",") {
// noop
}
else if (it == "]") {
last = stack.removeLast()
}
}
return last!!
}
fun part1(input: List<String>): Int {
val nodes = input.windowed(2, 3).flatten().map { parse(it) }
val indices = mutableListOf<Int>()
nodes.chunked(2).forEachIndexed { i, pair ->
if (compareTwo(pair[0], pair[1]) < 1) {
indices.add(i + 1)
}
}
return indices.sum()
}
fun makeDivider(v: Int): Node {
val outerList = Node(null, true)
val innerList = Node(null, true)
val valueNode = Node(v)
innerList.list.add(valueNode)
outerList.list.add(innerList)
return outerList
}
fun part2(input: List<String>): Int {
val dividers = listOf(makeDivider(2), makeDivider(6))
val nodes = listOf(
input.windowed(2, 3).flatten().map { parse(it) },
dividers
).flatten().sortedWith { left, right -> compareTwo(left, right) }
val indices = mutableListOf<Int>()
nodes.forEachIndexed { i, it ->
if (dividers.contains(it)) {
indices.add(i + 1)
}
}
return indices.reduce { acc, i -> acc * i }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f74331778fdd5a563ee43cf7fff042e69de72272 | 3,866 | advent-of-code-2022 | Apache License 2.0 |
src/main/Day02.kt | lifeofchrome | 574,709,665 | false | {"Kotlin": 19233} | package main
import readInput
fun main() {
val input = readInput("Day02")
val day2 = Day02(input)
day2.process()
print("Part 1: ${day2.part1()}\n")
print("Part 2: ${day2.part2()}")
}
class Day02(private val input: List<String>) {
private val rounds = mutableListOf<Pair<Shape, Shape>>()
fun process() {
var first: Shape
var second: Shape
for (round in input) {
first = when (round[0]) {
'A' -> Shape.ROCK
'B' -> Shape.PAPER
'C' -> Shape.SCISSORS
else -> error("Opponent's shape is invalid: $round")
}
second = when (round[2]) {
'X' -> Shape.ROCK
'Y' -> Shape.PAPER
'Z' -> Shape.SCISSORS
else -> error("Player's shape is invalid: $round")
}
rounds.add(Pair(first, second))
}
}
private fun isTie(round: Pair<Shape, Shape>): Boolean {
return round.first == round.second
}
private fun isWin(round: Pair<Shape, Shape>): Boolean {
if (round.second == Shape.ROCK && round.first == Shape.SCISSORS) {
return true
} else if (round.second == Shape.PAPER && round.first == Shape.ROCK) {
return true
} else if (round.second == Shape.SCISSORS && round.first == Shape.PAPER) {
return true
}
return false
}
private fun isLoss(round: Pair<Shape, Shape>): Boolean {
return !isTie(round) && !isWin(round)
}
fun part1(): Int {
var score = 0
for (round in rounds) {
score += round.second.value
score += if (isLoss(round)) {
0
} else if(isWin(round)) {
6
} else {
3
}
}
return score
}
fun part2(): Int {
var score = 0
val table: List<List<Shape>> = listOf(listOf(Shape.SCISSORS, Shape.ROCK, Shape.PAPER), listOf(Shape.ROCK, Shape.PAPER, Shape.SCISSORS), listOf(Shape.PAPER, Shape.SCISSORS, Shape.ROCK))
for(round in rounds) {
val playerShape = table[round.first.value - 1][round.second.value - 1]
val newRound = Pair(round.first, playerShape)
score += playerShape.value
score += if (isLoss(newRound)) {
0
} else if(isWin(newRound)) {
6
} else {
3
}
}
return score
}
}
enum class Shape(val value: Int) {
ROCK(1), PAPER(2), SCISSORS(3)
} | 0 | Kotlin | 0 | 0 | 6c50ea2ed47ec6e4ff8f6f65690b261a37c00f1e | 2,623 | aoc2022 | Apache License 2.0 |
src/main/java/com/booknara/problem/stack/LargestRectangleHistogramKt.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.stack
/**
* 84. Largest Rectangle in Histogram (Hard)
* https://leetcode.com/problems/largest-rectangle-in-histogram/
*/
class LargestRectangleHistogramKt {
var totalMax = 0
// TLE error because of T:O(nlogn), S:O(logn)
fun largestRectangleArea1(heights: IntArray): Int {
// input check, heights.length >= 1
divide(heights, 0, heights.size - 1)
return totalMax
}
fun divide(heights: IntArray, start: Int, end: Int) {
// base case
if (start == end) {
totalMax = Math.max(totalMax, heights[start])
return
}
val index = findMin(heights, start, end)
totalMax = Math.max(totalMax, heights[index] * (end - start + 1))
if (start != index) {
// left
divide(heights, start, index - 1)
}
if (end != index) {
// right
divide(heights, index + 1, end)
}
}
fun findMin(heights: IntArray, start: Int, end: Int): Int {
var min = Int.MAX_VALUE // height value is less than 10^4
var index = -1
for (i in start until end + 1) {
if (heights[i] < min) {
min = heights[i]
index = i
}
}
return index
}
// TLE error because of T:O(n^2), S:O(1)
fun largestRectangleArea2(heights: IntArray): Int {
// input check, heights.length >= 1
var max = 0
for (i in heights.indices) {
var minHeight = heights[i]
for (j in i until heights.size) {
minHeight = Math.min(minHeight, heights[j])
max = Math.max(max, (j - i + 1) * minHeight)
}
}
return max
}
} | 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 1,569 | playground | MIT License |
src/2023/Day05.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2023`
import java.io.File
import java.lang.RuntimeException
import java.util.*
import kotlin.math.max
import kotlin.math.min
fun main() {
Day05().solve()
}
class Day05 {
val input1 = """
seeds: 79 14 55 13
seed-to-soil map:
50 98 2
52 50 48
soil-to-fertilizer map:
0 15 37
37 52 2
39 0 15
fertilizer-to-water map:
49 53 8
0 11 42
42 0 7
57 7 4
water-to-light map:
88 18 7
18 25 70
light-to-temperature map:
45 77 23
81 45 19
68 64 13
temperature-to-humidity map:
0 69 1
1 0 69
humidity-to-location map:
60 56 37
56 93 4
""".trimIndent()
val input2 = """
""".trimIndent()
fun map(n: Long, rules: List<List<Long>>): Long {
for (rule in rules) {
if (n >= rule[1] && n < rule[1] + rule[2]) {
return rule[0] - rule[1] + n
}
}
return n
}
fun map(n: List<Interval1>, rules: List<List<Long>>): List<Interval1> {
return n.flatMap { map(it, rules) }
}
fun map(n: Interval1, rules: List<List<Long>>): List<Interval1> {
var i0s = listOf(n)
val irs = mutableListOf<Interval1>()
for (rule in rules) {
val i = Interval1(rule[1], rule[2])
val i1s = i0s.flatMap { it.minus(i) }
irs.addAll(i0s.flatMap { it.intersect(i) }.map {
val s1 = it.start
val e1 = it.end()-1
val sr = map(s1, listOf(rule))
val er = map(e1, listOf(rule))
Interval1(sr, it.length)
})
i0s = i1s
}
irs.addAll(i0s)
return irs
}
class Interval1(val start: Long, val length: Long) {
init {
if (length<1) {
throw RuntimeException()
}
}
fun minus(o: Interval1): List<Interval1> {
val start1 = max(start, o.start)
val start0 = min(start, o.start)
val end1 = min(end(), o.end())
val end2 = max(end(), o.end())
if (start1 >= end1) {
return listOf(this)
}
if (start < o.start) {
if (end() <= o.end()) {
return listOf(Interval1(start, o.start-start))
}
return listOf(Interval1(start, o.start-start), Interval1(o.end(), end()-o.end()))
}
if (end() <= o.end()) {
return listOf()
}
return listOf(Interval1(o.end(), end()-o.end()))
}
fun end(): Long {
return start + length
}
fun intersect(o: Interval1): List<Interval1> {
val start1 = max(start, o.start)
val start0 = min(start, o.start)
val end1 = min(end(), o.end())
val end2 = max(end(), o.end())
if (start1 >= end1) {
return listOf()
}
return listOf(Interval1(start1, end1-start1))
}
}
fun solve() {
val f = File("src/2023/inputs/day05.in")
val s = Scanner(f)
// val s = Scanner(input1)
// val s = Scanner(input2)
var sum = 0
var sum1 = 0
var lineix = 0
val lines = mutableListOf<String>()
val maps = List<MutableList<List<Long>>>(7){ mutableListOf() }
while (s.hasNextLine()) {
lineix++
val line = s.nextLine().trim()
if (line.isEmpty()) {
continue
}
lines.add(line)
}
val seeds = lines.filter{it.startsWith("seeds: ")}[0].split(Regex("[: ]+")).filter { it.all { it1 -> it1.isDigit() } }.map { it.toLong() }
val lines1 = lines.subList(2, lines.size)
var ix = 0
for (l in lines1) {
if (l.endsWith("map:")) {
ix++
continue
}
maps[ix].add(l.split(" ").map { it.toLong() })
}
val mappedSeeds = mutableListOf<Long>()
val locations =
seeds.map {
maps.fold(it){ it1, rules -> map(it1, rules) }
}
val seeds1 = seeds.windowed(2,2) {listOf(Interval1(it[0], it[1]))}
val locations1 =
seeds1.flatMap {
maps.fold(it){ it1, rules -> map(it1, rules) }
}
val m = locations1.map { it.start }.min()
print("$sum $sum1 ${locations.min()} $m\n")
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 4,647 | advent-of-code | Apache License 2.0 |
src/day18/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day18
import java.io.File
import java.lang.IllegalStateException
interface Element
class RegularNumber(val value: Int) : Element
object Open : Element
object Close : Element
fun main() {
val elements = File("src/day18/input.txt").readLines().map { line ->
line.toList().map { ch ->
when (ch) {
'[' -> Open
']' -> Close
',' -> null
else -> RegularNumber(ch.digitToInt())
}
}.filterNotNull()
}
println(elements.reduce { x, y -> x + y }.magnitude())
println(sequence {
for ((i, x) in elements.withIndex()) {
for ((j, y) in elements.withIndex()) {
if (i != j) yield(x + y)
}
}
}.maxOf { it.magnitude() })
}
private operator fun List<Element>.plus(other: List<Element>): List<Element> {
val result = ArrayList<Element>(this.size + other.size + 2)
result.add(Open)
result.addAll(this)
result.addAll(other)
result.add(Close)
outer@ while (true) {
var depth = 0
for (i in 0 until result.size - 4) {
if (depth > 3 && result[i] is Open && result[i + 3] is Close) { // Explode
val left = result[i + 1]
val right = result[i + 2]
if (left is RegularNumber && right is RegularNumber) {
result[i] = RegularNumber(0)
result.subList(i + 1, i + 4).clear()
for (j in i - 1 downTo 0) {
val number = result[j] as? RegularNumber ?: continue
result[j] = RegularNumber(number.value + left.value)
break
}
for (j in i + 1 until result.size) {
val number = result[j] as? RegularNumber ?: continue
result[j] = RegularNumber(number.value + right.value)
break
}
continue@outer
}
}
depth += when (result[i]) {
Open -> 1
Close -> -1
else -> 0
}
}
for ((i, element) in result.withIndex()) {
if (element is RegularNumber && element.value > 9) { // Split
result.removeAt(i)
result.addAll(
i,
listOf(Open, RegularNumber(element.value / 2), RegularNumber((element.value + 1) / 2), Close)
)
continue@outer
}
}
break@outer
}
return result
}
fun List<Element>.magnitude() = recurse(0).first
fun List<Element>.recurse(index: Int): Pair<Int, Int> {
return when (val element = this[index]) {
Open -> {
val (left, leftEnd) = recurse(index + 1)
val (right, rightEnd) = recurse(leftEnd)
Pair(3 * left + 2 * right, rightEnd + 1)
}
is RegularNumber -> Pair(element.value, index + 1)
else -> throw IllegalStateException()
}
} | 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 3,102 | advent-of-code-2021 | MIT License |
src/main/kotlin/week2/HillClimbing.kt | waikontse | 572,850,856 | false | {"Kotlin": 63258} | package week2
import shared.Algorithms.Companion.dijkstra
import shared.Algorithms.Edge
import shared.Algorithms.Graph
import shared.Algorithms.GraphSize
import shared.Node
import shared.Puzzle
class HillClimbing : Puzzle(12) {
override fun solveFirstPart(): Any {
val input = puzzleInput
val cleanedInput = input.map { it.replace("S", "a") }
.map { it.replace("E", "z") }
val graph = parseMap(cleanedInput)
val shortestPaths = dijkstra(findStartingPosition(input), graph)
return shortestPaths.first[findEndingPosition(input)]
}
override fun solveSecondPart(): Any {
val input = puzzleInput
val cleanedInput = input.map { it.replace("S", "a") }
.map { it.replace("E", "z") }
val graph = parseMap(cleanedInput)
return cleanedInput.joinToString("")
.mapIndexed { index, c -> if (c == 'a') index else -1 }
.filterNot { i -> i == -1 }
.map { dijkstra(it, graph) }
.map { it.first[findEndingPosition(input)] }
.min()
}
private fun parseMap(map: List<String>): Graph {
val width = map[0].length
val height = map.size
val size = GraphSize(width, height)
val graph = Graph(size)
return parseGraph2(map.joinToString(separator = ""), size, 0, graph)
}
private tailrec fun parseGraph2(
map: String,
size: GraphSize,
currPos: Node,
graph: Graph
): Graph {
if (currPos >= size.width * size.height) {
return graph
}
val edges = getConnectedEdges(map, size, currPos)
graph.addEdges(currPos, edges)
return parseGraph2(map, size, currPos.inc(), graph)
}
private fun getConnectedEdges(map: String, size: GraphSize, currPos: Node): List<Edge> {
val edges = mutableListOf<Edge>()
if (isConnectedTop(map, size, currPos)) {
edges.add(Edge(currPos.minus(size.width), 1))
}
if (isConnectedBottom(map, size, currPos)) {
edges.add(Edge(currPos.plus(size.width), 1))
}
if (isConnectedLeft(map, size, currPos)) {
edges.add(Edge(currPos.dec(), 1))
}
if (isConnectedRight(map, size, currPos)) {
edges.add(Edge(currPos.inc(), 1))
}
return edges
}
private fun isConnectedTop(map: String, size: GraphSize, pos: Int): Boolean {
return isConnected(map, size, pos, pos.minus(size.width))
}
private fun isConnectedBottom(map: String, size: GraphSize, pos: Int): Boolean {
return isConnected(map, size, pos, pos.plus(size.width))
}
private fun isConnectedLeft(map: String, size: GraphSize, pos: Int): Boolean {
return isConnected(map, size, pos, pos.dec())
}
private fun isConnectedRight(map: String, size: GraphSize, pos: Int): Boolean {
return isConnected(map, size, pos, pos.inc())
}
private fun isConnected(map: String, size: GraphSize, from: Int, to: Int): Boolean {
if (to < 0) {
return false
} else if (to >= size.width * size.height) {
return false
}
return (map[from].code - map[to].code) >= -1
}
private fun findStartingPosition(map: List<String>): Int {
return findPositionOfChar(map.joinToString(separator = ""), 'S', 0)
}
private fun findEndingPosition(map: List<String>): Int {
return findPositionOfChar(map.joinToString(separator = ""), 'E', 0)
}
private tailrec fun findPositionOfChar(map: String, target: Char, currPos: Int): Int {
if (map[currPos] == target) {
return currPos
}
return findPositionOfChar(map, target, currPos.inc())
}
}
| 0 | Kotlin | 0 | 0 | 860792f79b59aedda19fb0360f9ce05a076b61fe | 3,798 | aoc-2022-in-kotllin | Creative Commons Zero v1.0 Universal |
src/Day01.kt | mvanderblom | 573,009,984 | false | {"Kotlin": 25405} | fun main() {
val dayName = 1.toDayName()
fun List<Int?>.total(): Int = this.filterNotNull().sum()
fun getCaloriesPerElf(input: List<Int?>) = input
.mapIndexedNotNull { index, calories ->
when {
(index == 0 || calories == null) -> index
(index == input.size - 1) -> input.size
else -> null
}
}
.windowed(2, 1)
.map { (from, to) -> input.subList(from, to).total() }
fun part1(input: List<Int?>): Int = getCaloriesPerElf(input)
.max()
fun part2(input: List<Int?>): Int = getCaloriesPerElf(input)
.sortedDescending()
.subList(0,3)
.sum()
val testInput = readInput("${dayName}_test")
.map { it.toIntOrNull() }
val testOutputPart1 = part1(testInput)
testOutputPart1 isEqualTo 24000
val input = readInput(dayName)
.map { it.toIntOrNull() }
val outputPart1 = part1(input)
outputPart1 isEqualTo 69795
val testOutputPart2 = part2(testInput)
testOutputPart2 isEqualTo 45000
val outputPart2 = part2(input)
outputPart2 isEqualTo 208437
}
| 0 | Kotlin | 0 | 0 | ba36f31112ba3b49a45e080dfd6d1d0a2e2cd690 | 1,207 | advent-of-code-kotlin-2022 | Apache License 2.0 |
aoc21/day_04/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
data class Num(val n: Int, var marked: Boolean)
class Board(val nums: Array<Array<Num>>) {
var won = false
fun fullRow(i: Int): Boolean = nums[i].all { it.marked }
fun fullCol(i: Int): Boolean = nums.all { it[i].marked }
fun mark(n: Int) {
nums.forEach { it.forEach { if (it.n == n) it.marked = true } }
if ((0..4).any { fullRow(it) || fullCol(it) }) won = true
}
fun score(): Int = nums.map { it.filter { !it.marked }.map { it.n }.sum() }.sum()
}
fun main() {
val input = File("input").readText().trim().split("\n\n")
val nums = input[0].trim().split(",").map { it.toInt() }
val boards = input.drop(1).map {
Board(
it.trim().split("\n").map { line ->
line.trim().split("\\s+".toRegex()).map { n ->
Num(n.toInt(), false)
}.toTypedArray()
}.toTypedArray()
)
}
var first: Int? = null
for (n in nums) {
for (b in boards) {
if (!b.won) b.mark(n)
if (b.won && first == null) first = b.score() * n
if (boards.all { it.won }) {
println("First: $first")
println("Second: ${b.score() * n}")
return
}
}
}
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,295 | advent-of-code | MIT License |
src/main/kotlin/Day4.kt | lanrete | 244,431,253 | false | null | object Day4 : Solver() {
override val day: Int = 4
override val inputs: List<String> = getInput()
private fun getRange(): IntRange {
val (start, end) = inputs[0]
.split('-')
.map { it.toInt() }
return (start..end)
}
private val range = getRange()
private fun isValidQ1(candidate: Int): Boolean {
if (candidate < 100000) {
return false
}
if (candidate > 999999) {
return false
}
val digits = candidate.toString()
if (digits
.map { it - '0' }
.reduce { acc, i -> if (acc <= i) i else 10 }
== 10
) {
return false
}
if (digits
.mapIndexed { index, c -> if (index == 0) false else (c == digits[index - 1]) }
.none { it }
) {
return false
}
return true
}
private fun isValidQ2(candidate: Int): Boolean {
if (!isValidQ1(candidate)) {
return false
}
// Digits never decrease, no need to check the case like 123232
return candidate.toString()
.groupBy { it }
.mapValues { (_, v) -> v.size }
.any { (_, v) -> v == 2 }
}
override fun question1(): String {
return range
.filter { isValidQ1(it) }
.count()
.toString()
}
override fun question2(): String {
return range
.filter { isValidQ2(it) }
.count()
.toString()
}
}
fun main() {
Day4.validateInput()
Day4.solve()
}
| 0 | Kotlin | 0 | 1 | 15125c807abe53230e8d0f0b2ca0e98ea72eb8fd | 1,651 | AoC2019-Kotlin | MIT License |
ceria/09/src/main/kotlin/Solution.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File;
lateinit var heights: Array<IntArray>
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
heights = Array<IntArray>(input.size) { IntArray(input.first().length) {0} }
var i = 0
for (line in input) {
var row = heights[i]
for (idx in line.indices) {
row[idx] = line.get(idx).digitToInt()
}
i++
}
println("Solution 1: ${solution1()}")
println("Solution 2: ${solution2()}")
}
private fun solution1() :Int {
var sums = mutableListOf<Int>()
for (rowIdx in heights.indices) {
val row = heights[rowIdx]
for (idx in row.indices) {
val point = row[idx]
// compare to the left
if (idx > 0 && row[idx - 1] <= point) {
continue
}
// compare to the right
if (idx < row.size - 1 && row[idx + 1] <= point) {
continue
}
// compare above
if (rowIdx > 0 && heights[rowIdx - 1][idx] <= point) {
continue
}
// compare below
if (rowIdx < heights.size - 1 && heights[rowIdx + 1][idx] <= point) {
continue
}
// add to the list (could just keep a sum, but maybe part 2 will be easier if we keep a list)
sums.add(point + 1)
}
}
return sums.sum()
}
private fun solution2() :Int {
var basinSizes = mutableListOf<Int>()
for (rowIdx in heights.indices) {
val row = heights[rowIdx]
for (idx in row.indices) {
val point = row[idx]
// compare to the left
if (idx > 0 && row[idx - 1] <= point) {
continue
}
// compare to the right
if (idx < row.size - 1 && row[idx + 1] <= point) {
continue
}
// compare above
if (rowIdx > 0 && heights[rowIdx - 1][idx] <= point) {
continue
}
// compare below
if (rowIdx < heights.size - 1 && heights[rowIdx + 1][idx] <= point) {
continue
}
// if we made it this far, this is a basin, compute it's size
var basinBounds = mutableSetOf<Pair<Int, Int>>(Pair<Int, Int>(idx, rowIdx))
var allBounded = false
while (!allBounded) {
var newPoints = mutableSetOf<Pair<Int, Int>>()
for (bp in basinBounds) {
newPoints.addAll(checkForBounds(bp, basinBounds))
}
basinBounds.addAll(newPoints)
if (newPoints.isEmpty()) {
allBounded = true
}
}
basinSizes.add(basinBounds.size)
}
}
basinSizes.sort()
// return the product of the 3 largest values
return basinSizes.takeLast(3).reduce{ acc, i -> acc * i }
}
private fun checkForBounds(p: Pair<Int, Int>, basinPoints: Set<Pair<Int, Int>>) :Set<Pair<Int, Int>> {
var newPoints = mutableSetOf<Pair<Int, Int>>()
// compare to the point to the left - if it's not 9, and not already in newPoints, add it to newPoints
if (p.first > 0 && heights[p.second][p.first - 1] != 9) {
val newPoint = Pair<Int, Int>(p.first - 1, p.second)
if (!basinPoints.contains(newPoint)) {
newPoints.add(newPoint)
}
}
// compare to the point to the right - if it's not 9, and not already in newPoints, add it to newPoints
if (p.first < heights[0].size - 1 && heights[p.second][p.first + 1] != 9) {
val newPoint = Pair<Int, Int>(p.first + 1, p.second)
if (!basinPoints.contains(newPoint)) {
newPoints.add(newPoint)
}
}
// compare to the point above - if it's not 9, and not already in newPoints, add it to newPoints
if (p.second > 0 && heights[p.second - 1][p.first] != 9) {
val newPoint = Pair<Int, Int>(p.first, p.second - 1)
if (!basinPoints.contains(newPoint)) {
newPoints.add(newPoint)
}
}
// compare to the point above - if it's not 9, and not already in newPoints, add it to newPoints
if (p.second < heights.size -1 && heights[p.second + 1][p.first] != 9) {
val newPoint = Pair<Int, Int>(p.first, p.second + 1)
if (!basinPoints.contains(newPoint)) {
newPoints.add(newPoint)
}
}
return newPoints
}
| 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 4,524 | advent-of-code-2021 | MIT License |
src/main/kotlin/ru/timakden/aoc/year2022/Day20.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2022
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 20: Grove Positioning System](https://adventofcode.com/2022/day/20).
*/
object Day20 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2022/Day20")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Long {
return mix(input, 1, 1)
}
fun part2(input: List<String>): Long {
return mix(input, 10, 811589153)
}
private fun mix(input: List<String>, rounds: Int, multiplier: Int): Long {
val numbers = input
.map { it.toLong() }
.map { it * multiplier }
.mapIndexed { index, value -> Number(index, value) }
.toMutableList()
val processOrder = numbers.toList()
repeat(rounds) {
for (number in processOrder) {
val index = numbers.indexOf(number)
numbers.remove(number)
numbers.add(Math.floorMod(number.value + index, numbers.size), number)
}
}
val indexIterator = iterator {
val zeroIndex = numbers.indexOfFirst { it.value == 0L }
val indexes = numbers.indices.toList()
while (true) {
yieldAll(indexes.subList(zeroIndex + 1, numbers.lastIndex + 1) + indexes.subList(0, zeroIndex + 1))
}
}
return (1..3000).sumOf {
val index = indexIterator.next()
if (it % 1000 == 0) numbers[index].value else 0
}
}
private data class Number(val index: Int, val value: Long)
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 1,752 | advent-of-code | MIT License |
kool-core/src/commonMain/kotlin/de/fabmax/kool/math/Partition.kt | fabmax | 81,503,047 | false | {"Kotlin": 5023245, "HTML": 1464, "JavaScript": 597} | package de.fabmax.kool.math
import kotlin.math.*
fun <T> MutableList<T>.partition(k: Int, cmp: (T, T) -> Int) = partition(indices, k, cmp)
fun <T> MutableList<T>.partition(rng: IntRange, k: Int, cmp: (T, T) -> Int) {
partition(this, rng.first, rng.last, k, { get(it) }, cmp, { a, b -> this[a] = this[b].also { this[b] = this[a] } })
}
fun <T> Array<T>.partition(k: Int, cmp: (T, T) -> Int) = partition(indices, k, cmp)
fun <T> Array<T>.partition(rng: IntRange, k: Int, cmp: (T, T) -> Int) {
partition(this, rng.first, rng.last, k, { get(it) }, cmp, { a, b -> this[a] = this[b].also { this[b] = this[a] } })
}
/**
* Partitions items with the given comparator. After partitioning, all elements left of k are smaller
* than all elements right of k with respect to the given comparator function.
*
* This method implements the Floyd-Rivest selection algorithm:
* https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm
*/
fun <L,T> partition(elems: L, lt: Int, rt: Int, k: Int, get: L.(Int) -> T, cmp: (T, T) -> Int, swap: L.(Int, Int) -> Unit) {
var left = lt
var right = rt
while (right > left) {
if (right - left > 600) {
val n = right - left + 1
val i = k - left + 1
val z = ln(n.toDouble())
val s = 0.5 * exp(2.0 * z / 3.0)
val sd = 0.5 * sqrt(z * s * (n - s) / n) * sign(i - n / 2.0)
val newLeft = max(left, (k - i * s / n + sd).toInt())
val newRight = min(right, (k + (n - i) * s / n + sd).toInt())
partition(elems, newLeft, newRight, k, get, cmp, swap)
}
val t = elems.get(k)
var i = left
var j = right
elems.swap(left, k)
if (cmp(elems.get(right), t) > 0) {
elems.swap(right, left)
}
while (i < j) {
elems.swap(i, j)
i++
j--
while (cmp(elems.get(i), t) < 0) {
i++
}
while (j >= 0 && cmp(elems.get(j), t) > 0) {
j--
}
}
if (cmp(elems.get(left), t) == 0) {
elems.swap(left, j)
} else {
j++
elems.swap(j, right)
}
if (j <= k) {
left = j + 1
}
if (k <= j) {
right = j - 1
}
}
} | 12 | Kotlin | 14 | 234 | 85fe1de1d690d5571a2c33a5fd4cf7e23a645437 | 2,340 | kool | Apache License 2.0 |
src/Day12.kt | li-xin-yi | 573,617,763 | false | {"Kotlin": 23422} | fun main() {
val directions = listOf((0 to 1), (1 to 0), (0 to -1), (-1 to 0))
fun solvePart1(input: List<String>): Int {
val n = input.size
val m = input[0].length
var (startX, startY) = (0 to 0)
for (i in 0 until n) {
for (j in 0 until m) {
if (input[i][j] == 'S') {
startX = i
startY = j
break
}
}
}
val queue = ArrayDeque<List<Int>>()
val seen = List(n) { MutableList(m) { false } }
seen[startX][startY] = true
queue.add(listOf(startX, startY, 0, 'a'.code))
while (queue.isNotEmpty()) {
val (x, y, step, key) = queue.removeFirst()
for ((dx, dy) in directions) {
val (nx, ny) = (x + dx to y + dy)
if (nx < 0 || nx >= n || ny < 0 || ny >= m || seen[nx][ny]) continue
if (input[nx][ny] == 'E') {
if (key + 1 >= 'z'.code)
return step + 1
continue
}
if (input[nx][ny].code > key + 1) continue
seen[nx][ny] = true
queue.add(listOf(nx, ny, step + 1, input[nx][ny].code))
}
}
return 0
}
fun solvePart2(input: List<String>): Int {
val n = input.size
val m = input[0].length
var (startX, startY) = (0 to 0)
for (i in 0 until n) {
for (j in 0 until m) {
if (input[i][j] == 'E') {
startX = i
startY = j
break
}
}
}
val queue = ArrayDeque<List<Int>>()
val seen = List(n) { MutableList(m) { false } }
seen[startX][startY] = true
queue.add(listOf(startX, startY, 0, 'z'.code))
while (queue.isNotEmpty()) {
val (x, y, step, key) = queue.removeFirst()
for ((dx, dy) in directions) {
val (nx, ny) = (x + dx to y + dy)
if (nx < 0 || nx >= n || ny < 0 || ny >= m || seen[nx][ny]) continue
if (input[nx][ny] == 'S' || input[nx][ny] == 'a') {
if (key <= 'a'.code + 1)
return step + 1
continue
}
if (input[nx][ny].code < key - 1) continue
seen[nx][ny] = true
queue.add(listOf(nx, ny, step + 1, input[nx][ny].code))
}
}
return 0
}
val testInput = readInput("input/Day12_test")
check(solvePart1(testInput) == 31)
check(solvePart2(testInput) == 29)
val input = readInput("input/Day12_input")
println(solvePart1(input))
println(solvePart2(input))
} | 0 | Kotlin | 0 | 1 | fb18bb7e462b8b415875a82c5c69962d254c8255 | 2,827 | AoC-2022-kotlin | Apache License 2.0 |
solution/#56 Merge Intervals/Solution.kt | enihsyou | 116,918,868 | false | {"Java": 179666, "Python": 36379, "Kotlin": 32431, "Shell": 367} | package leetcode.q56.kotlin;
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
/**
* 56. Merge Intervals
*
* [LeetCode](https://leetcode-cn.com/problems/merge-intervals/)
*/
class Solution {
fun merge(intervals: Array<IntArray>): Array<IntArray> {
val result = java.util.LinkedList<IntArray>()
if (intervals.isEmpty()) {
return emptyArray()
} else {
intervals.sortBy { it.start /* 按区间起始值排序 */ }
result += intervals.first()
}
for (currInterval in intervals) {
val lastInterval = result.last()
if (lastInterval.end < currInterval.start) {
/* 如果当前区间和上一个区间没有重叠部分,说明这是一个新的区间 */
result += currInterval
} else {
/* 如果当前区间和上一个区间存在重叠部分,那么这个区间可能会被拓宽 */
lastInterval.end = maxOf(lastInterval.end, currInterval.end)
}
}
return result.toTypedArray()
}
var IntArray.start: Int
inline get() = this[0]
inline set(value) {
this[0] = value
}
var IntArray.end: Int
inline get() = this[1]
inline set(value) {
this[1] = value
}
}
class SolutionTest {
private val solution = Solution()
@ParameterizedTest(name = "merge({0}) = {1}")
@MethodSource("provider")
fun merge(input: Array<IntArray>, output: Array<IntArray>) {
Assertions.assertArrayEquals(solution.merge(input), output)
}
companion object {
@JvmStatic
fun provider(): List<Arguments> {
return listOf(
Arguments.of(arrayOf(
intArrayOf(1, 3),
intArrayOf(2, 6),
intArrayOf(8, 10),
intArrayOf(15, 18)), arrayOf(
intArrayOf(1, 6),
intArrayOf(8, 10),
intArrayOf(15, 18))),
Arguments.of(arrayOf(
intArrayOf(1, 4),
intArrayOf(4, 5)), arrayOf(
intArrayOf(1, 5)))
)
}
}
}
| 1 | Java | 0 | 0 | 230325d1dfd666ee53f304edf74c9c0f60f81d75 | 2,406 | LeetCode | MIT License |
src/main/kotlin/nl/kelpin/fleur/advent2018/Day13.kt | fdlk | 159,925,533 | false | null | package nl.kelpin.fleur.advent2018
sealed class Turn
object TurnLeft : Turn()
object TurnRight : Turn()
object Straight : Turn()
class Day13(input: List<String>, private val removeCrashedCarts: Boolean = false) {
companion object {
fun replaceCartWithTrack(cart: Char): Char = when (cart) {
'>', '<' -> '-'
'^', 'v' -> '|'
else -> cart
}
val readingOrder = compareBy<Cart>({ it.location.y }, { it.location.x })
}
val track: List<String> = input.map { it.map(Companion::replaceCartWithTrack).joinToString("") }
val initialCarts: Set<Cart> = input.mapIndexed { y, row ->
row.mapIndexed { x, char ->
when (char) {
'>' -> Cart(Point(x, y), Right)
'<' -> Cart(Point(x, y), Left)
'^' -> Cart(Point(x, y), Up)
'v' -> Cart(Point(x, y), Down)
else -> null
}
}.filterNotNull()
}.flatten().toSet()
data class Cart(val location: Point, val direction: Direction, val nextTurn: Turn = TurnLeft) {
private fun newNextTurn(charAtNewPos: Char): Turn = when (charAtNewPos) {
'+' -> when (nextTurn) {
TurnLeft -> Straight
Straight -> TurnRight
TurnRight -> TurnLeft
}
else -> nextTurn
}
private fun newDirection(charAtNewPos: Char): Direction = when (charAtNewPos) {
'\\' -> when (direction) {
Right -> Down
Up -> Left
Left -> Up
Down -> Right
}
'/' -> when (direction) {
Up -> Right
Left -> Down
Right -> Up
Down -> Left
}
'+' -> when (nextTurn) {
TurnLeft -> when (direction) {
Left -> Down
Down -> Right
Right -> Up
Up -> Left
}
Straight -> direction
TurnRight -> when (direction) {
Left -> Up
Up -> Right
Right -> Down
Down -> Left
}
}
else -> direction
}
fun moveOn(track: List<String>): Cart = with(location.move(direction)) {
val charAtNewPos = track[y][x]
return copy(location = this, direction = newDirection(charAtNewPos), nextTurn = newNextTurn(charAtNewPos))
}
}
fun next(carts: Set<Cart>): Pair<Point?, Set<Cart>> {
val sorted: MutableList<Cart> = carts.sortedWith(readingOrder).toMutableList()
val moved: MutableSet<Cart> = mutableSetOf()
while (sorted.isNotEmpty()) {
val movedCart = sorted.removeAt(0).moveOn(track)
if (moved.union(sorted).any { it.location == movedCart.location }) {
if (!removeCrashedCarts) {
return movedCart.location to emptySet()
} else {
moved.removeIf { it.location == movedCart.location }
sorted.removeIf { it.location == movedCart.location }
}
} else moved.add(movedCart)
}
return null to moved
}
tailrec fun part1(carts: Set<Cart> = initialCarts): Point {
val (collision, updated) = next(carts)
return collision ?: part1(updated)
}
tailrec fun part2(carts: Set<Cart> = initialCarts): Point {
val (_, updated) = next(carts)
return if (updated.size == 1) updated.first().location
else part2(updated)
}
} | 0 | Kotlin | 0 | 3 | a089dbae93ee520bf7a8861c9f90731eabd6eba3 | 3,699 | advent-2018 | MIT License |
src/Day03.kt | mpylypovych | 572,998,434 | false | {"Kotlin": 6455} | fun main() {
fun score(c: Char) = c - if (c.isUpperCase()) 'A' - 27 else 'a' - 1
fun part1(input: List<String>) = input
.map { it.chunked(it.length / 2) }
.sumOf { row ->
('A'..'z').sumOf {
if (row.first().contains(it) && row.last().contains(it))
score(it) else 0
}
}
fun part2(input: List<String>) = input
.map { it.toCharArray().toSet() }
.chunked(3)
.map {
it.reduce { intersection, element ->
intersection.intersect(element)
}
}
.sumOf {
score(it.first())
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println(part1(testInput))
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 733b35c3f4eea777a5f666c804f3c92d0cc9854b | 968 | aoc-2022-in-kotlin | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day4/Day4.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day4
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputLines
object Day4 : Day {
override val input = readInputLines(4).run { Game(first().parseNumbers(), drop(1).parseBoards()) }
override fun part1() = input.first()
override fun part2() = input.last()
private fun String.parseNumbers() = split(",").map { it.toInt() }
private fun List<String>.parseBoards() = chunked(boardSize() + 1).map { it.parseBoard() }
private fun List<String>.boardSize() = drop(1).mapIndexedNotNull { i, s -> i.takeIf { s.trim().isBlank() } }.first()
private fun List<String>.parseBoard() = Board(filter { it.trim().isNotBlank() }.readCells())
private fun List<String>.readCells() = flatMapIndexed { i, l -> l.trim().parseLine(i) }
private fun String.parseLine(index: Int): List<Cell> {
return split(" ").filter { it.trim().isNotBlank() }.mapIndexed { i, v -> Cell(Position(i, index), v.toInt()) }
}
class Game(private val numbers: List<Int>, private val boards: List<Board>) {
fun first() = numbers.firstNotNullOf { nb -> boards.firstOrNull { it.call(nb) }?.run { result(nb) } }.apply { reset() }
fun last() = numbers.firstNotNullOf { nb -> boards.filter { it.call(nb) }.lastOrNull { boards.all { it.resolved } }?.result(nb) }
private fun reset() = boards.forEach { it.reset() }
}
data class Board(val cells: List<Cell>) {
var resolved = false
fun call(number: Int) = if (resolved) false else cells.filter { it.value == number }.any { it.call() }
fun result(number: Int) = cells.filter { !it.called }.sumOf { it.value } * number
fun reset() {
resolved = false
cells.forEach { it.called = false }
}
private fun Cell.call(): Boolean {
called = true
if (allComplete { position.x } || allComplete { position.y }) {
resolved = true
}
return resolved
}
private fun Cell.allComplete(extract: Cell.() -> Int) = cells.filter { it.extract() == extract() }.all { it.called }
}
class Cell(val position: Position, val value: Int) {
var called: Boolean = false
}
data class Position(val x: Int, val y: Int)
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 2,341 | aoc2021 | MIT License |
src/main/kotlin/com/polydus/aoc18/Day4.kt | Polydus | 160,193,832 | false | null | package com.polydus.aoc18
class Day4: Day(4){
//https://adventofcode.com/2018/day/4
init {
//partOne()
partTwo()
}
fun partOne(){
val lines = input.sortedBy {
var min = it.substring(15, 17).toInt()
min
}.sortedBy {
var hour = it.substring(12, 14).toInt()
hour
}.sortedBy {
var day = it.substring(9, 11).toInt()
day
}.sortedBy {
//val chars = it.toCharArray()
var month = it.substring(6, 8).toInt()
//var day = it.substring(9, 11).toInt()
//var hour = it.substring(12, 14).toInt()
//var min = it.substring(15, 17).toInt()
month
}
for(line in lines){
//println(line)
}
val guards = HashMap<Int, Array<Int>>()
var currentGuard = 0
var lastTime = 0
//var sleeping = false
lines.forEach {
val chars = it.toCharArray()
var mins = 0
for(i in 0 until it.length){
if(chars[i] == ':'){
mins = it.substring(i + 1, i + 3).toInt()
}
if(chars[i] == 'G' && chars[i - 1] == ' '){
var counter = i + 6
while(chars[counter] != ' '){
counter++
}
currentGuard = it.substring(i + 7, counter).toInt()
if(!guards.contains(currentGuard)){
guards[currentGuard] = Array<Int>(59){0}
}
break
} else if(chars[i] == 'f' && chars[i - 1] == ' '){
break
} else if(chars[i] == 'w' && chars[i - 1] == ' '){
for(j in lastTime until mins){
guards[currentGuard]!![j]++
}
break
}
}
lastTime = mins
}
var mostIndex = 0
var mostMins = 0
var highestMin = 0
for(g in guards){
var mins = 0
var highValue = 0
var highIndex = 0
for(i in 0 until g.value.size){
mins += g.value[i]
if(highValue < g.value[i]){
highValue = g.value[i]
highIndex = i
}
}
if(mins > mostMins){
mostIndex = g.key
mostMins = mins
highestMin = highIndex
}
println("\n${g.key} awakemins: ${g.value.filter { it == 0 }.size} totalasleepmins: $mins")
for(i in 0 until g.value.size){
print("${g.value[i]} ")
}
}
println("\nanswer is #${mostIndex} with $mostMins highest min $highestMin. | ans is: ${mostIndex * highestMin}")
}
fun partTwo(){
val lines = input.sortedBy {
var min = it.substring(15, 17).toInt()
min
}.sortedBy {
var hour = it.substring(12, 14).toInt()
hour
}.sortedBy {
var day = it.substring(9, 11).toInt()
day
}.sortedBy {
//val chars = it.toCharArray()
var month = it.substring(6, 8).toInt()
//var day = it.substring(9, 11).toInt()
//var hour = it.substring(12, 14).toInt()
//var min = it.substring(15, 17).toInt()
month
}
for(line in lines){
//println(line)
}
val guards = HashMap<Int, Array<Int>>()
var currentGuard = 0
var lastTime = 0
//var sleeping = false
lines.forEach {
val chars = it.toCharArray()
var mins = 0
for(i in 0 until it.length){
if(chars[i] == ':'){
mins = it.substring(i + 1, i + 3).toInt()
}
if(chars[i] == 'G' && chars[i - 1] == ' '){
var counter = i + 6
while(chars[counter] != ' '){
counter++
}
currentGuard = it.substring(i + 7, counter).toInt()
if(!guards.contains(currentGuard)){
guards[currentGuard] = Array<Int>(59){0}
}
break
} else if(chars[i] == 'f' && chars[i - 1] == ' '){
break
} else if(chars[i] == 'w' && chars[i - 1] == ' '){
for(j in lastTime until mins){
guards[currentGuard]!![j]++
}
break
}
}
lastTime = mins
}
var mostIndex = 0
var mostMins = 0
var highestMin = 0
var highestMinValue = 0
for(g in guards){
var mins = 0
var highValue = 0
var highIndex = 0
for(i in 0 until g.value.size){
mins += g.value[i]
if(highValue < g.value[i]){
highValue = g.value[i]
highIndex = i
}
}
if(highValue > highestMinValue){
mostIndex = g.key
mostMins = mins
highestMin = highIndex
highestMinValue = highValue
}
println("\n${g.key} awakemins: ${g.value.filter { it == 0 }.size} totalasleepmins: $mins")
for(i in 0 until g.value.size){
print("${g.value[i]} ")
}
}
println("\nanswer is #${mostIndex} " +
"highest min $highestMin. with value $highestMinValue | ans is: ${mostIndex * highestMin}")
}
} | 0 | Kotlin | 0 | 0 | e510e4a9801c228057cb107e3e7463d4a946bdae | 5,887 | advent-of-code-2018 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestPath.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
import kotlin.math.max
/**
* 2246. Longest Path With Different Adjacent Characters
* @see <a href="https://leetcode.com/problems/longest-path-with-different-adjacent-characters/">Source</a>
*/
fun interface LongestPath {
operator fun invoke(parent: IntArray, s: String): Int
}
class LongestPathDFS : LongestPath {
var res = 0
override operator fun invoke(parent: IntArray, s: String): Int {
res = 0
val children: Array<ArrayList<Int>> = Array(parent.size) { ArrayList() }
for (i in 1 until parent.size) {
children[parent[i]].add(i)
}
dfs(children, s, 0)
return res
}
private fun dfs(children: Array<ArrayList<Int>>, s: String, i: Int): Int {
val queue: PriorityQueue<Int> = PriorityQueue()
for (j in children[i]) {
val cur = dfs(children, s, j)
if (s[j] != s[i]) queue.offer(-cur)
}
val big1 = if (queue.isEmpty()) 0 else -queue.poll()
val big2 = if (queue.isEmpty()) 0 else -queue.poll()
res = max(res, big1 + big2 + 1)
return big1 + 1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,785 | kotlab | Apache License 2.0 |
leetcode/src/linkedlist/Q24.kt | zhangweizhe | 387,808,774 | false | null | package linkedlist
import linkedlist.kt.ListNode
fun main() {
// 24. 两两交换链表中的节点
// https://leetcode-cn.com/problems/swap-nodes-in-pairs/
val createList = LinkedListUtil.createList(intArrayOf(1,2,3,4))
LinkedListUtil.printLinkedList(swapPairs2(createList))
}
/**
* 递归 https://lyl0724.github.io/2020/01/25/1/
* 三部曲
* 1.递归的终止条件
* 2.递归要返回什么
* 3.递归中要做什么
*/
fun swapPairs(head: ListNode?): ListNode? {
if (head == null || head.next == null) {
// 1.递归的终止条件,剩下0个或1个节点,无法进行交换的操作
return head
}
// 一共三个节点 head-next-swapPairs(next.next)
// 要交换成 next-head-swapPairs(next.next)
var next: ListNode? = head.next
head.next = swapPairs(next?.next)
next?.next = head
// 返回给上一级的,是当前已完成交互的链表的头结点,即next
return next
}
/**
* 迭代
*/
fun swapPairs1(head: ListNode?): ListNode? {
var dummyHead: ListNode? = null
var left: ListNode? = head
var right: ListNode? = left?.next
var prev: ListNode? = null
if (right == null) {
return head
}
while (left != null && right != null) {
left.next = right.next
right.next = left
prev?.next = right
if (dummyHead == null) {
dummyHead = right
}
prev = left
left = left.next
right = left?.next
}
return dummyHead
}
/**
* 迭代
* 定义一个哑结点dummyHead
* 定义一个tmp=dummyHead节点,如果tmp后面只有0个或1个节点,则不做交换,否则,交换tmp后面的两个节点
* tmp -> node1 -> node2 -> ...
* 转换为 tmp -> node2 -> node1 -> ...
*/
fun swapPairs2(head: ListNode?): ListNode? {
var dummyHead = ListNode(0)
dummyHead.next = head
var tmp: ListNode? = dummyHead
while (tmp?.next != null && tmp.next?.next != null) {
var node1 = tmp.next
var node2 = tmp.next?.next
tmp.next = node2
node1?.next = node2?.next
node2?.next = node1
tmp = node1
}
return dummyHead.next
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,188 | kotlin-study | MIT License |
src/Day21.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | import arrow.core.Either
private enum class MathOp { ADD, MUL, SUB, DIV;
fun calc(x: Long, y: Long): Long {
return when (this) {
ADD -> x + y
MUL -> x * y
SUB -> x - y
DIV -> x / y
}
}
}
fun main() {
class Monkey(val monkeyA: String, val monkeyB: String, val op: MathOp)
fun parseMonkey(input: String): Monkey {
val monkeyA = input.substring(0, 4)
val op = when (input[5]) {
'+' -> MathOp.ADD
'*' -> MathOp.MUL
'-' -> MathOp.SUB
'/' -> MathOp.DIV
else -> throw IllegalArgumentException("Unknown op $input")
}
val monkeyB = input.substring(7, 11)
return Monkey(monkeyA, monkeyB, op)
}
fun parseInput(input: List<String>): MutableMap<String, Either<Long, Monkey>> {
return input.associate {
val name = it.substring(0, 4)
val value = it.substring(6)
if (value[0].isDigit()) {
name to Either.Left(value.toLong())
} else {
name to Either.Right(parseMonkey(value))
}
}.toMutableMap()
}
fun part1(input: List<String>): Long {
val monkeys = parseInput(input)
fun calc(monkeyName: String): Long {
return when (val m = monkeys[monkeyName]!!) {
is Either.Left -> m.value
is Either.Right -> {
val monkey = m.value
val result = monkey.op.calc(calc(monkey.monkeyA), calc(monkey.monkeyB))
monkeys[monkeyName] = Either.Left(result)
result
}
}
}
return calc("root")
}
fun part2(input: List<String>): Long {
val monkeys = parseInput(input)
fun parentMonkeys(monkeyName: String): List<String> {
if (monkeyName == "root") {
return listOf()
}
val directParents =
monkeys.filter { m -> m.value.isRight() && m.value.fold({ false }, { it.monkeyA == monkeyName || it.monkeyB == monkeyName }) }
.map { it.key }
return directParents.flatMap { parentMonkeys(it) }.toList() + directParents
}
val pathToHumn = parentMonkeys("humn")
fun calc(monkeyName: String): Long {
return when (val m = monkeys[monkeyName]!!) {
is Either.Left -> m.value
is Either.Right -> {
val monkey = m.value
val result = monkey.op.calc(calc(monkey.monkeyA), calc(monkey.monkeyB))
if (monkeyName !in pathToHumn) monkeys[monkeyName] = Either.Left(result)
result
}
}
}
calc("root")
val root = monkeys["root"]!! as Either.Right
val otherValueName = if (root.value.monkeyA == pathToHumn[1]) {
root.value.monkeyB
} else {
root.value.monkeyA
}
var otherValue = (monkeys[otherValueName]!! as Either.Left).value
for (it in pathToHumn.drop(1)) {
val monkey = monkeys[it]!! as Either.Right
val monkeyA = monkeys[monkey.value.monkeyA]!!
val monkeyB = monkeys[monkey.value.monkeyB]!!
val op = monkey.value.op
if (monkeyA is Either.Left && monkeyB is Either.Right<Monkey> || monkey.value.monkeyB == "humn") {
val v = (monkeyA as Either.Left<Long>).value
otherValue = when (op) {
MathOp.ADD -> otherValue - v
MathOp.SUB -> v - otherValue
MathOp.MUL -> otherValue / v
MathOp.DIV -> v / otherValue
}
} else if (monkeyB is Either.Left<Long> && monkeyA is Either.Right<Monkey> || monkey.value.monkeyA == "humn") {
val v = (monkeyB as Either.Left<Long>).value
otherValue = when (op) {
MathOp.ADD -> otherValue - v
MathOp.SUB -> otherValue + v
MathOp.MUL -> otherValue / v
MathOp.DIV -> otherValue * v
}
} else {
throw IllegalArgumentException("Invalid monkey $it")
}
}
return otherValue
}
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 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 4,600 | aoc-2022 | Apache License 2.0 |
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2015/day16/Day16.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2015.day16
import nl.sanderp.aoc.common.readResource
fun parseLine(line: String): Map<String, Int> {
val facts = line.split(": ", limit = 2)[1].split(", ")
return buildMap {
for (fact in facts) {
val (key, value) = fact.split(": ")
put(key, value.toInt())
}
}
}
val firstRules = mapOf<String, (Int) -> Boolean>(
"children" to { it == 3 },
"cats" to { it == 7 },
"samoyeds" to { it == 2 },
"pomeranians" to { it == 3 },
"akitas" to { it == 0 },
"vizslas" to { it == 0 },
"goldfish" to { it == 5 },
"trees" to { it == 3 },
"cars" to { it == 2 },
"perfumes" to { it == 1 },
)
val secondRules = firstRules + mapOf(
"cats" to { it > 7 },
"pomeranians" to { it < 3 },
"goldfish" to { it < 5 },
"trees" to { it > 3 },
)
private fun Int?.check(predicate: (Int) -> Boolean) = this?.let(predicate) ?: true
fun main() {
val input = readResource("16.txt").lines().map(::parseLine)
val firstMatch = input.withIndex().single { (_, facts) ->
firstRules.all { (key, predicate) -> facts[key].check(predicate) }
}
println("Part one: ${firstMatch.index + 1}")
val secondMatch = input.withIndex().single { (_, facts) ->
secondRules.all { (key, predicate) -> facts[key].check(predicate) }
}
println("Part two: ${secondMatch.index + 1}")
} | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,405 | advent-of-code | MIT License |
src/main/kotlin/io/array/CourseScheduleSolution.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.array
import java.util.*
// https://leetcode.com/problems/course-schedule-iii/solution/
class CourseScheduleSolution {
fun execute(courses: Array<IntArray>): Int {
fun tryToChangePreviousLongerCourse(courses: Array<IntArray>, index: Int, duration: Int): Int? {
var longestCourse = index
(0 until index).forEach { j ->
if (courses[j].duration() > courses[longestCourse].duration())
longestCourse = j
}
return courses[longestCourse].duration().let { longestDuration ->
courses[longestCourse][0] = -1
if (longestDuration > duration) (duration - longestDuration) else null
}
}
courses.sortBy { it.endDay() }
var count = 0
var time = 0
courses.map { it.duration() to it.endDay() }.forEachIndexed { index, (duration, endDay) ->
if (duration + time <= endDay) {
count++
time += duration
} else {
tryToChangePreviousLongerCourse(courses, index, duration)?.let { time += it }
}
}
return count
}
private fun IntArray.duration() = this.first()
private fun IntArray.endDay() = this[1]
fun executeWithPriorityQueue(courses: Array<IntArray>): Int {
courses.sortBy { it.endDay() }
val queue = PriorityQueue<Int>(Comparator { a, b -> b - a })
var time = 0
courses.map { course ->
if (time + course.duration() <= course.endDay()) {
queue.offer(course.duration())
time += course.duration()
} else if (queue.isNotEmpty() && queue.peek() > course.duration()) {
time += course.duration() - queue.poll()
queue.offer(course.duration())
}
}
return queue.size
}
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,682 | coding | MIT License |
day5/src/main/kotlin/Main.kt | joshuabrandes | 726,066,005 | false | {"Kotlin": 47373} | import java.io.File
var seedToSoilMap: AlmanachMap? = null
var soilToFertilizerMap: AlmanachMap? = null
var fertilizerToWaterMap: AlmanachMap? = null
var waterToLightMap: AlmanachMap? = null
var lightToTemperatureMap: AlmanachMap? = null
var temperatureToHumidityMap: AlmanachMap? = null
var humidityToLocationMap: AlmanachMap? = null
fun main() {
println("------ Advent of Code 2023 - Day -----")
val puzzleInput = getPuzzleInput()
val seeds = getSeeds(puzzleInput)
seedToSoilMap = getMapByName("seed-to-soil map", puzzleInput)
soilToFertilizerMap = getMapByName("soil-to-fertilizer map", puzzleInput)
fertilizerToWaterMap = getMapByName("fertilizer-to-water map", puzzleInput)
waterToLightMap = getMapByName("water-to-light map", puzzleInput)
lightToTemperatureMap = getMapByName("light-to-temperature map", puzzleInput)
temperatureToHumidityMap = getMapByName("temperature-to-humidity map", puzzleInput)
humidityToLocationMap = getMapByName("humidity-to-location map", puzzleInput)
val locations = seeds.asSequence()
.map { seed -> mapSeedsToLocation(seed) }
println("Task 1: Minimum location: ${locations.minOrNull()}")
// --- Task 2 ---
val minimumSeedLocation = findMinimumLocationForSeedRanges(seeds)
println("Task 2: Minimum location: $minimumSeedLocation")
println("----------------------------------------")
}
fun findMinimumLocationForSeedRanges(seeds: List<Long>): Long {
return seeds
.chunked(2)
.fold(Long.MAX_VALUE) { minLocation, seedRange ->
val (start, length) = seedRange
val end = start + length
(start..<end).fold(minLocation) { currentMin, seed ->
minOf(currentMin, mapSeedsToLocation(seed))
}
}
}
fun mapSeedsToLocation(seed: Long): Long {
return listOfNotNull(
seedToSoilMap,
soilToFertilizerMap,
fertilizerToWaterMap,
waterToLightMap,
lightToTemperatureMap,
temperatureToHumidityMap,
humidityToLocationMap
).fold(seed) { input, map ->
map.getByInput(input)
}
}
fun getMapByName(delimiter: String, puzzleInput: List<String>): AlmanachMap {
for (lineNumber in puzzleInput.indices) {
if (puzzleInput[lineNumber].contains(delimiter)) {
val map = mutableListOf<List<Long>>()
var lineDela = lineNumber + 1
// Stelle sicher, dass lineDela innerhalb der Grenzen von puzzleInput bleibt
while (lineDela < puzzleInput.size && puzzleInput[lineDela].isNotEmpty()) {
val line = puzzleInput[lineDela]
val row = line.split(" ")
.map { it.trim() }
.filter { it.isNotEmpty() }
.map { it.toLong() }
map.add(row)
lineDela++
}
return AlmanachMap(map)
}
}
throw Exception("Map not found")
}
fun getSeeds(puzzleInput: List<String>): List<Long> {
return puzzleInput[0]
.substringAfter("seeds: ")
.split(" ")
.map { it.trim() }
.filter { it.isNotEmpty() }
.map { it.toLong() }
}
fun getPuzzleInput(): List<String> {
val fileUrl = ClassLoader.getSystemResource("input.txt")
return File(fileUrl.toURI()).readLines()
}
data class AlmanachMap(val map: List<List<Long>>) {
fun getByInput(input: Long): Long {
for (row in map) {
if (valueIsInRange(input, row)) {
return row[0] + (input - row[1])
}
}
// if no row was found, return input
return input
}
private fun valueIsInRange(input: Long, row: List<Long>): Boolean {
val min = row[1]
val max = (row[1] + row[2]) - 1
return input in min..max
}
}
| 0 | Kotlin | 0 | 1 | de51fd9222f5438efe9a2c45e5edcb88fd9f2232 | 3,846 | aoc-2023-kotlin | The Unlicense |
src/Day08.kt | emersonf | 572,870,317 | false | {"Kotlin": 17689} | fun main() {
fun List<String>.asGrid(): Array<IntArray> {
val grid = Array(size) {
IntArray(size)
}
forEachIndexed { row, line ->
line.forEachIndexed { column, char ->
grid[row][column] = char.digitToInt()
}
}
return grid
}
fun Array<IntArray>.print() {
forEach { println(it.joinToString()) }
}
fun part1(input: List<String>): Int {
// simple solution is n^2 where n is total number of trees
// should be able to work in passes, first from left, then top, then right, etc.
val edgeSize = input.size
val visible = Array(edgeSize) {
IntArray(edgeSize) // 0 == not visible, 1 == visible
}
val grid = input.asGrid()
var totalVisible = 0
fun checkRowVisibility(progression: IntProgression) {
for (i in 0 until edgeSize) {
var maximum = -1
for (j in progression) {
if (grid[i][j] > maximum) {
maximum = grid[i][j]
if (visible[i][j] == 0) {
visible[i][j] = 1
totalVisible++
}
}
}
}
}
fun checkColumnVisibility(progression: IntProgression) {
for (i in 0 until edgeSize) {
var maximum = -1
for (j in progression) {
if (grid[j][i] > maximum) {
maximum = grid[j][i]
if (visible[j][i] == 0) {
visible[j][i] = 1
totalVisible++
}
}
}
}
}
checkRowVisibility(0..edgeSize - 1)
checkRowVisibility(edgeSize - 1 downTo 0)
checkColumnVisibility(0..edgeSize - 1)
checkColumnVisibility(edgeSize - 1 downTo 0)
return totalVisible
}
fun part2(input: List<String>): Int {
val edgeSize = input.size
val visibility = Array(edgeSize) {
IntArray(edgeSize) { 1 }
}
val grid = input.asGrid()
fun computeVisibleDistances(treeHeights: Iterable<Int>): Iterable<Int> {
val treeHeightIndexes = MutableList(10) { 0 } // ignore 0 index
return treeHeights.mapIndexed { index, treeHeight ->
val closestBlockingTreeIndex = treeHeightIndexes.subList(treeHeight, 10).max()
val visibleDistance = (index - closestBlockingTreeIndex).coerceAtLeast(1)
treeHeightIndexes[treeHeight] = index
if (index == 0) 0 else visibleDistance // ignore edge trees
}
}
fun processRowLeftToRight(row: Int) {
val treeHeights = grid[row]
computeVisibleDistances(treeHeights.asIterable())
.forEachIndexed { index, visibleDistance ->
visibility[row][index] *= visibleDistance
}
}
fun processRowRightToLeft(row: Int) {
val treeHeights = grid[row].asIterable().reversed()
computeVisibleDistances(treeHeights)
.forEachIndexed { index, visibleDistance ->
visibility[row][edgeSize - index - 1] *= visibleDistance
}
}
fun processColumnTopToBottom(column: Int) {
val treeHeights = grid.map { it.get(column) }
computeVisibleDistances(treeHeights)
.forEachIndexed { index, visibleDistance ->
visibility[index][column] *= visibleDistance
}
}
fun processColumnBottomToTop(column: Int) {
val treeHeights = grid.map { it.get(column) }.reversed()
computeVisibleDistances(treeHeights)
.forEachIndexed { index, visibleDistance ->
visibility[edgeSize - index - 1][column] *= visibleDistance
}
}
for (i in 0 until edgeSize) {
processRowLeftToRight(i)
processRowRightToLeft(i)
processColumnTopToBottom(i)
processColumnBottomToTop(i)
}
return visibility.maxOf { it.max() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0e97351ec1954364648ec74c557e18ccce058ae6 | 4,634 | advent-of-code-2022-kotlin | Apache License 2.0 |
2022/src/day06/day06.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day06
import GREEN
import RESET
import printTimeMillis
import readInput
fun findMarker(str: String, markerSize: Int): Int {
for (i in 0..str.length - markerSize) {
if (str.substring(i, i + markerSize).toSet().size == markerSize) {
return i + markerSize
}
}
throw IllegalStateException("Wrong packet bro")
}
fun part1(input: List<String>) = findMarker(input.first(), 4)
fun part2(input: List<String>) = findMarker(input.first(), 14)
fun part2forDodo(input: List<String>) = input.first().let {
val markerSize = 5*2+4
for (i in 0..it.length - markerSize) {
val one = it[i]
val two = it[i + 1]
val three = it[i + 2]
val four = it[i + 3]
val five = it[i + 4]
val six = it[i + 5]
val seven = it[i + 6]
val two_times_four = it[i + 7]
val nine = it[i + 8]
val two_times_five = it[i + 9]
val eleven = it[i + 10]
val twelve = it[i + 11]
val thirteen = it[i + 12]
val two_times_seven = it[i + 13]
if (setOf(
one, two, three, four, five, six, seven, two_times_four,
nine, two_times_five, eleven, twelve, thirteen, two_times_seven
).size == markerSize) {
return@let i + markerSize
}
}
throw IllegalStateException("Wrong packet bro")
}
fun main() {
val testInput = readInput("day06_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day06.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
printTimeMillis { print("part2 for dodo = $GREEN" + part2forDodo(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 1,889 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumDifference.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
import kotlin.math.min
/**
* 2163. Minimum Difference in Sums After Removal of Elements
* @see <a href="https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/">Source</a>
*/
fun interface MinimumDifference {
operator fun invoke(nums: IntArray): Long
}
class MinimumDifferencePriorityQueue : MinimumDifference {
override operator fun invoke(nums: IntArray): Long {
var s1: Long = 0
var s2: Long = 0
val dp = LongArray(nums.size)
var r = Long.MAX_VALUE
val n = nums.size / 3
val q1: PriorityQueue<Int> = PriorityQueue(Comparator.reverseOrder())
val q2: PriorityQueue<Int> = PriorityQueue()
for (i in 0 until 2 * n) {
q1.offer(nums[i])
s1 += nums[i]
if (q1.size > n) {
s1 -= q1.poll()
}
dp[i] = s1
}
for (i in nums.size - 1 downTo n) {
q2.offer(nums[i])
s2 += nums[i]
if (q2.size > n) {
s2 -= q2.poll()
}
if (q2.size == n) {
r = min(r, dp[i - 1] - s2)
}
}
return r
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,861 | kotlab | Apache License 2.0 |
src/day9/Day09.kt | dinoolivo | 573,723,263 | false | null | package day9
import readInput
fun main() {
fun findNumVisitedByTail(input: List<String>, numRopeNodes:Int): Int {
val ropeNodes = mutableListOf<Position>()
for(i in 0 until numRopeNodes){
ropeNodes.add(Position(0,0))
}
val visited = HashSet<Position>()
for(direction in input){
val directionParts = direction.split(" ")
val funcToApply:(Position) -> Position = when(directionParts[0]){
"R" -> ::moveRight
"L" -> ::moveLeft
"U" -> ::moveTop
"D" -> ::moveBottom
else -> ::doNotMove
}
for(i in 0 until directionParts[1].toInt()){
ropeNodes[0] = funcToApply(ropeNodes[0])
for(j in 1 until numRopeNodes){
ropeNodes[j] = ropeNodes[j].positionToBeAdjacent(ropeNodes[j-1])
}
visited.add(ropeNodes[ropeNodes.size-1])
}
}
return visited.size
}
fun part1(input: List<String>): Int = findNumVisitedByTail(input, 2)
fun part2(input: List<String>): Int = findNumVisitedByTail(input, 10)
val testInput = (readInput("inputs/Day09_test"))
println("Test Part 1: " + part1(testInput))
println("Test Part 2: " + part2(testInput))
//execute the two parts on the real input
val input = readInput("inputs/Day09")
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 6e75b42c9849cdda682ac18c5a76afe4950e0c9c | 1,503 | aoc2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountDifferentPalindromicSubsequences.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.MOD
/**
* 730. Count Different Palindromic Subsequences
* @see <a href="https://leetcode.com/problems/count-different-palindromic-subsequences/">Source</a>
*/
fun interface CountDifferentPalindromicSubsequences {
fun countPalindromicSubsequences(s: String): Int
}
class CountDifferentPalindromicSubsequencesDP : CountDifferentPalindromicSubsequences {
override fun countPalindromicSubsequences(s: String): Int {
val len: Int = s.length
val dp = Array(len) { IntArray(len) }
val chs = s.toCharArray()
for (i in 0 until len) {
dp[i][i] = 1
}
for (distance in 1 until len) {
for (i in 0 until len - distance) {
val j = i + distance
if (chs[i] == chs[j]) {
var low = i + 1
var high = j - 1
while (low <= high && chs[low] != chs[j]) {
low++
}
while (low <= high && chs[high] != chs[j]) {
high--
}
if (low > high) {
dp[i][j] = dp[i + 1][j - 1] * 2 + 2
} else if (low == high) {
dp[i][j] = dp[i + 1][j - 1] * 2 + 1
} else {
dp[i][j] = dp[i + 1][j - 1] * 2 - dp[low + 1][high - 1]
}
} else {
dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]
}
dp[i][j] = if (dp[i][j] < 0) dp[i][j] + MOD else dp[i][j] % MOD
}
}
return dp[0][len - 1]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,351 | kotlab | Apache License 2.0 |
src/main/kotlin/Day10.kt | i-redbyte | 433,743,675 | false | {"Kotlin": 49932} | import java.util.*
fun main() {
val data = readInputFile("day10")
fun part1(): Int {
return data.sumOf { it.findSyntaxErrorScore() }
}
fun part2(): Long {
return data
.mapNotNull { it.findCompletionScore() }
.filter { it != 0L }
.sorted()
.let { it[it.size / 2] }
}
println("Result part1: ${part1()}")
println("Result part2: ${part2()}")
}
fun String.findSyntaxErrorScore(): Int {
val stack = LinkedList<Char>()
var i = 0
do {
when (val c = this[i]) {
'(', '[', '{', '<' -> stack.push(c)
')' -> {
val top = stack.pop()
if (top != '(') return score(c)
}
']' -> {
val top = stack.pop()
if (top != '[') return score(c)
}
'}' -> {
val top = stack.pop()
if (top != '{') return score(c)
}
'>' -> {
val top = stack.pop()
if (top != '<') return score(c)
}
}
i++
} while (stack.isNotEmpty() && i < length)
return 0
}
fun String.findCompletionScore(): Long? {
val stack = LinkedList<Char>()
var i = 0
do {
when (val c = this[i]) {
'(', '[', '{', '<' -> stack.push(c)
')' -> {
val top = stack.pop()
if (top != '(') return null
}
']' -> {
val top = stack.pop()
if (top != '[') return null
}
'}' -> {
val top = stack.pop()
if (top != '{') return null
}
'>' -> {
val top = stack.pop()
if (top != '<') return null
}
}
i++
} while (stack.isNotEmpty() && i < length)
return stack
.fold(0L) { acc, char ->
(acc * 5) + when (char) {
'(' -> 1
'[' -> 2
'{' -> 3
'<' -> 4
else -> 0
}
}
}
fun score(char: Char): Int = when(char) {
')' -> 3
']' -> 57
'}' -> 1197
'>' -> 25137
else -> 0
}
| 0 | Kotlin | 0 | 0 | 6d4f19df3b7cb1906052b80a4058fa394a12740f | 2,263 | AOC2021 | Apache License 2.0 |
src/main/kotlin/leetcode/kotlin/misc/350. Intersection of Two Arrays II.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.misc
private fun intersect5(nums1: IntArray, nums2: IntArray): IntArray {
nums1.sort()
nums2.sort()
var ans = ArrayList<Int>()
var i = 0
var j = 0
while (i < nums1.size && j < nums2.size) {
when {
nums1[i] > nums2[j] -> j++
nums1[i] < nums2[j] -> i++
else -> {
ans.add(nums1[i])
i++
j++
}
}
}
return ans.toIntArray()
}
private fun intersect4(nums1: IntArray, nums2: IntArray): IntArray {
var map = HashMap<Int, Int>()
var list = ArrayList<Int>()
nums1.forEach { i -> map.put(i, map.getOrDefault(i, 0) + 1) }
for (i in nums2) {
if (map.containsKey(i) && map.get(i)!! > 0) {
map.put(i, map.get(i)!! - 1)
list.add(i)
}
}
return list.toIntArray()
}
private fun intersect3(nums1: IntArray, nums2: IntArray): IntArray {
var map = HashMap<Int, Int>()
var list = ArrayList<Int>()
nums1.forEach { i -> map.put(i, map.getOrDefault(i, 0) + 1) }
nums2.forEach { i ->
run {
if (map.containsKey(i) && map.get(i)!! > 0) {
map.put(i, map.get(i)!! - 1)
list.add(i)
}
}
}
return list.toIntArray()
}
private fun intersect2(nums1: IntArray, nums2: IntArray): IntArray {
var map1 = HashMap<Int, Int>()
nums1.forEach { i -> map1.put(i, map1.getOrDefault(i, 0) + 1) }
var map2 = HashMap<Int, Int>()
nums2.forEach { i -> map2.put(i, map2.getOrDefault(i, 0) + 1) }
var list = ArrayList<Int>()
map1.keys.forEach {
var min = Math.min(map1.getOrDefault(it, 0), map2.getOrDefault(it, 0))
for (i in 0 until min) list.add(it)
}
return list.toIntArray()
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 1,804 | kotlinmaster | Apache License 2.0 |
codeforces/round740/b.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round740
fun main() {
val (n, m) = readInts()
Modular.M = m
val primeDivisors = primeDivisors(n)
val a = Array(n + 1) { it.toModular() }
for (i in 3..n) {
a[i] = 1 + 2 * a[i - 1]
for (r in divisorsOf(i, primeDivisors)) {
if (r == 1 || r == i) continue
a[i] += a[r] - a[r - 1]
}
}
println(a.last())
}
fun divisorsOf(n: Int, primeDivisors: IntArray): IntArray {
if (n == 1) return intArrayOf(1)
val p = primeDivisors[n]
var m = n / p
var counter = 2
while (m % p == 0) {
m /= p
counter++
}
val divisorsOfM = divisorsOf(m, primeDivisors)
val result = IntArray(divisorsOfM.size * counter)
for (i in divisorsOfM.indices) {
var d = divisorsOfM[i]
for (j in 0 until counter) {
result[i * counter + j] = d
d *= p
}
}
return result
}
fun primeDivisors(n: Int): IntArray {
val primeDivisors = IntArray(n + 1) { it }
for (i in 2..n) {
if (primeDivisors[i] < i) continue
var j = i * i
if (j > n) break
do {
primeDivisors[j] = i
j += i
} while (j <= n)
}
return primeDivisors
}
private fun Int.toModular() = Modular(this)//toDouble()
private class Modular {
companion object {
var M: Int = 0
}
val x: Int
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } }
operator fun plus(that: Modular) = Modular((x + that.x) % M)
operator fun minus(that: Modular) = Modular((x + M - that.x) % M)
operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular()
private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt())
operator fun div(that: Modular) = times(that.modInverse())
override fun toString() = x.toString()
}
private operator fun Int.plus(that: Modular) = Modular(this) + that
private operator fun Int.minus(that: Modular) = Modular(this) - that
private operator fun Int.times(that: Modular) = Modular(this) * that
private operator fun Int.div(that: Modular) = Modular(this) / that
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,138 | competitions | The Unlicense |
ceria/15/src/main/kotlin/Solution.kt | VisionistInc | 317,503,410 | false | null | import java.io.File
import java.util.Collections
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
private fun solution1(input :List<String>) :Int {
var nums = input.first().split(",").map{ it.toInt() }.toMutableList()
while (nums.size < 2020) {
var lastNumSpoken = nums.last()
if (Collections.frequency(nums, lastNumSpoken) == 1) {
nums.add(0)
} else {
var lastSpokenIndex = nums.dropLast(1).lastIndexOf(lastNumSpoken)
nums.add((nums.size - 1) - lastSpokenIndex)
}
}
return nums.last()
}
private fun solution2(input :List<String>) :Int {
var nums = input.first().split(",").map{ it.toInt() }
var numsMap = mutableMapOf<Int, Pair<Int, Int>>() // num => Pair(firstIndex, secondIndex)
for (n in nums.indices) {
numsMap.put(nums[n], Pair(n, -1))
}
var turn = nums.size
var lastSpoken = nums.last()
while (turn < 30000000) {
if (numsMap.containsKey(lastSpoken)) {
var indexPair = numsMap.get(lastSpoken)
if (indexPair!!.second == -1 && indexPair.first == turn - 1) {
// not spoken before
lastSpoken = 0
} else {
// spoken before
val lastSpokenPair = numsMap.get(lastSpoken)
lastSpoken = lastSpokenPair!!.second - lastSpokenPair.first
}
} else {
// not spoken before
lastSpoken = 0
}
if (numsMap.containsKey(lastSpoken)) {
val lastSpokenPair = numsMap.get(lastSpoken)
val newFirst = if (lastSpokenPair!!.second == -1) lastSpokenPair.first else lastSpokenPair.second
var updatedPair = Pair(newFirst, turn)
numsMap.put(lastSpoken, updatedPair)
} else {
numsMap.put(lastSpoken, Pair(turn, -1))
}
turn++
}
return lastSpoken
} | 0 | Rust | 0 | 0 | 002734670384aa02ca122086035f45dfb2ea9949 | 1,857 | advent-of-code-2020 | MIT License |
src/Day07.kt | Aldas25 | 572,846,570 | false | {"Kotlin": 106964} | fun main() {
// for part 1
val sizeLimit = 100000
// for part 2
val totalSpace = 70000000
val needUnused = 30000000
class Node(val name: String, val isLeaf: Boolean, val parent: Node?) {
var size: Int = 0
constructor(name: String, isLeaf: Boolean, parent: Node?, size: Int) : this(name, isLeaf, parent) {
this.size = size
}
val children = mutableListOf<Node>()
fun addChild(child: Node) {
children.add(child)
}
fun calcSizes() {
if (isLeaf) return
size = 0
for (child in children) {
child.calcSizes()
size += child.size
}
}
fun part1(): Int {
if (isLeaf)
return 0
var ans = 0
if (size <= sizeLimit) {
ans += size
}
for (child in children) {
ans += child.part1()
}
return ans
}
fun part2(removeAtLeast: Int): Int {
if (isLeaf) return Int.MAX_VALUE
var ans = Int.MAX_VALUE
if (size >= removeAtLeast) ans = minOf(ans, size)
for (child in children)
ans = minOf(ans, child.part2(removeAtLeast))
return ans
}
}
fun part1(root: Node): Int {
return root.part1()
}
fun part2(root: Node): Int {
val removeAtLeast = needUnused - (totalSpace - root.size)
return root.part2(removeAtLeast)
}
fun constructTree(input: List<String>): Node {
val root = Node("/",false, null)
var current = root
for (i in input.indices) {
val s = input[i]
if (s[0] != '$') continue
//println("now i=$i, current name = ${current.name}")
if (s[2] == 'c') {
// cd
val directory = s.substring(5)
if (directory == "..")
current = current.parent!!
else if (directory == "/")
current = root
else
for (child in current.children) {
if (child.name == directory) {
current = child
break
}
}
} else {
// ls
var j = i+1
while (j < input.size && input[j][0] != '$') {
val line = input[j]
val parts = line.split(" ")
val name = parts[1]
val child = if (parts[0] == "dir") {
// dir
Node(name, false, current)
} else {
// file
val size = parts[0].toInt()
Node(name, true, current, size)
}
current.addChild(child)
j++
}
}
}
return root
}
val filename =
// "inputs/day07_sample"
"inputs/day07"
val input = readInput(filename)
val root = constructTree(input)
root.calcSizes()
println("Part 1: ${part1(root)}")
println("Part 2: ${part2(root)}")
} | 0 | Kotlin | 0 | 0 | 80785e323369b204c1057f49f5162b8017adb55a | 3,361 | Advent-of-Code-2022 | Apache License 2.0 |
kotlin/MaxBipartiteMatchingEV.kt | polydisc | 351,544,331 | true | {"Java": 541473, "C++": 265630, "Python": 59545, "Kotlin": 28417, "CMake": 571} | // https://en.wikipedia.org/wiki/Matching_(graph_theory)#In_unweighted_bipartite_graphs in O(V * E)
fun maxMatching(graph: Array<out List<Int>>): Int {
val n1 = graph.size
val n2 = (graph.flatMap { it }.maxOrNull() ?: -1) + 1
val matching = IntArray(n2) { -1 }
return (0 until n1).sumOf { findPath(graph, it, matching, BooleanArray(n1)) }
}
fun findPath(graph: Array<out List<Int>>, u1: Int, matching: IntArray, vis: BooleanArray): Int {
vis[u1] = true
for (v in graph[u1]) {
val u2 = matching[v]
if (u2 == -1 || !vis[u2] && findPath(graph, u2, matching, vis) == 1) {
matching[v] = u1
return 1
}
}
return 0
}
// Usage example
fun main(args: Array<String>) {
val g = (1..2).map { arrayListOf<Int>() }.toTypedArray()
g[0].add(0)
g[0].add(1)
g[1].add(1)
println(2 == maxMatching(g))
}
| 1 | Java | 0 | 0 | be589a7d88250947a53ec07e6f74118857d2e65b | 884 | codelibrary | The Unlicense |
src/main/kotlin/aoc2016/SquaresWithThreeSides.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2016
import komu.adventofcode.utils.nonEmptyLines
fun squaresWithThreeSides1(input: String): Int {
val triangles = input.nonEmptyLines().map { Triangle.parse(it) }
return triangles.count { it.isPossible() }
}
fun squaresWithThreeSides2(input: String): Int {
val triangles = input.nonEmptyLines().map { Triangle.parse(it) }.chunked(3).flatMap { (a,b,c) ->
listOf(Triangle(a.x, b.x, c.x), Triangle(a.y, b.y, c.y), Triangle(a.z, b.z, c.z))
}
return triangles.count { it.isPossible() }
}
private data class Triangle(val x: Int, val y: Int, val z: Int) {
fun isPossible(): Boolean {
val hypothenuse = maxOf(x, y, z)
val sides = x + y + z - hypothenuse
return sides > hypothenuse
}
companion object {
private val pattern = Regex("""\s*(\d+)\s+(\d+)\s+(\d+)""")
fun parse(s: String): Triangle {
val (_, x, y, z) = pattern.matchEntire(s)?.groupValues ?: error("invalid input '$s'")
return Triangle(x.toInt(), y.toInt(), z.toInt())
}
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,085 | advent-of-code | MIT License |
kotlin/2306-naming-a-company.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} | class Solution {
fun distinctNames(ideas: Array<String>): Long {
val firstToSuffix = Array(26) { hashSetOf<String>() }
var res = 0L
ideas.forEach {
firstToSuffix[it[0] - 'a'].add(it.substring(1, it.length))
}
for (i in 0 until 26) {
for (j in i until 26) {
val common = firstToSuffix[i].intersect(firstToSuffix[j]).size
val mapI = firstToSuffix[i].size - common
val mapJ = firstToSuffix[j].size - common
res += (mapI * mapJ) * 2
}
}
return res
}
}
// without using kotlins intersect() funtions
class Solution {
fun distinctNames(ideas: Array<String>): Long {
val firstToSuffix = Array(26) { hashSetOf<String>() }
var res = 0L
ideas.forEach {
firstToSuffix[it[0] - 'a'].add(it.substring(1, it.length))
}
for (i in 0 until 26) {
for (j in i until 26) {
var common = 0
for(wordA in firstToSuffix[i]) {
if(wordA in firstToSuffix[j]) common++
}
val mapI = firstToSuffix[i].size - common
val mapJ = firstToSuffix[j].size - common
res += (mapI * mapJ) * 2
}
}
return res
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,376 | leetcode | MIT License |
src/main/kotlin/days/Day1.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package days
import util.DayInput
class Day1 : Day("1") {
override fun partOne(dayInput: DayInput): Any {
val digits = dayInput.inputList().map { line ->
line.toCharArray().filter { it.isDigit() }.map { it.digitToInt() }
}
return digits.map { 10 * it.first() + it.last() }.sum()
}
override fun partTwo(dayInput: DayInput): Any {
val replacement = listOf(
Pair("one", 1),
Pair("two", 2),
Pair("three", 3),
Pair("four", 4),
Pair("five", 5),
Pair("six", 6),
Pair("seven", 7),
Pair("eight", 8),
Pair("nine", 9),
Pair("1", 1),
Pair("2", 2),
Pair("3", 3),
Pair("4", 4),
Pair("5", 5),
Pair("6", 6),
Pair("7", 7),
Pair("8", 8),
Pair("9", 9),
)
val digits = dayInput.inputList().map { line ->
val map = replacement.flatMap {
val mutableListOf = mutableListOf<Pair<Int, Pair<String, Int>>>()
var prevIndex = line.indexOf(it.first, 0)
mutableListOf.add(Pair(prevIndex, it))
while (prevIndex != -1) {
val index = line.indexOf(it.first, prevIndex + 1)
if (index != -1) {
mutableListOf.add(Pair(index, it))
}
prevIndex = index
}
mutableListOf
}.filter { it.first != -1 }.sortedBy { it.first }.map { it.second.second }
map
}
return digits.map { 10 * it.first() + it.last() }.sum()
}
}
fun main() {
Day1().run()
}
| 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 1,754 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
year2016/src/main/kotlin/net/olegg/aoc/year2016/day7/Day7.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2016.day7
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2016.DayOf2016
/**
* See [Year 2016, Day 7](https://adventofcode.com/2016/day/7)
*/
object Day7 : DayOf2016(7) {
private val ABBA = ('a'..'z')
.flatMap { a -> ('a'..'z').filter { b -> a != b }.map { b -> "$a$b$b$a" } }
private val ABABAB = ('a'..'z')
.flatMap { a -> ('a'..'z').filter { b -> a != b }.map { b -> "$a$b$a" to "$b$a$b" } }
private fun splitAddresses(addresses: List<String>): List<Pair<List<String>, List<String>>> {
return addresses.map { it.split("[", "]") }
.map { tokens -> tokens.mapIndexed { i, s -> i to s }.partition { it.first % 2 == 0 } }
.map { (outer, inner) -> outer.map { it.second } to inner.map { it.second } }
}
override fun first(): Any? {
return splitAddresses(lines)
.filterNot { (_, inner) -> inner.any { token -> ABBA.any { it in token } } }
.count { (outer, _) -> outer.any { token -> ABBA.any { it in token } } }
}
override fun second(): Any? {
return splitAddresses(lines)
.count { (outer, inner) ->
ABABAB.any { ab ->
outer.any { ab.first in it } && inner.any { ab.second in it }
}
}
}
}
fun main() = SomeDay.mainify(Day7)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,267 | adventofcode | MIT License |
kotlin/graphs/matchings/MinBipartiteWeightedMatchingHungarian.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs.matchings
import java.util.Arrays
// https://en.wikipedia.org/wiki/Hungarian_algorithm in O(n^2 * m)
object MinBipartiteWeightedMatchingHungarian {
// a[n][m], n <= m, sum(a[i][p[i]]) -> min
fun minWeightPerfectMatching(a: Array<IntArray>): Int {
val n = a.size
val m: Int = a[0].length
val u = IntArray(n)
val v = IntArray(m)
val p = IntArray(m)
val way = IntArray(m)
for (i in 1 until n) {
val minv = IntArray(m)
Arrays.fill(minv, Integer.MAX_VALUE)
val used = BooleanArray(m)
p[0] = i
var j0 = 0
while (p[j0] != 0) {
used[j0] = true
val i0 = p[j0]
var delta: Int = Integer.MAX_VALUE
var j1 = 0
for (j in 1 until m) if (!used[j]) {
val d = a[i0][j] - u[i0] - v[j]
if (minv[j] > d) {
minv[j] = d
way[j] = j0
}
if (delta > minv[j]) {
delta = minv[j]
j1 = j
}
}
for (j in 0 until m) if (used[j]) {
u[p[j]] += delta
v[j] -= delta
} else minv[j] -= delta
j0 = j1
}
while (j0 != 0) {
val j1 = way[j0]
p[j0] = p[j1]
j0 = j1
}
}
val matching = IntArray(n)
for (i in 1 until m) matching[p[i]] = i
return -v[0]
}
// Usage example
fun main(args: Array<String?>?) {
// row1 and col1 should contain 0
val a = arrayOf(intArrayOf(0, 0, 0), intArrayOf(0, 1, 2), intArrayOf(0, 1, 2))
val res = minWeightPerfectMatching(a)
System.out.println(3 == res)
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 1,938 | codelibrary | The Unlicense |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxSumBST.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.max
import kotlin.math.min
/**
* 1373. Maximum Sum BST in Binary Tree
* @see <a href="https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/">Source</a>
*/
fun interface MaxSumBST {
operator fun invoke(root: TreeNode): Int
}
class MaxSumBSTPostOrder : MaxSumBST {
override operator fun invoke(root: TreeNode): Int {
val res = dfs(root)
return max(res[3], 0)
}
fun dfs(root: TreeNode?): IntArray {
if (root == null) return intArrayOf(Int.MAX_VALUE, Int.MIN_VALUE, 0, Int.MIN_VALUE)
val left = dfs(root.left)
val right = dfs(root.right)
return if (root.value > left[1] && root.value < right[0]) {
val min = min(left[0], root.value)
val max = max(right[1], root.value)
val sum: Int = left[2] + right[2] + root.value
val maxSum = max(sum, max(left[3], right[3]))
intArrayOf(min, max, sum, maxSum)
} else {
intArrayOf(
Int.MIN_VALUE,
Int.MAX_VALUE,
max(
left[2],
right[2],
),
max(left[3], right[3]),
)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,865 | kotlab | Apache License 2.0 |
src/main/kotlin/io/nozemi/aoc/solutions/year2021/day10/SyntaxScoring.kt | Nozemi | 433,882,587 | false | {"Kotlin": 92614, "Shell": 421} | package io.nozemi.aoc.solutions.year2021.day10
import io.nozemi.aoc.puzzle.ANSI_BOLD
import io.nozemi.aoc.puzzle.ANSI_RED
import io.nozemi.aoc.puzzle.ANSI_RESET
import io.nozemi.aoc.puzzle.Puzzle
import io.nozemi.aoc.utils.median
import kotlin.reflect.KFunction0
fun main() {
SyntaxScoring("").printAnswers()
}
class SyntaxScoring(input: String) : Puzzle<List<String>>(input) {
override fun Sequence<String>.parse(): List<String> = toList()
override fun solutions(): List<KFunction0<Any>> = listOf(
::part1,
::part2
)
private fun part1(): Long {
return getScore(ScoreType.ERROR)
}
private fun part2(): Long {
return getScore(ScoreType.AUTO_COMPLETE)
}
fun getScore(type: ScoreType): Long {
var errorScore = 0L
val autoCompleteLineScores = mutableListOf<Long>()
var currentLineAutoScore = 0L
parsedInput.forEach {
it.syntaxChecker(errorOccurred = { bracket ->
when (bracket) {
')' -> errorScore += 3
']' -> errorScore += 57
'}' -> errorScore += 1197
'>' -> errorScore += 25137
}
}, missingClosingBrackets = { stacks ->
stacks.filter { stack -> !stack.second }.forEach { stack ->
currentLineAutoScore *= 5
when (stack.first.toClosing()) {
')' -> currentLineAutoScore += 1
']' -> currentLineAutoScore += 2
'}' -> currentLineAutoScore += 3
'>' -> currentLineAutoScore += 4
}
}
autoCompleteLineScores.add(currentLineAutoScore)
currentLineAutoScore = 0
})
}
return if (type == ScoreType.ERROR) {
errorScore
} else {
autoCompleteLineScores.median()
}
}
enum class ScoreType {
ERROR,
AUTO_COMPLETE
}
private val openingSymbols = listOf('[', '{', '(', '<')
private val closingSymbols = listOf(']', '}', ')', '>')
private fun String.syntaxChecker(
errorOccurred: (char: Char) -> Unit,
missingClosingBrackets: (stacks: ArrayDeque<Pair<Char, Boolean>>) -> Unit
) {
val stacks = ArrayDeque<Pair<Char, Boolean>>(0)
this.forEachIndexed { index, it ->
when (it) {
in openingSymbols -> stacks.addFirst(Pair(it, false))
in closingSymbols -> {
val lastNotClosedIndex = stacks.lastNotClosed() ?: return@forEachIndexed
val lastNotClosed = lastNotClosedIndex.second
if (lastNotClosed.first.toClosing() != it) return errorOccurred(it)
else stacks[lastNotClosedIndex.first] = Pair(it, true)
}
}
}
missingClosingBrackets(stacks)
}
private fun String.highlight(column: Int, color: String = ANSI_RED): String {
val char = this[column]
val part1 = this.substring(0 until column)
val part2 = this.substring((column - 1) until this.length)
return buildString {
append(part1)
append(color)
append(ANSI_BOLD)
append(char)
append(ANSI_RESET)
append(part2)
}
}
private fun Char.toClosing(): Char {
return when (this) {
'(' -> ')'
'[' -> ']'
'{' -> '}'
'<' -> '>'
else -> throw RuntimeException("Wtf are you doing!? You shouldn't be able to get this!")
}
}
private fun MutableList<Pair<Char, Boolean>>.setLast(value: Pair<Char, Boolean>) {
this[this.size - 1] = value
}
private fun ArrayDeque<Pair<Char, Boolean>>.lastNotClosed(): Pair<Int, Pair<Char, Boolean>>? {
for ((index, pair) in withIndex()) {
if (!pair.second) return Pair(index, pair)
}
return null
}
} | 0 | Kotlin | 0 | 0 | fc7994829e4329e9a726154ffc19e5c0135f5442 | 4,079 | advent-of-code | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day14.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year21
import com.grappenmaker.aoc.PuzzleSet
fun PuzzleSet.day14() = puzzle(day = 14) {
// Get the input
val (template, rules) = input.split("\n\n")
// Window (or count) pairs
val polymer = template.windowed(2).groupingBy { it }.eachCount().mapValues { it.value.toLong() }
val mapping = rules.split("\n").map { line ->
val split = line.split(" -> ")
split.first() to split.last()
}
// Perform a step, as in apply mappings and return the new map
val step = { current: Map<String, Long> ->
val result = mutableMapOf<String, Long>()
current.forEach { (part, count) ->
mapping.find { (find, _) -> find == part }?.let { (_, replace) ->
result[part.first() + replace] = (result[part.first() + replace] ?: 0) + count
result[replace + part.last()] = (result[replace + part.last()] ?: 0) + count
}
}
result
}
// Get the result after an arbitrary number of steps
val getResultAfter = { start: Map<String, Long>, steps: Int -> (1..steps).fold(start) { cur, _ -> step(cur) } }
// Calculate the puzzle answer (both parts)
val calculate = { values: Map<String, Long> ->
val result = values.entries.fold(mutableMapOf<Char, Long>()) { cur, entry ->
cur[entry.key.first()] = (cur[entry.key.first()] ?: 0L) + entry.value
cur
}.mapValues { (k, v) -> if (k == template.last()) v + 1 else v }
result.maxOf { it.value } - result.minOf { it.value }
}
// Return the result
val partOneResult = getResultAfter(polymer, 10)
partOne = calculate(partOneResult).s()
partTwo = calculate(getResultAfter(partOneResult, 30)).s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,758 | advent-of-code | The Unlicense |
语言知识(Language knowledge)/Kotlin/Practice/src/Main.kt | shencang | 83,188,062 | false | null | //顶层变量:
val Pi = 3.14159265358979
var temp = 0
fun main(){
//定义只读局部变量使⽤关键字 val 定义。只能为其赋值⼀次
val a: Int = 1 // ⽴即赋值
val b = 2 // ⾃动推断出 `Int` 类型
val c: Int // 如果没有初始值类型不能省略
c = 3 // 明确赋值
var edge = a*b*c
println("S-P-D-B")
println(sum(a,b))
edge*=2
println(sum1(b,c))
println(sum2(a,c))
println(sum3(b,c))
println("sum:${sum(edge,edge)}")
println(incrementX())
println(maxOf(a,b))
}
//带有两个 Int 参数、返回 Int 的函数
fun sum(a:Int,b:Int):Int{
return a+b
}
//将表达式作为函数体、返回值类型⾃动推断的函数
fun sum1(a:Int,b:Int)= a+b
//函数返回⽆意义的值:
fun sum2(a:Int,b:Int):Unit{
println("sum of $a and $b is ${a+b}")
}
//Unit 返回类型可以省略:
fun sum3(a:Int,b:Int){
println("sum of $a and $b is ${a+b}")
}
fun incrementX():Int{
temp +=9
temp *=temp
println(Pi)
val sz = "temp is $temp"
temp = 10086
println(sz)
val so = "${sz.replace("is","was")},but new is $temp"
println(so)
return temp
}
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
| 13 | HTML | 1 | 5 | f321a2e35b50bb9383729ea56a15866c3c3ab93b | 1,284 | note | Apache License 2.0 |
src/main/kotlin/leetcode/kotlin/array/SortingAlgorithms/EfficientSort/QuickSort.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.array.SortingAlgorithms.EfficientSort
// https://en.wikipedia.org/wiki/Sorting_algorithm#Quicksort
/*
=> Quick Sort (Partition Exchange Sort)
1. Pick an element, called a pivot, from the array.
2. Partitioning: reorder the array so that all elements with values less than the pivot
come before the pivot, while all elements with values greater than the pivot come after
it (equal values can go either way). After this partitioning, the pivot is in its final
position. This is called the partition operation.
3. Recursively apply the above steps to the sub-array of elements with smaller values and
separately to the sub-array of elements with greater values.
-------------------------
| Time | O(nlogn)| worst case O(n^2), though this is rare
| Aux-Space | O(logn) | O(n) in worst case
-------------------------
| In-place | yes | we need auxiliary for stack calls
| Stable | no | Default implementation is not stable
| Online | no |
-------------------------
Highlights:
1. Its based on divide and conquer paradigm.
2. Algorithms efficiency greatly depends on partition scheme used. There are many partition schemes.
Todo :Must Visit https://www.geeksforgeeks.org/quick-sort/
*/
private fun sort(arr: IntArray) {
fun partition(arr: IntArray, lo: Int, hi: Int): Int {
var pivot = arr[hi]
var i = lo
var j = lo
while (j <= hi) {
if (arr[j] < pivot) {
arr[i] = arr[j].also { arr[j] = arr[i] }
i++
}
j++
}
arr[i] = arr[hi].also { arr[hi] = arr[i] }
return i
}
fun quickSort(arr: IntArray, lo: Int, hi: Int) {
if (lo < hi) {
var pi = partition(arr, lo, hi)
quickSort(arr, lo, pi - 1)
quickSort(arr, pi + 1, hi)
}
}
quickSort(arr, 0, arr.lastIndex)
println(arr.toList())
}
fun main() {
var arr = intArrayOf(64, 25, 12, 22, 11)
println(sort(arr))
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 2,034 | kotlinmaster | Apache License 2.0 |
src/Day01.kt | DeltaSonic62 | 572,718,847 | false | {"Kotlin": 8676} | fun getCarriedCals(input: List<String>): List<Int> {
val carriedCals: MutableList<Int> = mutableListOf()
var total = 0
for (str in input) {
if (str.isEmpty() || str.isBlank()) {
carriedCals.add(total)
total = 0
continue
}
total += str.toInt()
}
carriedCals.add(total)
return carriedCals
}
fun main() {
fun part1(input: List<String>): Int {
val carriedCals = getCarriedCals(input)
var max = carriedCals[0]
for (cal in carriedCals) {
if (cal > max) {
max = cal
}
}
return max
}
fun part2(input: List<String>): Int {
val carriedCals = getCarriedCals(input).sortedDescending()
return carriedCals.slice(0..2).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7cdf94ad807933ab4769ce4995a43ed562edac83 | 1,098 | aoc-2022-kt | Apache License 2.0 |
src/Day15.kt | greg-burgoon | 573,074,283 | false | {"Kotlin": 120556} | import java.util.*
fun main() {
class Point (x: Long, y: Long) {
val x = x
val y = y
fun getDistance(other: Point): Long {
return Math.abs(other.x-this.x) + Math.abs(other.y-this.y)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Point
if (x != other.x) return false
if (y != other.y) return false
return true
}
override fun hashCode(): Int {
var result = x.hashCode()
result = 31 * result + y.hashCode()
return result
}
}
fun part1(input: String, rowInQuestion: Long): Long {
val regexX = "x=-?[0-9]+".toRegex()
val regexY = "y=-?[0-9]+".toRegex()
val sensorBeaconList = input.split("\n")
.map { lineString ->
lineString.split(": ").map { coordString ->
var xCoord = regexX.find(coordString)?.value?.removePrefix("x=")?.toLong()!!
var yCoord = regexY.find(coordString)?.value?.removePrefix("y=")?.toLong()!!
Point(xCoord, yCoord)
}.toList()
}
var beaconList = sensorBeaconList.map {
it[1]
}
var sensorDistanceList = sensorBeaconList.map { (sensor, beacon) ->
val distance = sensor.getDistance(beacon)
listOf(sensor, distance)
}
var sensorPoints = sensorDistanceList.map {
it[0] as Point
}
var distanceList = sensorDistanceList.map {
it[1] as Long
}
var maxX = sensorPoints.maxOf {
it.x
}
var minX = sensorPoints.minOf {
it.x
}
var maxDistance = distanceList.max()
maxX = maxX + maxDistance
minX = minX - maxDistance
var count = 0L
for (x in minX .. maxX){
var comparisonPoint = Point(x, rowInQuestion)
var isInRangeOfSensor = false
sensorDistanceList.forEach { (sensor, distance) ->
if (sensor is Point && distance is Long) {
isInRangeOfSensor = isInRangeOfSensor ||
(sensor.getDistance(comparisonPoint) <= distance &&
!beaconList.contains(comparisonPoint))
}
}
if (isInRangeOfSensor) {
count++
}
}
return count
}
fun part2(input: String, minX: Long, maxX: Long, minY: Long, maxY: Long): Long {
val regexX = "x=-?[0-9]+".toRegex()
val regexY = "y=-?[0-9]+".toRegex()
val sensorDistanceList = input.split("\n")
.map { lineString ->
lineString.split(": ").map { coordString ->
var xCoord = regexX.find(coordString)?.value?.removePrefix("x=")?.toLong()!!
var yCoord = regexY.find(coordString)?.value?.removePrefix("y=")?.toLong()!!
Point(xCoord, yCoord)
}.toList()
}.map { (sensor, beacon) ->
val distance = sensor.getDistance(beacon)
listOf(sensor, distance)
}
var rangeMap = mutableMapOf<Long, MutableList<LongRange>>()
for (y in minY .. maxY) {
sensorDistanceList.forEach { (sensor, distance) ->
if (sensor is Point && distance is Long && Math.abs(sensor.y - y) <= distance) {
var length = (distance*2 +1) - (2*Math.abs(sensor.y - y))
var minRange = sensor.x - length/2
var maxRange = sensor.x + length/2
var rangeList = rangeMap.getOrDefault(y, mutableListOf<LongRange>())
rangeList.add(minRange .. maxRange)
rangeMap.put(y, rangeList)
}
}
}
for (y in minY .. maxY) {
var rangeIterator = rangeMap.get(y)!!.sortedBy {
it.first
}.iterator()
var previousRange = rangeIterator.next()
var previousMax = -1L
while (rangeIterator.hasNext()) {
var nextRange = rangeIterator.next()
previousMax = Math.max(previousRange.last, previousMax)
if (previousMax < nextRange.first) {
return ((previousRange.last+1) * 4000000) + y
}
previousRange = nextRange
}
}
return 0 //(deadBeacon.x * 4000000) + deadBeacon.y
}
val testInput = readInput("Day15_test")
val output = part1(testInput, 10)
check(output == 26L)
val outputTwo = part2(testInput, 0, 20, 0, 20)
check(outputTwo == 56000011L)
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 0, 4000000, 0, 4000000))
}
| 0 | Kotlin | 0 | 1 | 74f10b93d3bad72fa0fc276b503bfa9f01ac0e35 | 5,044 | aoc-kotlin | Apache License 2.0 |
kotlin/747. Largest Number At Least Twice of Others .kt | bchadwic | 372,917,249 | false | null | class Solution {
/*
Approach 2: A max heap is not needed given that if the second highest number isn't equal or greater
than the highest, the rest of the lower numbers aren't either. Use a data class to hold three
numbers, two being the first and second max, the last being the index of the first max.
*/
data class MaxValues(var first: Int, var second: Int, var firstIndex: Int){
fun shiftFirst(replacement: Int, replacementIndex: Int){
second = first
first = replacement
firstIndex = replacementIndex
}
fun shiftSecond(replacement: Int) { second = replacement }
}
fun dominantIndex(nums: IntArray): Int {
if(nums.size == 1) return 0
val n0 = nums[0]
val n1 = nums[1]
val mvs = if(n0 > n1) MaxValues(n0, n1, 0) else MaxValues(n1, n0, 1)
for(i in 2..nums.size - 1){
val num = nums[i]
with(mvs){
when {
num >= first -> shiftFirst(num, i)
num >= second -> shiftSecond(num)
}
}
}
return with(mvs){ if (first >= second * 2) firstIndex else -1 }
}
}
/*
Approach 1:
class ValueIndex(val value: Int, val index: Int)
fun dominantIndex(nums: IntArray): Int {
if(nums.size == 1) return 0
val maxheap = PriorityQueue<ValueIndex> { a, b -> b.value - a.value }
for(i in 0..nums.size - 1) {
maxheap.add(ValueIndex(nums[i] * 2, i))
}
return with(maxheap.remove()) {
if(this.value / 2 >= maxheap.peek().value) this.index else -1
}
}
*/
| 1 | Java | 5 | 13 | 29070c0250b7ea3f91db04076c8aff5504a9caec | 1,677 | BoardMasters-Question-Of-The-Day | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ProfitableSchemes.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.MOD
import kotlin.math.min
/**
* 879. Profitable Schemes
* https://leetcode.com/problems/profitable-schemes/
*/
private const val LIMIT = 101
fun interface ProfitableSchemes {
operator fun invoke(n: Int, minProfit: Int, group: IntArray, profits: IntArray): Int
}
/**
* Approach 1: Top-Down Dynamic Programming
*/
class ProfitableSchemesTopDown : ProfitableSchemes {
private val memo = Array(LIMIT) { Array(LIMIT) { IntArray(LIMIT) { -1 } } }
override operator fun invoke(n: Int, minProfit: Int, group: IntArray, profits: IntArray): Int {
return find(0, 0, 0, n, minProfit, group, profits)
}
fun find(pos: Int, count: Int, profit: Int, n: Int, minProfit: Int, group: IntArray, profits: IntArray): Int {
if (pos == group.size) {
// If profit exceeds the minimum required; it's a profitable scheme.
return if (profit >= minProfit) 1 else 0
}
if (memo[pos][count][profit] != -1) {
// Repeated sub-problem, return the stored answer.
return memo[pos][count][profit]
}
// Ways to get a profitable scheme without this crime.
var totalWays = find(pos + 1, count, profit, n, minProfit, group, profits)
if (count + group[pos] <= n) {
// Adding ways to get profitable schemes, including this crime.
totalWays += find(
pos + 1,
count + group[pos],
min(minProfit, profit + profits[pos]),
n,
minProfit,
group,
profits,
)
}
return totalWays % MOD.also { memo[pos][count][profit] = it }
}
}
class ProfitableSchemesBottomUp : ProfitableSchemes {
private val dp = Array(LIMIT) { Array(LIMIT) { IntArray(LIMIT) } }
override operator fun invoke(n: Int, minProfit: Int, group: IntArray, profits: IntArray): Int {
// Initializing the base case.
for (count in 0..n) {
dp[group.size][count][minProfit] = 1
}
for (index in group.size - 1 downTo 0) {
for (count in 0..n) {
for (profit in 0..minProfit) {
// Ways to get a profitable scheme without this crime.
dp[index][count][profit] = dp[index + 1][count][profit]
if (count + group[index] <= n) {
// Adding ways to get profitable schemes, including this crime.
val minIndex = min(minProfit, profit + profits[index])
val local = dp[index][count][profit].plus(dp[index + 1][count + group[index]][minIndex])
dp[index][count][profit] = local % MOD
}
}
}
}
return dp[0][0][0]
}
}
class ProfitableSchemesDP : ProfitableSchemes {
override operator fun invoke(n: Int, minProfit: Int, group: IntArray, profits: IntArray): Int {
val dp = Array(n + 1) { IntArray(minProfit + 1) }
dp[0][0] = 1
for (i in group.indices) {
val need = group[i]
val money = profits[i]
for (a in (need..n).reversed()) {
var tmp = dp[a][minProfit]
for (b in maxOf(0, minProfit - money)..minProfit)
tmp = (tmp + dp[a - need][b]) % MOD
dp[a][minProfit] = tmp
for (b in (money until minProfit).reversed())
dp[a][b] = (dp[a][b] + dp[a - need][b - money]) % MOD
}
}
var res = 0
for (i in 0..n)
res = (res + dp[i][minProfit]) % MOD
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,353 | kotlab | Apache License 2.0 |
src/examples/kotlin/org/holo/kGrammar/LL1Example.kt | Holo314 | 343,512,707 | false | null | package org.holo.kGrammar
import org.holo.kGrammar.parsers.parse
import kotlin.test.assertEquals
/**
* Defining the [org.holo.kGrammar.Symbol.NonTerminal] symbols
*/
val start = Symbol.NonTerminal.Start
val addExp = Symbol.NonTerminal.generate()
val startMult = Symbol.NonTerminal.generate()
val multExp = Symbol.NonTerminal.generate()
val expression = Symbol.NonTerminal.generate()
/**
* Defining the [org.holo.kGrammar.Symbol.Terminal] symbols
*/
val plus = Symbol.Terminal.from("\\+".toRegex())
val mult = Symbol.Terminal.from("\\*".toRegex())
val lb = Symbol.Terminal.from("\\(".toRegex())
val rb = Symbol.Terminal.from("\\)".toRegex())
val id = Symbol.Terminal.from("-?([1-9][0-9]*|0)(\\.[0-9]+)?".toRegex())
/**
* [Λ] represent the empty sequence
*/
val Λ = listOf(Symbol.Terminal.Empty)
/**
* Defining the rules.
*
* This rules define the grammar of a mathematical expression containing `+, *, [Double], (, )`.
* The rules will be correctly parse any legal expression of those symbols, it will respect the precedence of `+`, `*` and `()`.
* The parsing result will be *right associative*, so [Double] * [Double] * [Double] will be [Double] * ([Double] * [Double])
*/
val rules = Rule.rulesSet {
+(start to listOf(startMult, addExp))
+(addExp to Λ)
+(addExp to listOf(plus, start))
+(startMult to listOf(expression, multExp))
+(multExp to Λ)
+(multExp to listOf(mult, startMult))
+(expression to listOf(lb, start, rb))
+(expression to listOf(id))
}
/**
* The AST class, after parsing the input into [ParseTree] (see [parse]), we will manually transform our [ParseTree] into this object(see [parseTreeToAST])
*/
sealed class AST {
data class Number(val value: Double) : AST()
data class AddExp(val left: AST, val right: AST) : AST()
data class MulExp(val left: AST, val right: AST) : AST()
}
/**
* Transform any [ParseTreeNonEmpty] (see [ParseTree.removeEmpty] if you have [ParseTree] instead) into [AST]
*/
fun parseTreeToAST(pTree: ParseTreeNonEmpty.NonTerminalNode): AST {
return when (pTree.symbol) {
start -> startToAST(pTree)
addExp -> addExpToAST(pTree)
startMult -> startMultToAST(pTree)
multExp -> multExpToAST(pTree)
expression -> expToAst(pTree)
else -> error("Should not have reached here")
}
}
/**
* The function that evaluate [AST] into concrete result(in this case, a [Double])
*/
fun eval(ast: AST): Double = when (ast) {
is AST.Number -> ast.value
is AST.AddExp -> eval(ast.left) + eval(ast.right)
is AST.MulExp -> eval(ast.left) * eval(ast.right)
}
/**
* A complete process of evaluating an input
*/
fun main() {
val tokens = tokenize("1+2*3+1.5+2*(2+1)*2+1", setOf(plus, mult, lb, rb, id))
val parseTree = parse(tokens, rules).removeEmpty()
val ast = parseTreeToAST(parseTree)
assertEquals(1+2*3+1.5+2*(2+1)*2+1, eval(ast))
}
/**
* The following section is the implementation of how we transform each [ParseTreeNonEmpty.NonTerminalNode] ([start], [addExp], [startMult], [multExp], [expression]) into it's equivalent [AST] node.
*
* Because the library is *not* code generating library, we cannot guarantee exhaustive `when` expression,
* theoretically, one can just put the last case into `else` block([org.holo.kGrammar.ParseTreeNonEmpty.NonTerminalNode] have internal constructor,
* unless someone construct a tree with reflection, you should never reach the else block in the following example),
* but to make the logic clearer, I created a branch for each possible case, and am throwing an [IllegalStateException]
* in the `else` block.
*/
fun startToAST(pTree: ParseTreeNonEmpty.NonTerminalNode): AST =
when (pTree.children.size) {
1 -> parseTreeToAST(pTree.children.first() as ParseTreeNonEmpty.NonTerminalNode)
2 -> AST.AddExp(
parseTreeToAST(pTree.children.first() as ParseTreeNonEmpty.NonTerminalNode),
parseTreeToAST(pTree.children.last() as ParseTreeNonEmpty.NonTerminalNode)
)
else -> error("Nodes of \"Start\" can have only 1 or 2 children")
}
fun addExpToAST(pTree: ParseTreeNonEmpty.NonTerminalNode): AST =
parseTreeToAST(pTree.children.last() as ParseTreeNonEmpty.NonTerminalNode)
fun startMultToAST(pTree: ParseTreeNonEmpty.NonTerminalNode): AST =
when (pTree.children.size) {
1 -> parseTreeToAST(pTree.children.first() as ParseTreeNonEmpty.NonTerminalNode)
2 -> AST.MulExp(
parseTreeToAST(pTree.children.first() as ParseTreeNonEmpty.NonTerminalNode),
parseTreeToAST(pTree.children.last() as ParseTreeNonEmpty.NonTerminalNode)
)
else -> error("Nodes of \"startMult\" can have only 1 or 2 children")
}
fun multExpToAST(pTree: ParseTreeNonEmpty.NonTerminalNode): AST =
parseTreeToAST(pTree.children.last() as ParseTreeNonEmpty.NonTerminalNode)
fun expToAst(pTree: ParseTreeNonEmpty.NonTerminalNode): AST =
when (pTree.children.size) {
1 -> AST.Number((pTree.children.first() as ParseTreeNonEmpty.TerminalNode).token.value.toDouble())
3 -> parseTreeToAST(pTree.children.drop(1).first() as ParseTreeNonEmpty.NonTerminalNode)
else -> error("Nodes of \"expression\" can have only 1 or 3 children")
}
| 0 | Kotlin | 0 | 0 | af5568fc4d1a56d98a93a645ca0ffbbf966a450b | 5,278 | KGrammar | MIT License |
src/main/kotlin/com/frankandrobot/rapier/util/combinations.kt | frankandrobot | 62,833,944 | false | null | /*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.frankandrobot.rapier.util
/**
* Ex: a = [1, 2], b = [3, 4]
* result => [(1, 3), (1, 4), (2, 3), (2, 4)]
* where (x,y) = pair(x,y)
*
* Ex2: x = [a], y = [c, d]
* result => [(a, c), (a, d)]
*
* Creates all the combinations of the items in the lists.
*/
fun <In,Out> combinations(
a : Collection<out In> = listOf(),
b : Collection<out In> = listOf(),
pair: (In, In) -> Out
) : List<Out> {
return a.flatMap { aItem -> b.map { bItem -> pair(aItem, bItem) } }
}
/**
* Ex: list = [[x,y], [1,2], [3,4]]
* result => [[x,1,3], [x,1,4], [x,2,3], [x,2,4], [y,1,3], [y,1,4], ...]
*
* @param list - the input
* @param _curIndex - used by tail recursion, no need to set
* @param _acc - used by tail recursion, no need to set
*/
fun <In> combinations(
list : List<List<In>>,
_curIndex: Int = 0,
_acc: List<In> = listOf()
) : List<List<In>> {
val iterator = list.listIterator(_curIndex)
if (iterator.hasNext()) {
return iterator.next().flatMap{ combinations(list, _curIndex + 1, _acc + it) }
}
else {
return listOf(_acc)
}
}
/**
* Ex: x = [[a], [1]], y = [[c,d], [3,4]]
* result => [(a,c), (1,3)], [(a,d), (1,3)], [(a,c), (1,4)], [(a,d), (1,4)]
* where (x,y) = pair(x,y)
*/
fun <In,Out> combinations2(
x: List<Collection<out In>>,
y: List<Collection<out In>>,
pair: (In, In) -> Out
) : List<List<Out>> {
val iter = y.iterator()
val result = x.map { aItems -> combinations(aItems, iter.next(), pair) }
return combinations(result)
}
| 1 | Kotlin | 1 | 1 | ddbc0dab60ca595e63a701e2f8cd6694ff009adc | 2,134 | rapier | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day16/Day16.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day16
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInput
object Day16 : Day {
override var input = readInput(16)
override fun part1() = PacketFactory(input).build().subVersions.sum()
override fun part2() = PacketFactory(input).build().value
sealed interface Packet {
val version: Int
val value: Long
val subVersions: List<Int>
}
class Literal(override val version: Int, override val value: Long) : Packet {
override val subVersions: List<Int> = listOf(version)
}
class Operator(override val version: Int, override val value: Long, packets: List<Packet>) : Packet {
companion object {
fun from(version: Int, typeId: Int, packets: List<Packet>) = when (typeId) {
0 -> packets.sumOf { it.value }
1 -> packets.fold(1L) { a, c -> a * c.value }
2 -> packets.minOf { it.value }
3 -> packets.maxOf { it.value }
4 -> error("Type 4 is restricted to value literals")
5 -> packets.compare { first, second -> first > second }
6 -> packets.compare { first, second -> first < second }
7 -> packets.compare { first, second -> first == second }
else -> error("Unsupported operator type '$typeId'")
}.run { Operator(version, this, packets) }
private fun List<Packet>.compare(comparison: (Long, Long) -> Boolean): Long {
return take(2).map { it.value }.let { (first, last) -> if (comparison(first, last)) 1 else 0 }
}
}
override val subVersions = packets.flatMap { it.subVersions } + listOf(version)
}
class PacketFactory(raw: String) {
var unprocessed = raw.map { it.toString().toInt(16) }.joinToString("") { it.toString(2).padStart(4, '0') }
fun build(): Packet {
val version = process(3).toInt(2)
val typeId = process(3).toInt(2)
return if (typeId == 4) Literal(version, literalValue()) else Operator.from(version, typeId, subPackets())
}
private fun process(bits: Int) = unprocessed.take(bits).apply { unprocessed = unprocessed.drop(bits) }
private fun literalValue(): Long {
return buildString {
while (unprocessed.first() == '1') {
append(process(5).drop(1))
}
append(process(5).drop(1))
}.toLong(2)
}
private fun subPackets(): List<Packet> {
return when (val id = process(1).single()) {
'0' -> buildList {
val length = process(15).toLong(2)
val end = unprocessed.length - length
while (unprocessed.length > end) {
add(build())
}
}
'1' -> buildList { repeat((1..process(11).toLong(2)).count()) { add(build()) } }
else -> error("Length type ID should be either '0' or '1' not '$id'")
}
}
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 3,175 | aoc2021 | MIT License |
src/main/java/Day2.kt | mattyb678 | 319,195,903 | false | null | class Day2 : Day {
override fun asInt(): Int = 2
override fun part1InputName(): String = "day2"
override fun part1(input: List<String>): String {
return input.map { it.split(":") }
.map { it.map { s -> s.trim() } }
.filter { validPasswordPart1(it[0], it[1]) }
.count()
.toString()
}
private fun validPasswordPart1(rule: String, password: String): Boolean {
val letterAndLimits = rule.split(" ").map { it.trim() }
val limits = letterAndLimits[0]
.split("-")
.map { it.toInt() }
.chunked(2)
.map { it[0]..it[1] }
.first()
val letter = letterAndLimits[1][0]
val times = password.filter { it == letter }.count()
return times in limits
}
override fun part2InputName(): String = "day2"
override fun part2(input: List<String>): String {
return input.map { it.split(":") }
.map { it.map { s -> s.trim() } }
.filter { validPasswordPart2(it[0], it[1]) }
.count()
.toString()
}
private fun validPasswordPart2(rule: String, password: String): Boolean {
val letterAndPositions = rule.split(" ").map { it.trim() }
val positions = letterAndPositions[0]
.split("-")
.map { it.toInt() }
.chunked(2)
.map { it[0] to it[1] }
.first()
val letter = letterAndPositions[1][0]
val matchCount = password
.filterIndexed { idx, _ -> idx == positions.first - 1 || idx == positions.second - 1 }
.filter { it == letter }
.count()
return matchCount == 1
}
} | 0 | Kotlin | 0 | 1 | f677d61cfd88e18710aafe6038d8d59640448fb3 | 1,724 | aoc-2020 | MIT License |
src/Day09.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | import kotlin.math.abs
fun main() {
fun part1(input: List<Mvmt>) {
val head = Point(0, 0)
val tail = Point(0, 0)
val positions = mutableSetOf(tail.copy())
input.forEach { mvmt ->
head.move(mvmt)
if (!tail.isAdjecent(head)) {
tail.catchUp(head, mvmt)
positions.add(tail.copy())
}
}
positions.size.log("part1")
}
fun part2(input: List<Mvmt>) {
val knots = (0..9).map { Point(0,0) }
val positions = mutableSetOf(Point(0,0))
// knots.plot(15, 15)
input.forEach { mvmt ->
knots[0].move(mvmt)
knots.drop(1).forEachIndexed { i, p ->
if (!p.isAdjecent(knots[i])) {
p.catchUp(knots[i], mvmt)
// knots.plot(35, 35)
}
}
// knots.plot(35, 35, positions)
positions.add(knots.last().copy())
}
positions.size.log("part2")
}
val input = downloadAndReadInput("Day09").filter { it.isNotBlank() }.flatMap { Mvmt.parse(it) }
part1(input)
part2(input)
}
fun List<Point>.plot(h : Int, w : Int, tailPositions: Collection<Point> = emptyList()) {
(-(h/2)..(h/2)).reversed().forEach { y ->
(-(w/2)..(w/2)).forEach { x ->
val visited = tailPositions.contains(Point(x,y))
val p = indexOfFirst { it.x == x && it.y == y }.let {
when (it) {
-1 -> if (y == 0 && x == 0) "s" else if (visited) "#" else "."
0 -> "H"
size-1 -> "T"
else -> (it).toString()
}
}
print(p)
}
println()
}
}
sealed interface Mvmt {
companion object {
fun parse(s: String): List<Mvmt> {
return s.split(" ").let { (m, t) ->
(0 until t.toInt()).map {
when (m) {
"L" -> Left
"R" -> Right
"U" -> Up
"D" -> Down
else -> error("unknown")
}
}
}
}
}
}
object Up : Mvmt
object Down : Mvmt
object Left : Mvmt
object Right : Mvmt
data class Point(var x: Int, var y: Int) {
fun isAdjecent(p: Point): Boolean {
return abs(x - p.x) < 2 && abs(y - p.y) < 2
}
fun move(mvmt: Mvmt) {
when (mvmt) {
is Down -> y -= 1
is Left -> x -= 1
is Right -> x += 1
is Up -> y += 1
}
}
fun catchUp(p: Point, lastMvmt: Mvmt) {
when (lastMvmt) {
is Down -> {
if (y != p.y) {
if (y < p.y) {
move(Up)
} else {
move(lastMvmt)
}
}
if (x < p.x) {
move(Right)
} else if (x > p.x) {
move(Left)
}
}
is Left -> {
if (x != p.x) {
if (x < p.x) {
move(Right)
} else {
move(lastMvmt)
}
}
if (y < p.y) {
move(Up)
} else if (y > p.y) {
move(Down)
}
}
is Right -> {
if (x != p.x) {
if (x > p.x) {
move(Left)
} else {
move(lastMvmt)
}
}
if (y < p.y) {
move(Up)
} else if (y > p.y) {
move(Down)
}
}
is Up -> {
if (y != p.y) {
if (y > p.y) {
move(Down)
} else {
move(lastMvmt)
}
}
if (x < p.x) {
move(Right)
} else if (x > p.x) {
move(Left)
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 4,326 | advent-of-code-2022 | Apache License 2.0 |
kotlin/0785-is-graph-bipartite.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} | /*
* BFS
*/
class Solution {
fun isBipartite(graph: Array<IntArray>): Boolean {
if (graph.isEmpty()) return true
val nodeColorMap = mutableMapOf<Int, Color>()
fun bfs(startNode: Int): Boolean {
// if the node is already colored, return true
if (startNode in nodeColorMap.keys) return true
nodeColorMap[startNode] = Color.RED
val queue = (LinkedList<Int>() as Queue<Int>).apply { add(startNode) }
while (queue.isNotEmpty()) {
val currentNode = queue.remove()
val colorOfCurrentNode = nodeColorMap.getValue(currentNode)
for (adjacentNode in graph[currentNode]) {
if (adjacentNode in nodeColorMap.keys) {
val colorOfAdjacentNode = nodeColorMap.getValue(adjacentNode)
if (colorOfAdjacentNode == colorOfCurrentNode) return false
continue
}
nodeColorMap[adjacentNode] = colorOfCurrentNode.inverse
queue.add(adjacentNode)
}
}
return true
}
for (node in graph.indices) {
if (!bfs(node)) return false
}
return true
}
private enum class Color { RED, GREEN }
private val Color.inverse
get() = when (this) {
Color.RED -> Color.GREEN
Color.GREEN -> Color.RED
}
}
/*
* DFS
*/
class Solution {
fun isBipartite(graph: Array<IntArray>): Boolean {
if (graph.isEmpty()) return true
val nodeColorMap = mutableMapOf<Int, Color>()
fun dfs(node: Int, defaultColor: Color): Boolean {
if (node !in nodeColorMap.keys) nodeColorMap[node] = defaultColor
for (adjacentNode in graph[node]) {
val isEdgeVisited = nodeColorMap[adjacentNode] != null
if (isEdgeVisited) {
val colorOfCurrentNode = nodeColorMap.getValue(node)
val colorOfAdjacentNode = nodeColorMap.getValue(adjacentNode)
if (colorOfAdjacentNode == colorOfCurrentNode) return false
else continue
}
if (!dfs(adjacentNode, defaultColor.inverse)) return false
}
return true
}
for (node in graph.indices) {
if (node in nodeColorMap.keys) continue
if (!dfs(node, Color.RED)) return false
}
return true
}
private enum class Color { RED, GREEN }
private val Color.inverse
get() = when (this) {
Color.RED -> Color.GREEN
Color.GREEN -> Color.RED
}
}
/*
* Union Find
*/
class Solution {
class DSU(val n: Int) {
val parent = IntArray(n) { it }
val rank = IntArray(n) { 1 }
fun find(x: Int): Int {
if (x != parent[x])
parent[x] = find(parent[x])
return parent[x]
}
fun union(x: Int, y: Int) {
val px = find(x)
val py = find(y)
if (rank[px] >= rank[py]) {
parent[py] = px
rank[px] += rank[py]
} else {
parent[px] = py
rank[py] += rank[px]
}
}
}
fun isBipartite(graph: Array<IntArray>): Boolean {
val dsu = DSU(graph.size)
for (i in 0 until graph.size) {
for (j in graph[i]) {
if (dsu.find(i) == dsu.find(j))
return false
dsu.union(graph[i][0], j)
}
}
return true
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 3,699 | leetcode | MIT License |
src/main/java/im/joshua/leetcode/topic/LeetCode_5.kt | JoshuaYin | 239,452,799 | false | {"Java": 13766, "Kotlin": 10698} | package im.joshua.leetcode.topic
/**
* @description:
* @author: joshua
* @E-mail: <EMAIL>
* @date: 2020/8/5 16:10
*/
fun main(args: Array<String>) {
val topic = LeetCode_5("abacabbacad")
println(topic.solve())
}
class LeetCode_5(val s: String) : LeetCodeTopic<String>() {
override fun formatParams() {
params.addProperty("s", s)
}
var max = ""
override fun solution(): String {
val len = s.length
if (len < 2)
return s
val dp: Array<BooleanArray> = Array(len) { BooleanArray(len) { false } }
for (i in 0 until len) {
dp[i][i] = true
}
val charArr = s.toCharArray()
var maxLen = 1
var start = 0
for (j in 1 until len) {
// 只有下面这一行和「参考代码 2」不同,i 正着写、倒过来写都行,因为子串都有参考值
for (i in (j - 1) downTo 0) {
println("[$i]:${charArr[i]} [$j]:${charArr[j]}")
if (charArr[i] == charArr[j]) {
if (j - i < 3) {
dp[i][j] = true
} else {
println("else-> [${i + 1}]:${charArr[i + 1]} [${j - 1}]:${charArr[j - 1]}")
dp[i][j] = dp[i + 1][j - 1]
}
} else {
dp[i][j] = false
}
println("dp[$i][$j]:${dp[i][j]}")
// 只要 dp[i][j] == true 成立,就表示子串 s[i, j] 是回文,此时记录回文长度和起始位置
if (dp[i][j]) {
val curLen = j - i + 1
if (curLen > maxLen) {
maxLen = curLen
start = i
}
}
}
println("-------------------------------------")
}
for (i in 0 until len) {
var sb = StringBuilder()
for (j in 0 until len) {
sb.append("[$i][$j]:${dp[i][j]}\t")
}
println(sb.toString())
}
return s.substring(start, start + maxLen)
}
private fun pickMax(old: String, new: String): String {
if (old.length > new.length)
return old
return new
}
private fun subFunc(str: String): String? {
val len = str.length
val start = str[0]
// println("[start]: $start\t[leng]: $len\t[sub]: $str")
var left = 0
var right = len - 1
while (left < right) {
// println("sub[$i]:${str[i]} sub[${len - 1 - i}]:${str[len - 1 - i]}")
if (str[left] != str[right]) {
return if (str.count { it == start } > 2) {
val sub = str.substring(0, str.substring(0, len - 1).lastIndexOf(start) + 1)
return if (max.isEmpty() || sub.length > max.length)
subFunc(sub)
else null
} else {
null
}
}
left++
right--
}
return str
}
} | 0 | Java | 0 | 0 | 03f5672551189bfd3fc396f1b34a30fb79749f5a | 3,171 | leet-code-java | Apache License 2.0 |
src/Day06.kt | GarrettShorr | 571,769,671 | false | {"Kotlin": 82669} | fun main() {
fun part1(input: List<String>): Int {
println(input)
val potentialMarkers = input[0].windowed(4).map { it.windowed(1).sorted() }
println(potentialMarkers)
for(i in potentialMarkers.indices) {
if(potentialMarkers[i][0] != potentialMarkers[i][1] &&
potentialMarkers[i][1] != potentialMarkers[i][2] &&
potentialMarkers[i][2] != potentialMarkers[i][3]) {
return i + 4
}
}
return 0
}
fun part2(input: List<String>): Int {
println(input)
val potentialMarkers = input[0].windowed(14).map { it.windowed(1) }
println(potentialMarkers)
for(i in potentialMarkers.indices) {
val markerSet = mutableSetOf<String>()
markerSet.addAll(potentialMarkers[i])
if(markerSet.size == 14) { return i + 14 }
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
// println(part1(testInput))
println(part2(testInput))
val input = readInput("Day06")
// output(part1(input))
output(part2(input))
}
| 0 | Kotlin | 0 | 0 | 391336623968f210a19797b44d027b05f31484b5 | 1,082 | AdventOfCode2022 | Apache License 2.0 |
src/aoc_2023/Day01.kt | jakob-lj | 573,335,157 | false | {"Kotlin": 38689} | package aoc_2023
class Day01 {
val testInput = """
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
""".trimIndent()
val realInput = """""".trimIndent()
val textToDigits = 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 String.addFirstAndLastLetter(textualDigit: String): String {
return "${textualDigit[0]}$this${textualDigit[textualDigit.length - 1]}"
}
fun textToDigit(line: String): String {
var mutableLine = line
for (textualDigit in textToDigits.keys) {
mutableLine =
mutableLine.replace(
textualDigit,
textToDigits[textualDigit].toString().addFirstAndLastLetter(textualDigit)
)
}
return mutableLine.filter { it.isDigit() }
}
enum class Part {
ONE,
TWO
}
fun part1(part: Part): Int {
val data = realInput
val linesWithNumbers = data.split("\n")
.map { row -> if (part == Part.ONE) row.filter { it.isDigit() } else textToDigit(row) }
val result = linesWithNumbers.map {
"${it[0]}${
it[it.length - 1]
}".toInt()
}
return result.sum()
}
}
fun main() {
println(Day01().part1(Day01.Part.TWO))
}
| 0 | Kotlin | 0 | 0 | 3a7212dff9ef0644d9dce178e7cc9c3b4992c1ab | 1,520 | advent_of_code | Apache License 2.0 |
src/main/kotlin/day03/Day03.kt | tiefenauer | 727,712,214 | false | {"Kotlin": 11843} | /**
* You and the Elf eventually reach a gondola lift station; he says the gondola lift will take you up to the water source, but this is as far as he can bring you. You go inside.
*
* It doesn't take long to find the gondolas, but there seems to be a problem: they're not moving.
*
* "Aaah!"
*
* You turn around to see a slightly-greasy Elf with a wrench and a look of surprise. "Sorry, I wasn't expecting anyone! The gondola lift isn't working right now; it'll still be a while before I can fix it." You offer to help.
*
* The engineer explains that an engine part seems to be missing from the engine, but nobody can figure out which one. If you can add up all the part numbers in the engine schematic, it should be easy to work out which part is missing.
*
* The engine schematic (your puzzle input) consists of a visual representation of the engine. There are lots of numbers and symbols you don't really understand, but apparently any number adjacent to a symbol, even diagonally, is a "part number" and should be included in your sum. (Periods (.) do not count as a symbol.)
*
* Here is an example engine schematic:
*
* 467..114..
* ...*......
* ..35..633.
* ......#...
* 617*......
* .....+.58.
* ..592.....
* ......755.
* ...$.*....
* .664.598..
* In this schematic, two numbers are not part numbers because they are not adjacent to a symbol: 114 (top right) and 58 (middle right). Every other number is adjacent to a symbol and so is a part number; their sum is 4361.
*
* Of course, the actual engine schematic is much larger. What is the sum of all of the part numbers in the engine schematic?
*
*
*/
package day03
import readLines
private val sample = """
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...${'$'}.*....
.664.598..
""".trimIndent().lines()
fun main() {
val lines = "day03-1.txt".readLines()
// val part1 = lines.part1()
val part1 = sample.part1()
println(part1)
}
private data class Part(val lineNumber: Int, val lefIndex: Int, val rightIndex: Int, val partNumber: String)
private fun List<String>.part1() {
val parts = mapIndexed { lineNumber, line -> line.getParts(lineNumber) }
println(parts)
}
private fun String.getParts(lineNumber: Int): List<Part> {
val partNumbers = split("\\D".toRegex()).filter { it.isNotBlank() }
return partNumbers.map { partNumber ->
val leftIndex = indexOf(partNumber)
val rightIndex = indexOf(partNumber) + partNumber.length
Part(lineNumber, leftIndex, rightIndex, partNumber)
}
} | 0 | Kotlin | 0 | 0 | ffa90fbdaa779cfff956fab614c819274b793d04 | 2,576 | adventofcode-2023 | MIT License |
src/main/java/com/ncorti/aoc2021/Exercise16.kt | cortinico | 433,486,684 | false | {"Kotlin": 36975} | package com.ncorti.aoc2021
object Exercise16 {
private fun getInput() =
getInputAsTest("16") {
toCharArray().joinToString("") {
when (it) {
'0' -> "0000"
'1' -> "0001"
'2' -> "0010"
'3' -> "0011"
'4' -> "0100"
'5' -> "0101"
'6' -> "0110"
'7' -> "0111"
'8' -> "1000"
'9' -> "1001"
'A' -> "1010"
'B' -> "1011"
'C' -> "1100"
'D' -> "1101"
'E' -> "1110"
else -> "1111"
}
}
}
private fun parsePacket(chars: CharArray, i: Int = 0): Triple<Int, Int, Long> {
val version = (i..i + 2).map { chars[it] }.joinToString("").toInt(2)
val typeId = (i + 3..i + 5).map { chars[it] }.joinToString("").toInt(2)
val (nexti, partialVersion, value) =
if (typeId == 4) {
parsePacketLiteral(chars, i + 6)
} else {
parsePacketOperator(chars, i + 6, typeId)
}
return Triple(nexti, version + partialVersion, value)
}
private fun parsePacketLiteral(chars: CharArray, i: Int): Triple<Int, Int, Long> {
var nexti = i
val number = mutableListOf<Char>()
while (chars[nexti] == '1') {
(1..4).onEach { number.add(chars[nexti + it]) }
nexti += 5
}
(1..4).onEach { number.add(chars[nexti + it]) }
nexti += 5
return Triple(nexti, 0, number.joinToString("").toLong(2))
}
private fun parsePacketOperator(
chars: CharArray,
starti: Int,
typeId: Int
): Triple<Int, Int, Long> {
var i = starti
var sum = 0
val partialResults = mutableListOf<Long>()
if (chars[i] == '0') {
val length = (i + 1..i + 15).map { chars[it] }.joinToString("").toInt(2)
i += 16
val target = i + length
while (i < target) {
val (nexti, partialVersion, partialResult) = parsePacket(chars, i)
i = nexti
sum += partialVersion
partialResults += partialResult
}
} else {
val packets = (i + 1..i + 11).map { chars[it] }.joinToString("").toInt(2)
i += 12
repeat(packets) {
val (nexti, partialVersion, partialResult) = parsePacket(chars, i)
i = nexti
sum += partialVersion
partialResults += partialResult
}
}
val computation =
when (typeId) {
0 -> partialResults.sum()
1 -> partialResults.fold(1L) { next, acc -> next * acc }
2 -> partialResults.minOrNull()!!
3 -> partialResults.maxOrNull()!!
5 -> if (partialResults[0] > partialResults[1]) 1L else 0L
6 -> if (partialResults[0] < partialResults[1]) 1L else 0L
else -> if (partialResults[0] == partialResults[1]) 1L else 0L
}
return Triple(i, sum, computation)
}
fun part1() = parsePacket(getInput().toCharArray(), 0).second
fun part2() = parsePacket(getInput().toCharArray(), 0).third
}
fun main() {
println(Exercise16.part1())
println(Exercise16.part2())
}
| 0 | Kotlin | 0 | 4 | af3df72d31b74857201c85f923a96f563c450996 | 3,522 | adventofcode-2021 | MIT License |
src/main/kotlin/g2101_2200/s2131_longest_palindrome_by_concatenating_two_letter_words/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2101_2200.s2131_longest_palindrome_by_concatenating_two_letter_words
// #Medium #Array #String #Hash_Table #Greedy #Counting #Level_2_Day_5_Greedy
// #2023_06_25_Time_607_ms_(90.00%)_Space_55.2_MB_(100.00%)
class Solution {
fun longestPalindrome(words: Array<String>): Int {
val counter: MutableMap<String, Int> = HashMap()
for (word in words) {
counter[word] = counter.getOrDefault(word, 0) + 1
}
var pairPalindrome = 0
var selfPalindrome = 0
for ((key, count1) in counter) {
if (isPalindrome(key)) {
selfPalindrome += if (count1 % 2 == 1 && selfPalindrome % 2 == 0) {
count1
} else {
count1 - count1 % 2
}
} else {
val palindrome = palindrome(key)
val count = counter[palindrome]
if (count != null) {
pairPalindrome += Math.min(count, count1)
}
}
}
return 2 * (selfPalindrome + pairPalindrome)
}
private fun isPalindrome(word: String): Boolean {
return word[1] == word[0]
}
private fun palindrome(word: String): String {
return java.lang.String.valueOf(charArrayOf(word[1], word[0]))
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,327 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/g1201_1300/s1278_palindrome_partitioning_iii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1201_1300.s1278_palindrome_partitioning_iii
// #Hard #String #Dynamic_Programming #2023_06_08_Time_137_ms_(100.00%)_Space_35.4_MB_(50.00%)
class Solution {
fun palindromePartition(s: String, k: Int): Int {
val n = s.length
val pal = Array(n + 1) { IntArray(n + 1) }
fillPal(s, n, pal)
val dp = Array(n + 1) { IntArray(k + 1) }
for (row in dp) {
row.fill(-1)
}
return calculateMinCost(s, 0, n, k, pal, dp)
}
private fun calculateMinCost(
s: String,
index: Int,
n: Int,
k: Int,
pal: Array<IntArray>,
dp: Array<IntArray>
): Int {
if (index == n) {
return n
}
if (k == 1) {
return pal[index][n - 1]
}
if (dp[index][k] != -1) {
return dp[index][k]
}
var ans = Int.MAX_VALUE
for (i in index until n) {
ans = Math.min(ans, pal[index][i] + calculateMinCost(s, i + 1, n, k - 1, pal, dp))
}
dp[index][k] = ans
return ans
}
private fun fillPal(s: String, n: Int, pal: Array<IntArray>) {
for (gap in 0 until n) {
var i = 0
var j = gap
while (j < n) {
if (gap == 0) {
pal[i][i] = 0
} else if (gap == 1) {
if (s[i] == s[i + 1]) {
pal[i][i + 1] = 0
} else {
pal[i][i + 1] = 1
}
} else {
if (s[i] == s[j]) {
pal[i][j] = pal[i + 1][j - 1]
} else {
pal[i][j] = pal[i + 1][j - 1] + 1
}
}
i++
j++
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,874 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/io/string/MultiplyStrings.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.string
import io.utils.runTests
// https://leetcode.com/problems/multiply-strings/
class MultiplyStrings {
fun execute(input0: String, input1: String): String = input0 * input1
fun multiply(input0: String, input1: String): String? {
val map = IntArray(input0.length + input1.length)
for (i in input0.lastIndex downTo 0) {
for (j in input1.lastIndex downTo 0) {
val mul = input0[i].toInteger() * input1[j].toInteger()
val p1 = i + j
val p2 = i + j + 1
val sum = mul + map[p2]
map[p1] += sum / 10
map[p2] = sum.rem(10)
}
}
return map.fold(StringBuilder()) { acc, value ->
acc.apply { if (isNotEmpty() || value != 0) append(value) }
}.let { if (it.isEmpty()) "0" else it.toString() }
}
}
private fun Char.toInteger() = this - '0'
operator fun String.times(another: String): String {
fun multiply(anotherIndex: Int): String {
var accumulator = 0
val result = StringBuilder()
repeat(another.lastIndex - anotherIndex) { result.append('0') }
val multiply = another[anotherIndex].toInteger()
(this.lastIndex downTo 0).forEach { index ->
val sum = this[index].toInteger() * multiply + accumulator
result.append(sum.rem(10))
accumulator = sum / 10
}
if (accumulator > 0)
result.append(accumulator)
return result.reverse().toString()
}
if (this.all { it == '0' } || another.all { it == '0' }) return "0"
var result: String? = null
(another.lastIndex downTo 0).forEach { index ->
if (another[index].toInteger() != 0) {
val multiply = multiply(index)
result = result?.let { it `+` multiply } ?: multiply
}
}
return result ?: "0"
}
@Suppress("FunctionName")
infix fun String.`+`(another: String): String {
if (another.isEmpty()) return this
if (this.isEmpty()) return another
var index = this.lastIndex
var anotherIndex = another.lastIndex
val result = StringBuilder()
var accumulator = 0
while (index >= 0 && anotherIndex >= 0) {
val first = this[index].toInteger()
val second = another[anotherIndex].toInteger()
val sum = first + second + accumulator
result.append(sum.rem(10))
accumulator = sum / 10
index--
anotherIndex--
}
if (index >= 0 || anotherIndex >= 0) {
while (index >= 0) {
val first = this[index].toInteger()
val sum = first + accumulator
result.append(sum.rem(10))
accumulator = sum / 10
index--
}
while (anotherIndex >= 0) {
val first = another[anotherIndex].toInteger()
val sum = first + accumulator
result.append(sum.rem(10))
accumulator = sum / 10
anotherIndex--
}
}
if (accumulator != 0)
result.append(accumulator)
return result.reverse().toString()
}
fun main() {
runTests(listOf(
Triple("123", "2", "246"),
Triple("9", "9", "81"),
Triple("10", "10", "100"),
Triple("123", "456", "56088"),
Triple("52", "0", "0"),
Triple("0", "52", "0")
)) { (input0, input1, value) -> value to MultiplyStrings().multiply(input0, input1) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 3,110 | coding | MIT License |
src/main/kotlin/days/aoc2023/Day8.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2023
import days.Day
import util.lcm
class Day8 : Day(2023, 8) {
override fun partOne(): Any {
return calculatePartOne(inputList)
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
fun calculatePartOne(input: List<String>): Int {
val directions = Directions(input[0])
val destinations = input.drop(2).map {
Regex("(\\w+) = \\((\\w+), (\\w+)\\)").matchEntire(it)?.destructured?.let { (source, left, right) ->
source to Pair(left, right)
}
}.associate {
it?.first to it?.second
}
var current = "AAA"
var count = 0
val iterator = directions.nextDirection.iterator()
while (current != "ZZZ") {
current = if (iterator.next() == 'L')
destinations[current]!!.first
else
destinations[current]!!.second
count++
}
return count
}
fun calculatePartTwo(input: List<String>): Long {
val destinations = input.drop(2).map {
Regex("(\\w+) = \\((\\w+), (\\w+)\\)").matchEntire(it)?.destructured?.let { (source, left, right) ->
source to Pair(left, right)
}
}.associate {
it?.first!! to it.second
}
return destinations.filter { it.key.endsWith('A') }.map { distanceToFirstZ(it.key!!, Directions(input[0]).nextDirection.iterator(), destinations) }.lcm()
}
private fun distanceToFirstZ(start: String, directions: Iterator<Char>, destinations: Map<String,Pair<String,String>>): Int {
var current = start
var count = 0
do {
current = if (directions.next() == 'L') destinations[current]!!.first else destinations[current]!!.second
count++
} while (!current.endsWith('Z'))
return count
}
internal class Directions(private val directionList: String) {
val nextDirection = sequence {
do {
directionList.forEach { yield(it) }
} while (true)
}
}
}
| 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 2,131 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
aoc2016/src/main/kotlin/io/github/ajoz/aoc16/Day1.kt | ajoz | 116,427,939 | false | null | package io.github.ajoz.aoc16
import io.github.ajoz.sequences.firstRepeated
import io.github.ajoz.sequences.scan
/**
* Day 1: No Time for a Taxicab
*
* -------------------- Part 1 -----------------------
*
* You're airdropped near Easter Bunny Headquarters in a city somewhere. "Near", unfortunately, is as close as you can get
* - the instructions on the Easter Bunny Recruiting Document the Elves intercepted start here, and nobody had time to work
* them out further.
*
* The Document indicates that you should start at the given coordinates (where you just landed) and face North. Then,
* follow the provided sequence: either turn left (L) or right (R) 90 degrees, then walk forward the given number of
* blocks, ending at a new intersection.
*
* There's no time to follow such ridiculous instructions on foot, though, so you take a moment and work out the
* destination. Given that you can only walk on the street grid of the city, how far is the shortest path to the
* destination?
*
* http://adventofcode.com/2016/day/1
*/
/**
* Describes all possible directions that we can take in a taxi cab geometry.
*/
private enum class Direction {
NORTH,
EAST,
WEST,
SOUTH
}
/**
* Describes a single Instruction in terms of direction instead of terms of Left or Right turn.
*/
private data class Instruction(val direction: Direction, val distance: Int)
/**
* Allows to generate a next [Instruction] from the given instruction string representation. In the puzzle it is stated
* that we can have only two types of instructions: 'R' or 'L'. There is no theoretical limit to the size of the
* instruction string or if the string instructions can be incorrect (wrong letter or more letters, no number of blocks,
* negative number of blocks etc).
*
* After looking at the input data given, I assumed:
* - instruction has only one letter {'R', 'L'}
* - instruction has only a positive number of blocks
* - number of blocks will never reach maximum of integer ;)
*
* To calculate next [Instruction] we need previous [Direction] and the single string instruction. For example let's say
* that the current [Direction] is [Direction.EAST] and string instruction is 'L', then if we are pointing east and we
* look on the left our next direction will be [Direction.NORTH].
*
* I've implemented it as an extension function to the [Instruction] type to allow shorter notation in lambdas.
*/
private fun Instruction.next(instruction: String): Instruction {
val turn = instruction.substring(0, 1)
val numOfBlocks = instruction.substring(1).toInt()
return when (turn) {
"R" -> when (this.direction) {
Direction.NORTH -> Instruction(Direction.EAST, numOfBlocks)
Direction.EAST -> Instruction(Direction.SOUTH, numOfBlocks)
Direction.WEST -> Instruction(Direction.NORTH, numOfBlocks)
Direction.SOUTH -> Instruction(Direction.WEST, numOfBlocks)
}
"L" -> when (this.direction) {
Direction.NORTH -> Instruction(Direction.WEST, numOfBlocks)
Direction.EAST -> Instruction(Direction.NORTH, numOfBlocks)
Direction.WEST -> Instruction(Direction.SOUTH, numOfBlocks)
Direction.SOUTH -> Instruction(Direction.EAST, numOfBlocks)
}
else -> throw IllegalArgumentException("Unknown direction for instruction: $instruction")
}
}
/**
* Class represents calculated coordinates of each step of the route to Bunny HQ.
*/
private data class Coordinates(val x: Int, val y: Int) {
/**
* Calculates the L1 distance (other names include: l1 norm, snake distance, city block distance, Manhattan
* distance, Manhattan length, rectilinear distance).
*
* @param to [Coordinates] to which the L1 distance will be calculated.
*/
fun getL1distance(to: Coordinates) = Math.abs(this.x - to.x) + Math.abs(this.y - to.y)
}
/**
* Allows to generate coordinates of the next step of the route. As we can go only in any of the four directions: North,
* East, West or South then Coordinates of next step will either differ in the x or y -axis to the previous one.
*
* I used a copy method that helps to create a new object based on the given one (also change only set of its
* properties)
*/
private fun Coordinates.next(direction: Direction, distance: Int) = when (direction) {
Direction.NORTH -> this.copy(y = this.y + distance)
Direction.EAST -> this.copy(x = this.x + distance)
Direction.WEST -> this.copy(x = this.x - distance)
Direction.SOUTH -> this.copy(y = this.y - distance)
}
/**
* Allows to generate coordinates of the next step of the route.
*/
private fun Coordinates.next(instruction: Instruction) = next(instruction.direction, instruction.distance)
/**
* Calculates the shortest path from the start [Coordinates] (0, 0) to the [Coordinates] calculated by processing the
* given instructions string.
*
* Algorithm is simple:
* 1. split the instruction string into a [Sequence] of [String] (from: "L2, L3" we get: "L2", " L3")
* 2. trim the white chars from the [Sequence] of [String] we got in previous step
* 3. each instruction can be built only when we know what was the previous instruction, so we [scan] the whole
* [Sequence] of [String]. Method [scan] for a Sequence<T> takes an initial value of type R and a lambda (R, T) -> R to
* process all the elements of the sequence. As the function (R, T) -> R expects two arguments, for the first element in
* the Sequence<T> the specified initial value is used. This way in our case we can easily calculate each [Instruction].
* 4. Change [Instruction] to [Coordinates]
* 5. Pick last [Coordinates] from the [Sequence]
*/
fun getShortestPathLengthToDestination(instructions: String): Int {
val startInstruction = Instruction(Direction.NORTH, 0) //after we land in the city we are pointing North
val startCoords = Coordinates(0, 0)
val stopCoords = instructions
.splitToSequence(delimiters = ",", ignoreCase = true)
.map(String::trim)
.scan(startInstruction, Instruction::next)
.scan(startCoords, Coordinates::next)
.last()
return startCoords.getL1distance(stopCoords)
}
/**
* -------------------- Part 2 -----------------------
*
* Then, you notice the instructions continue on the back of the Recruiting Document. Easter Bunny HQ is actually at the
* first location you visit twice. For example, if your instructions are R8, R4, R4, R8, the first location you visit
* twice is 4 blocks away, due East.
*
* http://adventofcode.com/2016/day/1
*/
/**
* Calculates a [List] of [Coordinates] for a given [Direction] and a distance. It's working through a infinite
* [Sequence] of value 1 (this is the step), it takes only first few values (the amount of values taken is equal to the
* distance), then it just calculates [Coordinates] on the path in the given [Direction].
*
* Before I implement a nice flatScan method, we need to return a [List] because
*/
private fun Coordinates.path(direction: Direction, distance: Int) =
generateSequence { 1 }
.take(distance)
.scan(this) { coordinates, value -> coordinates.next(direction, value) }
.toList()
/**
* Calculates a [List] of [Coordinates] for a given [Instruction].
*/
private fun Coordinates.path(instruction: Instruction) = path(instruction.direction, instruction.distance)
/**
* Calculates the shortest path from the start [Coordinates] (0, 0) to the first repeating [Coordinates] calculated by
* processing the given instructions string.
*
* Algorithm is simple:
* 1. split the instruction string into a [Sequence] of [String] (from: "L2, L3" we get: "L2", " L3")
* 2. trim the white chars from the [Sequence] of [String] we got in previous step
* 3. each instruction can be built only when we know what was the previous instruction, so we [scan] the whole
* [Sequence] of [String]. Method [scan] for a Sequence<T> takes an initial value of type R and a lambda (R, T) -> R to
* process all the elements of the sequence. As the function (R, T) -> R expects two arguments, for the first element in
* the Sequence<T> the specified initial value is used. This way in our case we can easily calculate each [Instruction].
* 4. between each previous and next [Coordinates] a [List] of [Coordinates] is calculated (a path). As we are working
* after [Int] values for coordinates, the calculated path will have a difference of 1 between two coordinates that are
* next of each other (in terms of x or y value)
* 5. we need to flatten Sequence<List<Coordinates>> to Sequence<Coordinates>
* 6. we take the fist repeated coordinates
*/
fun getShortestPathLengthToFirstRepeatedDestination(instructions: String): Int {
val startInstruction = Instruction(Direction.NORTH, 0) //after we land in the city we are pointing North
val startCoords = Coordinates(0, 0)
val partialPath = instructions
.splitToSequence(delimiters = ",", ignoreCase = true)
.map(String::trim)
.scan(startInstruction, Instruction::next)
.scan(listOf(startCoords)) { list, instr -> list.last().path(instr) } //flatScan??
.flatten()
val fullPath = sequenceOf(startCoords) + partialPath
val stopCoords = fullPath.firstRepeated()
return startCoords.getL1distance(stopCoords)
} | 0 | Kotlin | 0 | 0 | 49ba07dd5fbc2949ed3c3ff245d6f8cd7af5bebe | 9,426 | challenges-kotlin | Apache License 2.0 |
src/main/kotlin/de/consuli/aoc/year2022/days/Day05.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2022.days
import de.consuli.aoc.common.Day
class Day05 : Day(5, 2022) {
override fun partOne(testInput: Boolean): Any {
return calculateFinalCrateOrder(testInput, false)
}
override fun partTwo(testInput: Boolean): Any {
return calculateFinalCrateOrder(testInput, true)
}
private fun calculateFinalCrateOrder(testInput: Boolean, moveMultipleCrates: Boolean): String {
val stacks = getStacks(testInput).toMutableList()
getRearrangements(testInput).forEach {
stacks[it.third - 1] = stacks[it.second - 1].take(it.first)
.let { crates -> if (!moveMultipleCrates) crates.reversed() else crates } + stacks[it.third - 1]
stacks[it.second - 1] = stacks[it.second - 1].drop(it.first)
}
return stacks.filter { it.isNotEmpty() }.joinToString("") { it[0] }
}
private fun getStacks(testInput: Boolean): List<List<String>> {
val stacks = List(9) { ArrayList<String>() }
getInput(testInput).subList(
0,
getInput(testInput).indexOf("") - 1
).reversed().forEach {
var stackIndex = 0
for (crateIndex in 1 until it.length step 4) {
val crate = it[crateIndex]
stackIndex++
if (crate !in 'A'..'Z') continue
stacks[stackIndex - 1].add(0, crate.toString())
}
}
return stacks
}
private fun getRearrangements(testInput: Boolean): List<Triple<Int, Int, Int>> {
return getInput(testInput).subList(
getInput(testInput).indexOf("") + 1,
getInput(testInput).size
).map {
val (amount, from, to) = "(\\d+)".toRegex().findAll(it).map { it.value.toInt() }.toList()
Triple(amount, from, to)
}
}
}
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 1,859 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day14.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | import kotlin.math.sign
data class Position14(val right: Int, val down: Int) {
fun to(end: Position14): Sequence<Position14> {
var p = this
return sequence {
while (p != end) {
yield(p)
if (p.down == end.down) {
p = Position14((end.right - p.right).sign + p.right, p.down)
} else if (p.right == end.right) {
p = Position14(p.right, (end.down - p.down).sign + p.down)
}
}
yield(end)
}
}
val below: Position14
get() = Position14(right, down + 1)
val belowLeft: Position14 get() = Position14(right - 1, down + 1)
val belowRight: Position14 get() = Position14(right + 1, down + 1)
}
data class Bounds(var left: Int, var right: Int, var up: Int, var down: Int)
class Map14(private val grid: MutableMap<Position14, Char> = mutableMapOf()) {
private var pen: Position14 = Position14(0, 0)
private var bounds: Bounds = Bounds(500, 500, 0, 0)
private var floor: Int? = null
private fun update(pos: Position14) {
bounds.left = min(bounds.left, pos.right)
bounds.right = max(bounds.right, pos.right)
bounds.up = min(bounds.up, pos.down)
bounds.down = max(bounds.down, pos.down)
}
fun move(position: Position14) {
pen = position
update(pen)
}
fun draw(position: Position14) {
for (p in pen.to(position)) {
grid[p] = '#'
update(p)
}
pen = position
}
fun drop(start: Position14): Boolean {
var sand = start
if (c(sand) != null) {
return false
}
while (true) {
sand = when {
c(sand.below) == null -> sand.below
c(sand.belowLeft) == null -> sand.belowLeft
c(sand.belowRight) == null -> sand.belowRight
else -> break
}
if (sand.down > bounds.down) {
return false
}
}
grid[sand] = 'o'
return true
}
private fun c(pos: Position14): Char? {
if (pos.down == floor) {
return '#'
}
return grid[pos]
}
fun print() {
for (y in bounds.up..bounds.down) {
for (x in bounds.left..bounds.right) {
val ch = grid[Position14(x, y)] ?: '.'
print(ch)
}
println()
}
}
fun addFloor() {
bounds.down += 2
floor = bounds.down
}
}
fun main() {
fun parse(input: List<String>): Map14 {
val result = Map14()
for (line in input) {
val positions = line.split(" -> ").map {
val (right, down) = it.split(',')
Position14(right.toInt(), down.toInt())
}
result.move(positions[0])
for (point in positions.drop(1)) {
result.draw(point)
}
}
return result
}
fun part1(input: List<String>): Int {
val map = parse(input)
var steps = 0
while (map.drop(Position14(500, 0))) {
steps += 1
}
map.print()
return steps
}
fun part2(input: List<String>): Int {
val map = parse(input)
map.addFloor()
var steps = 0
while (map.drop(Position14(500, 0))) {
steps += 1
}
map.print()
// println(steps)
return steps
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
val input = readInput("Day14")
println(part1(input))
check(part2(testInput) == 93)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 3,826 | advent-of-code-2022 | Apache License 2.0 |
src/day8/Day8.kt | ZsemberiDaniel | 159,921,870 | false | null | package day8
import RunnablePuzzleSolver
class Day8 : RunnablePuzzleSolver {
private lateinit var rootNode: Node
override fun readInput1(lines: Array<String>) {
rootNode = getNodeStartingFrom(lines[0].split(" ").map { it.toInt() }.toTypedArray(), 0).first
}
private fun getNodeStartingFrom(numbers: Array<Int>, at: Int): Pair<Node, Int> {
val currNode = Node(numbers[at], numbers[at + 1])
// this will store how long this node is in the input array
var currLength = 2
// we go through the children and get them from the input array
for (i in 0 until currNode.childCount) {
// the child should be at 'at + currLength' because we always add the child's length to the current length
val childNodeWithLength = getNodeStartingFrom(numbers, at + currLength)
currLength += childNodeWithLength.second
currNode.children[i] = childNodeWithLength.first
}
// we also need to get the metadata
for (i in 0 until currNode.metadataCount) {
currNode.metadata[i] = numbers[at + currLength + i]
}
currLength += currNode.metadataCount
// we return the node itself and how long it is in the input array
return Pair(currNode, currLength)
}
override fun readInput2(lines: Array<String>) { }
override fun solvePart1(): String {
return addMetadata(rootNode).toString()
}
private fun addMetadata(currNode: Node): Int {
// we store the sum for part 2 so if it is null we need to calculate it
if (currNode.normalSum == null) {
// simply add metadata sum
currNode.normalSum = currNode.metadata.sumBy { it ?: 0 }
// and sum of all child metadata
for (child in currNode.children) {
currNode.normalSum = currNode.normalSum!! + addMetadata(child!!)
}
}
// this cannot be null at this point
return currNode.normalSum!!
}
override fun solvePart2(): String {
return addMetadataComplicated(rootNode).toString()
}
private fun addMetadataComplicated(currNode: Node): Int {
// we need to store the complicated sum because it may have to be calculated more than once for a single node
if (currNode.complicatedSum == null) {
// just like how it said in the exercise
if (currNode.childCount == 0) {
currNode.complicatedSum = currNode.normalSum
} else {
currNode.complicatedSum = 0
// we go through the metadata and get only the ones which can be an index
for (md in currNode.metadata) {
if (1 <= md!! && md <= currNode.childCount) {
currNode.complicatedSum =
currNode.complicatedSum!! + addMetadataComplicated(currNode.children[md - 1]!!)
}
}
}
}
return currNode.complicatedSum!!
}
data class Node(val childCount: Int, val metadataCount: Int) {
val metadata = Array<Int?>(metadataCount) { null }
val children = Array<Node?>(childCount) { null }
var normalSum: Int? = null
var complicatedSum: Int? = null
}
}
| 0 | Kotlin | 0 | 0 | bf34b93aff7f2561f25fa6bd60b7c2c2356b16ed | 3,336 | adventOfCode2018 | MIT License |
src/Day10.kt | sungi55 | 574,867,031 | false | {"Kotlin": 23985} | fun main() {
val day = "Day10"
val oneCycleCommand = "noop"
val twoCycleCommand = "addx"
fun part1(lines: List<String>): Int {
val commands = lines.iterator()
var signalStrength = 1
var currentCycle = 0
return listOf(20, 60, 100, 140, 180, 220).sumOf { nextCycle ->
var currentStrength = signalStrength
while (currentCycle < nextCycle) {
currentStrength = signalStrength
val command = commands.next()
when {
command.startsWith(oneCycleCommand) -> currentCycle++
command.startsWith(twoCycleCommand) -> {
currentCycle += 2
signalStrength += command.substringAfter(" ").toInt()
}
}
}
nextCycle * currentStrength
}
}
fun part2(lines: List<String>): String = buildList {
val commands = lines.iterator()
var currentCycle = 0
var signalStrength = 1
repeat(6) { row ->
val line = buildString {
repeat(40) { column ->
append(if (signalStrength - column in -1..1) '#' else '.')
while (currentCycle < 40 * row + column) {
val command = commands.next()
when {
command.startsWith(oneCycleCommand) -> currentCycle++
command.startsWith(twoCycleCommand) -> {
currentCycle += 2
signalStrength += command.substringAfter(" ").toInt()
}
}
}
}
}
add(line)
}
}.joinToString("\n")
val testInput = readInput(name = "${day}_test")
val input = readInput(name = day)
check(part1(testInput) == 13140)
println(part2(testInput))
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2a9276b52ed42e0c80e85844c75c1e5e70b383ee | 2,052 | aoc-2022 | Apache License 2.0 |
kotlin/app/src/main/kotlin/coverick/aoc/day2/RockPaperScissors.kt | RyTheTurtle | 574,328,652 | false | {"Kotlin": 82616} | package coverick.aoc.day2;
import readResourceFile
// https://adventofcode.com/2022/day/2
val INPUT_FILE = "rockPaperScissors-input.txt"
// enumerate shapes and outcomes for rock,paper,scissors
// according to text rules.
enum class Shape(val score: Int) {
ROCK(1),
PAPER(2),
SCISSOR(3)
}
enum class Outcome(val score: Int){
WIN(6),
LOSE(0),
DRAW(3)
}
// map input letters to shapes and outcomes for the game
// based on rules (outcome letter mappings are from part 2)
val SHAPE_LETTER_MAPPINGS = mapOf(
"A" to Shape.ROCK,
"X" to Shape.ROCK,
"B" to Shape.PAPER,
"Y" to Shape.PAPER,
"C" to Shape.SCISSOR,
"Z" to Shape.SCISSOR
)
val OUTCOME_LETTER_MAPPING = mapOf(
"X" to Outcome.LOSE,
"Y" to Outcome.DRAW,
"Z" to Outcome.WIN
)
// configure scoring rules for 2 player rock,paper,scissors
// as a multidimensional map opponent shape -> my shape -> outcome
val TWO_PLAYER_SCORE_MAPPING = mapOf(
Shape.ROCK to mapOf(
Shape.ROCK to Outcome.DRAW,
Shape.PAPER to Outcome.WIN,
Shape.SCISSOR to Outcome.LOSE
),
Shape.PAPER to mapOf(
Shape.ROCK to Outcome.LOSE,
Shape.PAPER to Outcome.DRAW,
Shape.SCISSOR to Outcome.WIN
),
Shape.SCISSOR to mapOf(
Shape.ROCK to Outcome.WIN,
Shape.PAPER to Outcome.LOSE,
Shape.SCISSOR to Outcome.DRAW
)
)
/* for part 2, configure mapping of
opponent shape -> desired outcome -> my shape to get that outcome
*/
val OPPONENT_OUTCOME_CONFIG = mapOf(
Shape.ROCK to mapOf(
Outcome.DRAW to Shape.ROCK,
Outcome.WIN to Shape.PAPER,
Outcome.LOSE to Shape.SCISSOR
),
Shape.PAPER to mapOf(
Outcome.DRAW to Shape.PAPER,
Outcome.WIN to Shape.SCISSOR,
Outcome.LOSE to Shape.ROCK
),
Shape.SCISSOR to mapOf(
Outcome.DRAW to Shape.SCISSOR,
Outcome.WIN to Shape.ROCK,
Outcome.LOSE to Shape.PAPER
)
)
fun scoreRound(opponent: Shape?, me:Shape?) : Int {
val outcomeScore: Int = TWO_PLAYER_SCORE_MAPPING.get(opponent)?.get(me)?.score?:0
val choiceScore: Int = me?.score?:0
return outcomeScore + choiceScore
}
fun part1(): Int{
val rounds = readResourceFile(INPUT_FILE)
var totalScore = 0
rounds.forEach({
val inputs = it.split(" ")
val myChoice = SHAPE_LETTER_MAPPINGS.get(inputs[1])
val opponentChoice = SHAPE_LETTER_MAPPINGS.get(inputs[0])
totalScore += scoreRound(opponentChoice, myChoice)
})
return totalScore
}
fun part2(): Int{
val rounds = readResourceFile(INPUT_FILE)
var totalScore = 0
rounds.forEach({
val inputs = it.split(" ")
val opponentChoice = SHAPE_LETTER_MAPPINGS.get(inputs[0])
val desiredOutcome = OUTCOME_LETTER_MAPPING.get(inputs[1])
val myChoice = OPPONENT_OUTCOME_CONFIG.get(opponentChoice)?.get(desiredOutcome)
totalScore += scoreRound(opponentChoice, myChoice)
})
return totalScore
}
fun solution(){
println("Rock,Paper,Scissors Part 1 Solution: ${part1()}")
println("Rock,Paper,Scissors Part 2 Solution: ${part2()}")
} | 0 | Kotlin | 0 | 0 | 35a8021fdfb700ce926fcf7958bea45ee530e359 | 3,154 | adventofcode2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.