path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/dev/bogwalk/batch5/Problem57.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch5
import dev.bogwalk.util.maths.lcm
import dev.bogwalk.util.strings.digitCount
import java.math.BigInteger
/**
* Problem 57: Square Root Convergents
*
* https://projecteuler.net/problem=57
*
* Goal: Given N, in the 1st N expansions of the square root of 2's infinite continued fraction,
* find the iteration numbers where the numerator has more digits than the denominator.
*
* Constraints: 8 <= N <= 1e4
*
* Square Root of 2: This can be expressed as an infinite continued fraction ->
*
* Iteration 1 -> sqrt(2) = 1 + 1/2 = 3/2 = 1.5
* Iteration 2 -> 1 + 1/(2 + 1/2) = 7/5 = 1.4
* Iteration 3 -> 1 + 1/(2 + (1/(2+1/2))) = 17/12 = 1.41666...
* Iteration 4 -> 1 + 1/(2 + (1/(2 + 1/(2 + 1/2)))) = 41/29 = 1.41379...
*
* The next 4 expansions are 99/70, 239/169, 577/408, 1393/985. The latter 8th
* expansion is the 1st expansion where the number of digits in the numerator exceed
* that of the denominator.
*
* e.g.: N = 14
* iterations = [8, 13]
* expansions are: 1393 / 985 and 114243 / 80782
*/
class SquareRootConvergents {
/**
* The infinite continued fractional part is repeatedly calculated by adding its previous
* value to 2 (= 4/2) then dividing 1 by the result, simply by swapping the numerator and
* denominator. The result is then added to 1.
*
* e.g. 3rd iteration, with 2nd iteration fractional part = 2/5:
* 1 + (1 / (4/2 + 2/5)) = 1 + (1 / (12/5))
* fractional part becomes 5/12
* expansion = 1 + 5/12 = 17/12
*
* Consider comparing number of digits by calling log10() instead of casting to string.
* Remember that log10(10) = 1.0 because 10^1 = 10 and every 2-digit number will be a
* fraction between 1 and 2. Consider implementing a helper to do so for BigInteger.
*
* SPEED (WORSE) 937.57ms for N = 2e3
*
* @return list of integers representing the iteration where number of digits in the
* numerator exceeds number of digits in the denominator.
*/
fun squareRootFractionsManual(n: Int): List<Int> {
val iterations = mutableListOf<Int>()
// 1st iteration fractional part
var infFraction = 1.toBigInteger() to 2.toBigInteger()
for (i in 2..n) {
// continued fraction of 1 / (2 + previous fraction)
infFraction = addFractions(
4.toBigInteger(), 2.toBigInteger(), infFraction.first, infFraction.second
).reversed()
val fraction = addFractions(
BigInteger.ONE, BigInteger.ONE, infFraction.first, infFraction.second
)
if (
fraction.first.digitCount() > fraction.second.digitCount()
) {
iterations.add(i)
}
}
return iterations
}
private fun Pair<BigInteger, BigInteger>.reversed() = second to first
/**
* Add 2 fractions manually and return in a reduced form.
*
* @return pair of (numerator, denominator).
*/
private fun addFractions(
n1: BigInteger,
d1: BigInteger,
n2: BigInteger,
d2: BigInteger
): Pair<BigInteger, BigInteger> {
val denominator = d1.lcm(d2)
val numerator = denominator / d1 * n1 + denominator / d2 * n2
val divisor = numerator.gcd(denominator)
return numerator / divisor to denominator / divisor
}
/**
* Solution optimised based on the following:
*
* - Further reducing the above formula:
*
* if a_0 = 1 + 1/2, a_1 = 1 + 1/(2 + 1/2)
* then a_(i+1) = 1 + 1/(1 + a_i)
*
* if a_i = n_i / d_i is inserted, the formula becomes:
*
* a_(i+1) = (2d_i + n_i) / (d_i + n_i)
*
* - Storing the ceiling for current number of digits, i.e. 10 for 1-digit numbers, 100
* for 2-digit numbers, etc. This is compared instead of repeatedly calling log10().
*
* SPEED (BETTER) 4.31ms for N = 2e3
*
* @return list of integers representing the iteration where number of digits in the
* numerator exceeds number of digits in the denominator.
*/
fun squareRootFractions(n: Int): List<Int> {
val iterations = mutableListOf<Int>()
// 1st iteration expansion
var infN = 3.toBigInteger()
var infD = 2.toBigInteger()
// both start as 1-digit numbers
var nCeil = BigInteger.TEN
var dCeil = BigInteger.TEN
for (i in 2..n) {
infN += BigInteger.TWO * infD.also {
// uses previous infN value, not the newly assigned one
infD += infN
}
if (infN >= nCeil) nCeil *= BigInteger.TEN
if (infD >= dCeil) dCeil *= BigInteger.TEN
if (nCeil > dCeil) iterations.add(i)
}
return iterations
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 4,916 | project-euler-kotlin | MIT License |
src/Day06.kts | Cicirifu | 225,414,163 | false | null | import java.io.File
val input by lazy {
File("Day06.txt").readLines(Charsets.UTF_8)
}
val edges = input.map { line ->
val nodes = line.split(")")
nodes[1] to nodes[0]
}.toMap()
fun pathToRoot(node: String) = generateSequence(node) { edges[it] }
val orbits = edges.keys.map { pathToRoot(it).count() - 1 }.sum()
println("Assignment A: $orbits")
val santaPath = pathToRoot("SAN").toList()
val youPath = pathToRoot("YOU").toList()
val crossing = santaPath.intersect(youPath).count() // Find index of divergence
val transfers = santaPath.size + youPath.size - 2 * crossing - 2 // do not count YOU/SAN
println("Assignment B: $transfers")
//### Silly Dijkstra version for posterity.
//data class Path(val parent: Path?, val node: String, val cost: Int)
//
//fun dijkstra(edgeMap: Map<String, String>, start: String, end: String): Path? {
// fun children(node: String) = edgeMap.filterKeys { it == node }.values + edgeMap.filterValues { it == node }.keys
//
// val visited = mutableMapOf<String, Path>()
// val queue = PriorityQueue<Path> { a, b -> a.cost.compareTo(b.cost) }
// queue += Path(null, start, 0)
//
// while (!queue.isEmpty()) {
// val current = queue.poll()
// if (current.node == end) {
// return current
// }
// val children = children(current.node)
// children.filter { it != current.parent?.node }.forEach { c ->
// val cost = current.cost + 1
// val existing = visited[c]
// if (existing == null || cost < existing.cost) {
// val path = Path(current, c, current.cost + 1)
// visited[c] = path
// queue += path
// }
// }
// }
//
// return null
//}
//
//val path = dijkstra(edges, "YOU", "SAN")
//val transfers = path!!.cost - 2
| 0 | Kotlin | 0 | 0 | bbeb2ee39fd13bd57cd6384d0a82f91227e4541f | 1,820 | AdventOfCode2019 | Apache License 2.0 |
src/Day06.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | fun main() {
val testInput = readInput("Day06_test")
check(part1(testInput[0]) == 5)
check(part1(testInput[1]) == 6)
check(part1(testInput[2]) == 10)
check(part1(testInput[3]) == 11)
check(part2(testInput[0]) == 23)
check(part2(testInput[1]) == 23)
check(part2(testInput[2]) == 29)
check(part2(testInput[3]) == 26)
val input = readInput("Day06")
println(part1(input[0]))
println(part2(input[0]))
}
private fun part1(input: String): Int = findUniqueSequence(input, 4)
private fun part2(input: String): Int = findUniqueSequence(input, 14)
private fun findUniqueSequence(input: String, targetCount: Int): Int {
val counts = mutableMapOf<Char, Int>()
repeat(targetCount - 1) { i ->
counts[input[i]] = counts.getOrDefault(input[i], 0) + 1
}
for (i in (targetCount - 1)..input.lastIndex) {
counts[input[i]] = counts.getOrDefault(input[i], 0) + 1
if (counts.size == targetCount) {
return i + 1
}
if (counts[input[i - targetCount + 1]] == 1) {
counts.remove(input[i - targetCount + 1])
} else {
counts[input[i - targetCount + 1]] = counts.getValue(input[i - targetCount + 1]) - 1
}
}
error("Not found")
} | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 1,268 | AOC2022 | Apache License 2.0 |
src/day25/Day25.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day25
import readInput
import kotlin.math.pow
fun main() {
val day = 25
val testInput = readInput("day$day/testInput")
check(part1(testInput) == "2=-1=0")
val input = readInput("day$day/input")
println(part1(input))
}
fun part1(input: List<String>): String {
return convertDigitToSnafu(input.sumOf { convertFromSnafuToDigit(it) })
}
fun part2(input: List<String>): Int {
return input.size
}
fun convertFromSnafuToDigit(snafu: String): Long {
val snafuDigits = snafu.toCharArray().reversedArray()
val digit = snafuDigits.mapIndexed { index, snafuDigit ->
var digit = 5.0.pow(index).toLong()
if (snafuDigit == '-') {
digit *= -1
} else if (snafuDigit == '=') {
digit *= -2
} else {
digit *= snafuDigit.digitToInt()
}
digit
}.sum()
return digit
}
fun convertDigitToSnafu(digit: Long): String {
// convert to 5
val fivesRadixNums = digit.toString(5).map { it.digitToInt() }.toMutableList()
val res = mutableListOf<String>()
for (i in fivesRadixNums.size - 1 downTo 0) {
val r: Int = fivesRadixNums[i]
if (r <= 2) {
res.add(0, r.toString())
} else {
if (r == 3) {
res.add(0, "=")
} else if (r == 4) {
res.add(0, "-")
} else if (r == 5) {
res.add(0, "0")
}
if (i != 0) {
fivesRadixNums[i - 1] += 1
} else {
res.add(0, 1.toString())
}
}
}
return res.joinToString(separator = "")
} | 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 1,659 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2015/Day14.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2015
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 14: Reindeer Olympics](https://adventofcode.com/2015/day/14).
*/
object Day14 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2015/Day14")
val raceTime = 2503
println("Part One: ${part1(input, raceTime)}")
println("Part Two: ${part2(input, raceTime)}")
}
}
fun part1(input: List<String>, raceTime: Int) = race(input, raceTime)
.maxByOrNull { it.totalDistance }?.totalDistance
fun part2(input: List<String>, raceTime: Int) = race(input, raceTime)
.maxByOrNull { it.scores }?.scores
private fun race(input: List<String>, raceTime: Int): List<Reindeer> {
val reindeerList = input.map { Reindeer(it.split(' ')) }
repeat(raceTime) {
reindeerList.forEach { deer ->
if (deer.isMoving && deer.currentMoveTime < deer.moveTime) {
deer.totalDistance += deer.distancePerSecond
deer.currentMoveTime++
} else if (deer.isMoving && deer.currentMoveTime == deer.moveTime) {
deer.currentRestTime = 1
deer.isMoving = false
} else if (!deer.isMoving && deer.currentRestTime < deer.restTime)
deer.currentRestTime++
else {
deer.currentMoveTime = 1
deer.totalDistance += deer.distancePerSecond
deer.isMoving = true
}
}
val currentLeadingDistance = reindeerList.maxByOrNull { it.totalDistance }?.totalDistance
reindeerList.forEach { if (it.totalDistance == currentLeadingDistance) it.scores++ }
}
return reindeerList
}
data class Reindeer(
var name: String, var distancePerSecond: Int, var moveTime: Int, var restTime: Int,
var totalDistance: Int = 0, var currentMoveTime: Int = 0, var currentRestTime: Int = 0,
var isMoving: Boolean = true, var scores: Int = 0
) {
constructor(split: List<String>) : this(
name = split[0], distancePerSecond = split[3].toInt(),
moveTime = split[6].toInt(), restTime = split[13].toInt()
)
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 2,371 | advent-of-code | MIT License |
src/questions/BestTimeStockII.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
import java.util.*
/**
* You are given an integer array prices where `prices[i]` is the price of a given stock on the ith day.
* On each day, you may decide to buy and/or sell the stock.
* You can only hold at most one share of the stock at any time.
* However, you can buy it then immediately sell it on the same day.
* Find and return the maximum profit you can achieve.
*
* [Source](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)
*
* @see [BestTimeStock]
*/
@UseCommentAsDocumentation
private object BestTimeStockII
private fun maxProfit(prices: IntArray): Int {
val futureSellPrices = Array<Int>(prices.size) { Integer.MIN_VALUE }
val futureBuyPrices = Array<Int>(prices.size) { Integer.MAX_VALUE }
for (index in prices.lastIndex downTo 0) {
futureSellPrices[index] = maxOf(futureSellPrices.getOrNull(index + 1) ?: Integer.MIN_VALUE, prices[index])
futureBuyPrices[index] = minOf(futureBuyPrices.getOrNull(index + 1) ?: Integer.MAX_VALUE, prices[index])
}
var result = 0
var boughtAt: Int? = null
for (index in 0..prices.lastIndex) {
val maxSell = futureSellPrices[index] // max sell price in future
val minBuy = futureBuyPrices[index] // min buy price in future
val current = prices[index]
if (boughtAt == null) { // haven't bought yet
if (current == maxSell) { // if this is maxSell price, then don't buy
boughtAt = null
} else if (current in minBuy until maxSell) { // buy if you can sell it at higher price in future
boughtAt = current
}
} else { // if already bought, see if you can sell
if (current == maxSell) { // this is max sell price, then sell it!
result += (current - boughtAt) // sold
} else if (current > boughtAt && current in minBuy until maxSell) { // sell if there's profit
result += (current - boughtAt) //sold
}
if (current in minBuy until maxSell) { // re-buy it if you can have profit in the future
boughtAt = current // re-bought at the same day
} else {
boughtAt = null // sold
}
}
}
return result
}
fun main() {
maxProfit(intArrayOf(7, 1, 5, 3, 6, 4)) shouldBe 7
maxProfit(intArrayOf(2, 4, 1)) shouldBe 2
maxProfit(intArrayOf(1, 2, 3, 4, 5)) shouldBe 4
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,516 | algorithms | MIT License |
src/Day04_CampCleanup.kt | raipc | 574,467,742 | false | {"Kotlin": 9511} | fun main() {
checkAndSolve("Day04", 2) { it.count { line -> lineHasIncludingRanges(line) } }
checkAndSolve("Day04", 4) { it.count { line -> lineHasOverlappingRanges(line) } }
}
private fun parseRange(value: String) = value.split('-').let { IntRange(it[0].toInt(), it[1].toInt()) }
private fun lineHasIncludingRanges(value: String): Boolean =
value.split(',').let { oneContainsTheOther(parseRange(it[0]), parseRange(it[1])) }
private fun lineHasOverlappingRanges(value: String): Boolean =
value.split(',').let { oneOverlapsTheOther(parseRange(it[0]), parseRange(it[1])) }
private fun oneContainsTheOther(first: IntRange, second: IntRange): Boolean =
(first.first <= second.first && first.last >= second.last) ||
(second.first <= first.first && second.last >= first.last)
private fun oneOverlapsTheOther(first: IntRange, second: IntRange): Boolean =
(second.first <= first.last && first.first <= second.first) ||
(first.first <= second.last && second.first <= first.first)
| 0 | Kotlin | 0 | 0 | 9068c21dc0acb5e1009652b4a074432000540d71 | 1,025 | adventofcode22 | Apache License 2.0 |
src/year2022/Day04.kt | Maetthu24 | 572,844,320 | false | {"Kotlin": 41016} | package year2022
fun main() {
fun part1(input: List<String>): Int {
return input.count {
val parts = it.split(",")
val range1 =
parts.first().split("-").first().toInt()..parts.first().split("-").last().toInt()
val range2 =
parts.last().split("-").first().toInt()..parts.last().split("-").last().toInt()
(range1.first >= range2.first && range1.last <= range2.last) || (range2.first >= range1.first && range2.last <= range1.last)
}
}
fun part2(input: List<String>): Int {
return input.count {
val parts = it.split(",")
val range1 =
parts.first().split("-").first().toInt()..parts.first().split("-").last().toInt()
val range2 =
parts.last().split("-").first().toInt()..parts.last().split("-").last().toInt()
range1.first <= range2.last && range2.first <= range1.last
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val testResult = part1(testInput)
val testExpected = 2
check(testResult == testExpected) { "testResult should be $testExpected, but is $testResult" }
val testResult2 = part2(testInput)
val testExpected2 = 4
check(testResult2 == testExpected2) { "testResult2 should be $testExpected2, but is $testResult2" }
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 3b3b2984ab718899fbba591c14c991d76c34f28c | 1,516 | adventofcode-kotlin | Apache License 2.0 |
src/Day12.kt | anilkishore | 573,688,256 | false | {"Kotlin": 27023} | import java.util.LinkedList
import java.util.Queue
fun main() {
fun part1(grid: List<String>): Int {
data class Cell(val r: Int, val c: Int) {
fun neighbors(): List<Cell> = listOf(Cell(r-1, c), Cell(r, c-1), Cell(r+1, c), Cell(r, c+1))
fun elev(): Char {
val c = grid[r][c]
if (c == 'S')
return 'a'
else if (c == 'E')
return 'z'
return c
}
}
fun findIt(ch: Char): Cell {
for (i in grid.indices) {
var j = grid[i].indexOf(ch)
if (j >= 0)
return Cell(i, j)
}
return Cell(-1, -1)
}
val start = findIt('S')
var end = findIt('E')
val Q: Queue<Cell> = LinkedList()
val visited = hashSetOf<Cell>()
fun checkAndAdd(cell: Cell) =
if (visited.contains(cell)) false
else {
Q.offer(cell)
visited.add(cell)
cell == end
}
checkAndAdd(start)
var steps = 0
while (Q.isNotEmpty()) {
++steps
println()
println("Steps #$steps")
for (i in Q.size downTo 1) {
val curc = Q.poll()
println(curc)
curc?.neighbors()?.filter {
c -> c.r in grid.indices && c.c in grid[0].indices && (curc.elev() <= c.elev() + 1)
}?.forEach {
println(" $it")
if (checkAndAdd(it)) {
return steps
}
}
}
println(Q)
}
return -1
}
val input = readInput("Day12")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9 | 1,845 | AOC-2022 | Apache License 2.0 |
src/Day01.kt | jottinger | 573,151,634 | false | {"Kotlin": 2022} | data class Elf(val calories: List<Int>) {
fun totalCalories(): Int {
return calories.sum()
}
override fun toString(): String {
return calories.toString()+" (total: "+totalCalories()+")"
}
}
fun main() {
val mode = "actual"
fun convertToElves(input: List<String>): List<Elf> {
val elves: MutableList<Elf> = mutableListOf()
val calories: MutableList<Int> = mutableListOf()
input.stream().forEach {
if (it.trim() == "") {
elves += Elf(calories.toList())
calories.clear()
} else {
calories+=it.trim().toInt()
}
}
return elves
}
fun part1(input: List<Elf>): Int {
return input
.map { it.totalCalories() }
.maxOf { it }
}
fun part2(input: List<Elf>): Int {
return input
.map { it.totalCalories() }
.sorted()
.reversed()
.subList(0,3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(mode)
// check(part1(testInput) == 1)
val input = readInput(mode)
val elves= convertToElves(input)
println("the calories from the top elf : "+part1(elves))
println("the calories from the top three elves: "+part2(elves))
}
| 0 | Kotlin | 0 | 0 | 910ec8f0b6f64e4fa27c53189babe12e2e1f030b | 1,381 | advent202201 | Apache License 2.0 |
src/aoc2017/kot/Day07.kt | Tandrial | 47,354,790 | false | null | package aoc2017.kot
import getWords
import java.io.File
object Day07 {
data class Program(val name: String, val oWeight: Int, val supports: List<String> = listOf(), var weight: Int = oWeight)
private fun parse(input: List<String>): List<Program> = input.map {
val line = it.getWords()
Program(line[0], line[1].toInt(), line.drop(2))
}
fun partOne(input: List<String>): String {
// The root node has no edge pointing to it ==> it never shows up on the right side of an edge
val out = parse(input)
val onRightSide = out.flatMap { it.supports }
return out.first { it.name !in onRightSide }.name
}
fun partTwo(input: List<String>, rootNode: String): Int {
val lookUp = parse(input).associateBy { it.name }
updatedWeights(lookUp[rootNode]!!, lookUp)
for (p in lookUp.values) {
// Group the weights of the child nodes, if there is more then one group we found the disbalanced group
val weights = p.supports.map { lookUp[it] }.groupBy { it!!.weight }
if (weights.size > 1) {
val correctWeight = weights.filterValues { it.size > 1 }.keys.toList()[0]
val wrongWeight = weights.filterValues { it.size == 1 }.keys.toList()[0]
val diff = correctWeight - wrongWeight
return (weights[wrongWeight]!![0]?.oWeight ?: 0) + if (correctWeight > wrongWeight) -diff else diff
}
}
return -1
}
private fun updatedWeights(p: Program, lookup: Map<String, Program>) {
for (support in p.supports) {
updatedWeights(lookup[support]!!, lookup)
lookup[p.name]!!.weight += lookup[support]!!.weight
}
}
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day07_input.txt").readLines()
val result = Day07.partOne(input)
println("Part One = $result")
println("Part Two = ${Day07.partTwo(input, result)}")
} | 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 1,837 | Advent_of_Code | MIT License |
src/day9/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day9
import java.io.File
data class Coord(val x: Int, val y: Int)
fun Map<Coord, Int>.neighbours(coord: Coord) =
listOf(Pair(-1, 0), Pair(0, -1), Pair(1, 0), Pair(0, 1))
.map { Coord(coord.x + it.first, coord.y + it.second) }
.filter { contains(it) }
.toSet()
fun Map<Coord, Int>.isLowest(coord: Coord) =
neighbours(coord).map { this[coord]!! < this[it]!! }.all { it }
fun Map<Coord, Int>.basin(coord: Coord, visited: Set<Coord>): Set<Coord> {
if (visited.contains(coord)) {
return visited
}
return neighbours(coord)
.filter { this[it] != 9 && this[coord]!! < this[it]!! }
.fold(visited + coord) { acc, neighbour -> acc + basin(neighbour, acc) }
}
fun main() {
val grid = File("src/day9/input.txt").readLines()
.mapIndexed { i, row -> row.toList().mapIndexed { j, ch -> Coord(i, j) to Character.getNumericValue(ch) } }
.flatten()
.toMap()
val lowest = grid.filter { (coord, _) -> grid.isLowest(coord) }
println(lowest.values.sumOf { it + 1 })
println(lowest.keys
.map { grid.basin(it, emptySet()).size }
.sortedDescending()
.take(3)
.reduce(Int::times))
} | 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 1,210 | advent-of-code-2021 | MIT License |
project/src/problems/SieveOfErotasthenese.kt | informramiz | 173,284,942 | false | null | package problems
/**
* https://codility.com/media/train/9-Sieve.pdf
* The Sieve of Eratosthenes is a very simple and popular technique for finding all the prime
* numbers in the range from 2 to a given number n. The algorithm takes its name from the
* process of sieving—in a simple way we remove multiples of consecutive numbers.
* Initially, we have the set of all the numbers {2, 3,...,n}. At each step we choose the
* smallest number in the set and remove all its multiples. Notice that every composite number
* has a divisor of at most Ôn. In particular, it has a divisor which is a prime number. It
* is sucient to remove only multiples of prime numbers not exceeding Ôn. In this way, all
* composite numbers will be removed.
*/
object SieveOfErotasthenese {
/**
* Finds prime numbers in range[2..n]
*/
fun findPrimesInRange(n: Int): Array<Int> {
val isPrimeNumber = Array(n+1) {true}
isPrimeNumber[0] = false
isPrimeNumber[1] = false
var i = 2
while (i * i <= n) {
//make sure i has not already been crossed out (set to false)
if (isPrimeNumber[i]) {
var k = i * i
while (k <= n) {
isPrimeNumber[k] = false
k += i
}
}
i++
}
val primeNumbers = mutableListOf<Int>()
isPrimeNumber.forEachIndexed { index, isPrime ->
if (isPrime) {
primeNumbers.add(index)
}
}
return primeNumbers.toTypedArray()
}
/**
* https://codility.com/media/train/9-Sieve.pdf
* Find prime factors for given number n
* @param n, number for which to find prime factors/divisors
* @param primeDivisors, represent smallest prime divisor for each number in range [2, n]
* @return Array, prime factors/divisors of number n
*/
fun factorize(n: Int, primeDivisors: Array<Int>): List<Int> {
val factors = mutableListOf<Int>()
//start from n and keep decomposing it into primes
//n1 = n/prime1, n2 = n1/prime2 ... primeN = 1
var x = n
//we keep decomposing x till the point we reach the prime that can't be further decomposed
//ie. it will not be crossed it (primeDivisors[number] = 0)
while (primeDivisors[x] > 0) {
//primeDivisors[x] is the prime divisor for current value of x so it is a factor
factors += primeDivisors[x]
//let's move to the next decomposition of x
x /= primeDivisors[x]
}
//at this we have covered all the primes, except the last prime which is not crossed out
factors += x
return factors
}
fun factorize(n: Int): List<Int> {
//find prime divisors for each number in range[2, n]
val primeDivisors = primeDivisors(n)
return factorize(n, primeDivisors)
}
/**
* Find the smallest prime divisor for the given number
* @param n, range [2, n] in which to find smallest prime divisors
* @return Array contain smallest prime divisor for each number in range [2, n]
*/
private fun primeDivisors(n: Int): Array<Int> {
val primeDivisors = Array(n+1) {0}
//use sieve to cross multiples of each prime
var i = 2
//we only need to try divisors below sqrt(n) = ixi
//as after that we get symmetric divisors (n/i) for i
while (i * i <= n) {
//only check for numbers not crossed out
if (primeDivisors[i] == 0) {
var k = i * i
while (k <= n) {
//check if k is not crossed out
if (primeDivisors[k] == 0) {
//as k is not crossed out then that means i is the smallest prime number
//divisor of k so assign it to k index
primeDivisors[k] = i
}
k += i
}
}
i += 1
}
return primeDivisors
}
/**
* https://app.codility.com/programmers/lessons/11-sieve_of_eratosthenes/count_semiprimes/
* CountSemiprimes
* Count the semiprime numbers in the given range [a, b]
*
* int[] solution(int N, int[] P, int[] Q)
*
* Given an integer N and two non-empty arrays P and Q consisting of M integers,
* returns an array consisting of M elements specifying the consecutive answers to all the queries.
*/
fun countSemiPrimes(N: Int, P: IntArray, Q: IntArray): IntArray {
val prefixSumOfSemiPrimesCount = prefixSumOfSemiPrimesCount(N)
val semiPrimesCount = IntArray(P.size) {0}
for (i in 0 until P.size) {
val p = P[i]
val q = Q[i]
//calculate count of semi-primes using prefix sums
semiPrimesCount[i] = prefixSumOfSemiPrimesCount[q+1] - prefixSumOfSemiPrimesCount[p]
}
return semiPrimesCount
}
/**
* Given number n returns the prefix sums of semi primes count in range[2, n]
* @param n, end of range
* @return An array of prefix sums of semi primes count in range [2, n]
*/
private fun prefixSumOfSemiPrimesCount(n: Int): Array<Int> {
val primeDivisors = primeDivisors(n)
val prefixSumOfSemiPrimesCount = Array(n+2) { 0 }
for (i in 1..n) {
if (isSemiPrime(i, primeDivisors)) {
//add 1 because i is semi prime
prefixSumOfSemiPrimesCount[i+1] = prefixSumOfSemiPrimesCount[i] + 1
} else {
//as i is not semi prime so count remains same
prefixSumOfSemiPrimesCount[i+1] = prefixSumOfSemiPrimesCount[i]
}
}
return prefixSumOfSemiPrimesCount
}
/**
* Check if given number is a semi prime. A semi prime is product of two (may or may not be distinct)
* prime numbers
* @param n, number to check for semi prime
* @param primeDivisors, represent smallest prime divisor for each number in range [2, n]
* @return true/false, depending on if the number is prime
*/
private fun isSemiPrime(n: Int, primeDivisors: Array<Int>): Boolean {
val factors = factorize(n, primeDivisors)
return factors.size == 2
}
/**
* https://app.codility.com/programmers/lessons/11-sieve_of_eratosthenes/count_non_divisible/
* CountNonDivisible
* Calculate the number of elements of an array that are not divisors of each element.
*
* You are given an array A consisting of N integers.
* For each number A[i] such that 0 ≤ i < N, we want to count the number of elements of the array that are not the divisors of A[i]. We say that these elements are non-divisors.
* For example, consider integer N = 5 and array A such that:
* A[0] = 3
* A[1] = 1
* A[2] = 2
* A[3] = 3
* A[4] = 6
* For the following elements:
* A[0] = 3, the non-divisors are: 2, 6,
* A[1] = 1, the non-divisors are: 3, 2, 3, 6,
* A[2] = 2, the non-divisors are: 3, 3, 6,
* A[3] = 3, the non-divisors are: 2, 6,
* A[4] = 6, there aren't any non-divisors.
* Write a function:
* class Solution { public int[] solution(int[] A); }
* that, given an array A consisting of N integers, returns a sequence of integers representing the amount of non-divisors.
* Result array should be returned as an array of integers.
* For example, given:
* A[0] = 3
* A[1] = 1
* A[2] = 2
* A[3] = 3
* A[4] = 6
* the function should return [2, 4, 3, 2, 0], as explained above.
*/
fun countNonDivisors(A: Array<Int>): Array<Int> {
if (A.isEmpty()) return emptyArray()
//count all numbers in array
val count = countNumbers(A)
//create array to maintain count for each
val divisorsCount = Array(count.size) {0}
for (a in A) {
//check if a is already gone through processing and already has divisors count
if (divisorsCount[a] > 0) {
//as a already has divisors count calculated so no need to repeat
continue
}
//count divisors, including division by itself
divisorsCount[a] = countDivisors(a, count)
}
//now that we have divisors count for each number a in array A, we can easily
//calculate non-divisors by subtracting divisor count of each number for total numbers in A
val nonDivisorsCount = Array(A.size) {0}
for (i in 0 until A.size) {
val a = A[i]
nonDivisorsCount[i] = A.size - divisorsCount[a]
}
return nonDivisorsCount
}
fun countNumbers(A: Array<Int>): Array<Int> {
//find max number in array A
val N = A.max() ?: 0
val count = Array(N + 1) {0}
for (a in A) {
count[a]++
}
return count
}
fun countDivisors(n: Int, count: Array<Int>): Int {
var divisorsCount = 0
var i = 1
while (i * i <= n) {
if (n % i == 0) {
divisorsCount += count[i]
//now check for symmetric divisor
val symmetricDivisor = n / i
//make sure symmetric divisor is not same as i or n as they are already covered
if (symmetricDivisor != i) {
divisorsCount += count[symmetricDivisor]
}
}
i++
}
return divisorsCount
}
} | 0 | Kotlin | 0 | 0 | a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4 | 9,642 | codility-challenges-practice | Apache License 2.0 |
src/Day01.kt | makobernal | 573,037,099 | false | {"Kotlin": 16467} | fun main() {
fun asListOfListOfInts(input: List<String>): List<List<Int>> {
val accumlatorList = mutableListOf<MutableList<String>>()
accumlatorList.add(mutableListOf())
var currentIndex = 0
input.forEach {
if (it == "") {
currentIndex++
accumlatorList.add(mutableListOf())
} else {
accumlatorList[currentIndex].add(it)
}
}
return accumlatorList.map { it.map { it.toInt() }.toList() }.toList()
}
fun part1(input: List<String>): Int {
return asListOfListOfInts(input).map { it.sum() }.max()
}
fun part2(input: List<String>): Int {
val summedList = asListOfListOfInts(input).map { it.sum() }
val sortedList = summedList.sortedDescending()
val trimmedList = sortedList.take(3)
return trimmedList.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("solution for your input, part 1 = ${part1(input)}")
println("solution for your input, part 2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 63841809f7932901e97465b2dcceb7cec10773b9 | 1,260 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | Tiebe | 579,377,778 | false | {"Kotlin": 17146} | fun main() {
fun List<String>.mapToCrateList(): List<MutableList<Char>> {
val crates = mutableListOf<MutableList<Char>>()
repeat((this[0].length+1) / 4) {
crates.add(mutableListOf())
}
this.subList(0, this.indexOf("")-1).forEach {
it.forEachIndexed { index, letter ->
if (index % 4 == 1) {
if (letter != ' ') {
crates[(index-1)/4].add(letter)
}
}
}
}
crates.forEach {
it.reverse()
}
return crates
}
fun List<String>.parseListOfMoves(): List<Move> {
return this.subList(this.indexOf("")+1, this.size).map {
val wordsList = it.split(" ")
Move(wordsList[1].toInt(), wordsList[3].toInt(), wordsList[5].toInt())
}
}
fun part1(input: List<String>): String {
val crates = input.mapToCrateList().toMutableList()
val moves = input.parseListOfMoves()
for (move in moves) {
repeat(move.amount) {
val crate = crates[move.startPos-1].last()
crates[move.startPos-1].removeLast()
crates[move.endPos-1].add(crate)
}
}
var finalString = ""
crates.forEach { finalString += it.last() }
return finalString
}
fun part2(input: List<String>): String {
val crates = input.mapToCrateList().toMutableList()
val moves = input.parseListOfMoves()
for (move in moves) {
for (i in 0 until move.amount) {
val crateIndex = crates[move.startPos-1].dropLast(move.amount-i-1).lastIndex
val crate = crates[move.startPos-1].dropLast(move.amount-i-1).last()
crates[move.startPos-1].removeAt(crateIndex)
crates[move.endPos-1].add(crate)
}
}
var finalString = ""
crates.forEach { finalString += it.last() }
return finalString
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
part1(input).println()
part2(input).println()
}
data class Move(val amount: Int, val startPos: Int, val endPos: Int) | 1 | Kotlin | 0 | 0 | afe9ac46b38e45bd400e66d6afd4314f435793b3 | 2,408 | advent-of-code | Apache License 2.0 |
src/day11/Day11.kt | jacobprudhomme | 573,057,457 | false | {"Kotlin": 29699} | import java.io.File
import java.lang.IllegalArgumentException
import java.math.BigInteger
import java.util.PriorityQueue
class Monkey(
val heldItems: MutableList<Int>,
val applyOperation: (Int) -> BigInteger,
val decide: (Int) -> Int
) {
var inspectedItems: BigInteger = BigInteger.ZERO
fun inspect() { ++inspectedItems }
}
fun main() {
fun readInput(name: String) = File("src/day11", name)
.readLines()
fun iterateInput(input: List<String>) = sequence {
var currMonkey = input.takeWhile { it.isNotBlank() }.drop(1)
var rest = input.dropWhile { it.isNotBlank() }.drop(1)
while (currMonkey.isNotEmpty()) {
yield(currMonkey)
currMonkey = rest.takeWhile { it.isNotBlank() }
.let { if (it.isNotEmpty()) { it.drop(1) } else { it } }
rest = rest.dropWhile { it.isNotBlank() }
.let { if (it.isNotEmpty()) { it.drop(1) } else { it } }
}
}
fun processOperation(
opStr: String,
leftArg: String,
rightArg: String
): (Int) -> BigInteger {
val operation: (BigInteger, BigInteger) -> BigInteger = when (opStr) {
"+" -> { m, n -> m + n }
"*" -> { m, n -> m * n }
else -> throw IllegalArgumentException("We should never get here")
}
return if ((leftArg == "old") and (rightArg == "old")) {
{ n -> operation(n.toBigInteger(), n.toBigInteger()) }
} else if (leftArg == "old") {
{ n -> operation(n.toBigInteger(), rightArg.toBigInteger()) }
} else if (rightArg == "old") {
{ n -> operation(leftArg.toBigInteger(), n.toBigInteger()) }
} else {
{ _ -> operation(leftArg.toBigInteger(), rightArg.toBigInteger()) }
}
}
fun gcd(m: Int, n: Int): Int {
var a = m
var b = n
while (b > 0) {
val temp = b
b = a % b
a = temp
}
return a
}
fun lcm(m: Int, n: Int): Int = (m * n) / gcd(m, n)
fun processInput(input: List<String>): Pair<Array<Monkey>, Int> {
val monkeys = mutableListOf<Monkey>()
val testValues = mutableListOf<Int>()
for (monkeyStr in iterateInput(input)) {
val initItems = monkeyStr[0].substring(18).split(", ").map(String::toInt)
val (leftArg, op, rightArg, _) = monkeyStr[1].substring(19).split(" ")
val testValue = monkeyStr[2].substring(21).toInt()
val trueResult = monkeyStr[3].substring(29).toInt()
val falseResult = monkeyStr[4].substring(30).toInt()
val monkey = Monkey(
initItems.toMutableList(),
processOperation(op, leftArg, rightArg)
) { n -> if (n % testValue == 0) { trueResult } else { falseResult } }
monkeys.add(monkey)
testValues.add(testValue)
}
return Pair(monkeys.toTypedArray(), testValues.reduce { acc, value -> lcm(acc, value) })
}
fun doRound(monkeys: Array<Monkey>, spiraling: Boolean = false, lcm: Int = 1) {
for (monkey in monkeys) {
while (monkey.heldItems.isNotEmpty()) {
val currItem = monkey.heldItems.removeFirst()
monkey.inspect()
val worryLevel = monkey.applyOperation(currItem)
.let { if (spiraling) { it % lcm.toBigInteger() } else { it.div(3.toBigInteger()) } }
.toInt()
val monkeyToCatch = monkey.decide(worryLevel)
monkeys[monkeyToCatch].heldItems.add(worryLevel)
}
}
}
fun multiplyTwoLargest(monkeys: Array<Monkey>): BigInteger {
val monkeysByInspectedElements = PriorityQueue(monkeys.map { -it.inspectedItems }) // Induce max-queue
return monkeysByInspectedElements.poll() * monkeysByInspectedElements.poll()
}
fun part1(input: List<String>): BigInteger {
val (monkeys, _) = processInput(input)
repeat(20) {
doRound(monkeys)
}
return multiplyTwoLargest(monkeys)
}
fun part2(input: List<String>): BigInteger {
val (monkeys, lcm) = processInput(input)
repeat(10000) {
doRound(monkeys, spiraling=true, lcm=lcm)
}
return multiplyTwoLargest(monkeys)
}
val input = readInput("input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 9c2b080aea8b069d2796d58bcfc90ce4651c215b | 4,479 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | fun main() {
fun String.toSectionRanges(): Pair<IntRange, IntRange> {
val ranges = this.split(",")
val firstRangeArray = ranges.first().split("-")
val lastRangeArray = ranges.last().split("-")
val firstRange = IntRange(firstRangeArray.first().toInt(), firstRangeArray.last().toInt())
val lastRange = IntRange(lastRangeArray.first().toInt(), lastRangeArray.last().toInt())
return Pair(firstRange, lastRange)
}
fun part1(input: List<String>): Int =
input.filter {
val sectionRanges = it.toSectionRanges()
val firstRange = sectionRanges.first
val lastRange = sectionRanges.second
(firstRange.first <= lastRange.first && firstRange.last >= lastRange.last)||
(lastRange.first <= firstRange.first && lastRange.last >= firstRange.last)
}
.size
fun part2(input: List<String>): Int =
input.filter {
val sectionRanges = it.toSectionRanges()
val firstRange = sectionRanges.first
val lastRange = sectionRanges.second
firstRange.intersect(lastRange).isNotEmpty()
}
.size
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 1,399 | AdventOfCode2022 | Apache License 2.0 |
day01/kotlin/RJPlog/day2301_1_2.kt | mr-kaffee | 720,687,812 | false | {"Rust": 223627, "Kotlin": 46100, "Python": 39390, "Shell": 3369, "Haskell": 3122, "Dockerfile": 2236, "Gnuplot": 1678, "C++": 980, "HTML": 592, "CMake": 314} | import java.io.File
fun trebuchet(in1: Int): Int {
var conMap = mutableMapOf("0" to 1, "1" to 1, "2" to 2, "3" to 3, "4" to 4, "5" to 5, "6" to 6, "7" to 7, "8" to 8, "9" to 9)
var pattern = """\d""".toRegex()
if (in1 == 2) {
var conMap2 = 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)
conMap = conMap.plus(conMap2).toMutableMap()
pattern = """\d|one|two|three|four|five|six|seven|eight|nine""".toRegex()
}
var calibValues = mutableListOf<Int>()
File("day2301_puzzle_input.txt").forEachLine {
var firstDigit = pattern.find(it)!!.value
var matches = pattern.findAll(it)
var secondDigit = ""
matches.forEach{
secondDigit = it.value
}
calibValues.add(conMap.getValue(firstDigit)*10 + conMap.getValue(secondDigit))
}
return calibValues.sum()
}
fun main() {
var t1 = System.currentTimeMillis()
var solution1 = trebuchet(1)
var solution2 = trebuchet(2)
// print solution for part 1
println("*******************************")
println("--- Day 1: Trebuchet?! ---")
println("*******************************")
println("Solution for part1")
println(" $solution1 is the sum of all of the calibration values")
println()
// print solution for part 2
println("*******************************")
println("Solution for part2")
println(" $solution2 is the sum of all of the calibration values")
println()
t1 = System.currentTimeMillis() - t1
println("puzzle solved in ${t1} ms")
}
| 0 | Rust | 2 | 0 | 5cbd13d6bdcb2c8439879818a33867a99d58b02f | 2,144 | aoc-2023 | MIT License |
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day08.kt | loehnertz | 573,145,141 | false | {"Kotlin": 53239} | package codes.jakob.aoc
import codes.jakob.aoc.shared.*
class Day08 : Solution() {
override fun solvePart1(input: String): Any {
val grid: Grid<Tree> = input.parseGrid { Tree(it.parseInt()) }
val visibleTrees: Set<Grid.Cell<Tree>> =
SimpleDirection.values()
.flatMap { direction: SimpleDirection ->
grid.reduce(
direction,
{ cells: List<Grid.Cell<Tree>> ->
var currentMax = -1
cells.mapNotNull { cell: Grid.Cell<Tree> ->
val tree: Tree = cell.content.value
if (tree.height > currentMax) {
currentMax = tree.height
cell
} else null
}
},
{ it.flatten() },
)
}.toSet()
return visibleTrees.count()
}
override fun solvePart2(input: String): Any {
val scoreByTree: Grid<Int> = input
.parseGrid { Tree(it.parseInt()) }
.map { cell: Grid.Cell<Tree> ->
SimpleDirection.values()
.map { it.expanded }
.map { direction: ExpandedDirection ->
var keepGoing = true
cell.foldInDirection(direction, 0) { visible: Int, other: Grid.Cell<Tree> ->
if (keepGoing) {
if (cell.content.value.height <= other.content.value.height) keepGoing = false
visible + 1
} else visible
}
}.multiply()
}
return scoreByTree.cells.maxOfOrNull { it.content.value }!!
}
@JvmInline
value class Tree(
val height: Int
)
}
fun main() = Day08().solve()
| 0 | Kotlin | 0 | 0 | ddad8456dc697c0ca67255a26c34c1a004ac5039 | 2,024 | advent-of-code-2022 | MIT License |
src/main/kotlin/aoc2022/Day09.kt | w8mr | 572,700,604 | false | {"Kotlin": 140954} | package aoc2022
import aoc.*
import aoc.parser.*
import kotlin.math.absoluteValue
import kotlin.math.sign
class Day09 {
enum class Dir(val text: String) {
UP("U"),
DOWN("D"),
LEFT("L"),
RIGHT("R")
}
data class Move(val dir: Dir, val count: Int)
val dir = byEnum(Dir::class, Dir::text)
val move = seq(dir followedBy " ", number() followedBy "\n", ::Move)
val parser = oneOrMore(move)
fun solve(input: String, n: Int): Int {
data class State(
val hits: Set<Coord> = mutableSetOf(),
val head: Coord = Coord(),
val tails: List<Coord>
)
val moves = parser.parse(input)
fun Coord.move(dir: Dir): Coord =
when (dir) {
Dir.UP -> Coord(this.x, this.y + 1)
Dir.DOWN -> Coord(this.x, this.y - 1)
Dir.LEFT -> Coord(this.x - 1, this.y)
Dir.RIGHT -> Coord(this.x + 1, this.y)
}
fun Coord.follow(head: Coord): Coord =
if (((this.x - head.x).absoluteValue > 1) || ((this.y - head.y).absoluteValue > 1)) {
Coord(this.x - (this.x - head.x).sign, this.y - (this.y - head.y).sign)
} else {
this
}
val r = moves.fold(State(tails = MutableList(n) { Coord() })) { s, m ->
(0 until m.count).fold(s) { acc, _ ->
val newHead = acc.head.move(m.dir)
val newTails = acc.tails.scan(newHead) { previous, tail -> tail.follow(previous) }.drop(1)
val newHits = acc.hits.plus(newTails.last())
State(newHits, newHead, newTails)
}
}
return r.hits.size
}
fun part1(input: String): Int {
return solve(input, 1)
}
fun part2(input: String): Int {
return solve(input, 9)
}
}
| 0 | Kotlin | 0 | 0 | e9bd07770ccf8949f718a02db8d09daf5804273d | 1,886 | aoc-kotlin | Apache License 2.0 |
src/Day03.kt | chrisjwirth | 573,098,264 | false | {"Kotlin": 28380} | fun main() {
fun sharedItem(firstCompartment: CharSequence, secondComponent: CharSequence): Char {
return firstCompartment.first { it in secondComponent }
}
fun sharedItem(first: CharSequence, second: CharSequence, third: CharSequence): Char {
return first.first { it in second && it in third }
}
fun priorityOfSharedItem(sharedItem: Char): Int {
return if (sharedItem.isLowerCase()) {
sharedItem.code - 'a'.code + 1
} else {
sharedItem.code - 'A'.code + 27
}
}
fun part1(input: List<String>): Int {
var sum = 0
input.forEach {
val firstCompartment = it.subSequence(0, it.length.floorDiv(2))
val secondCompartment = it.subSequence(it.length.floorDiv(2), it.length)
sum += priorityOfSharedItem(sharedItem(firstCompartment, secondCompartment))
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
var index = 0
while (index < input.size) {
val first = input[index++]
val second = input[index++]
val third = input[index++]
sum += priorityOfSharedItem(sharedItem(first, second, third))
}
return sum
}
// Test
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
// Final
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d8b1f2a0d0f579dd23fa1dc1f7b156f728152c2d | 1,501 | AdventOfCode2022 | Apache License 2.0 |
src/Day04.kt | esp-er | 573,196,902 | false | {"Kotlin": 29675} | package patriker.day04
import patriker.utils.*
fun main() {
val testInput = readInput("Day04_test")
val input = readInput("Day04_input")
check(solvePart1(testInput) == 2)
println(solvePart1(input))
println(solvePart2(input))
}
fun solvePart1(input: List<String>): Int{
return input.count{ elfPair ->
val pairs = elfPair.split(",")
val firstRange = pairs.first().toRange()
val secondRange = pairs.last().toRange()
firstRange in secondRange || secondRange in firstRange
}
}
fun solvePart2(input: List<String>): Int{
return input.count{ elfPair ->
val pairs = elfPair.split(",")
val firstRange = pairs.first().toRange()
val secondRange = pairs.last().toRange()
firstRange.first in secondRange || secondRange.first in firstRange
}
}
fun String.toRange(): IntRange{
val (start, end) = split("-")
return start.toInt()..end.toInt()
}
operator fun IntRange.contains(other: IntRange): Boolean{
return other.first >= this.first && other.last <= this.last
}
| 0 | Kotlin | 0 | 0 | f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362 | 1,072 | aoc2022 | Apache License 2.0 |
src/main/kotlin/Day23.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | import java.util.*
import kotlin.collections.ArrayList
fun main() {
val input = readFileAsList("Day23")
println(Day23.part1(input))
println(Day23.part2(input))
}
object Day23 {
private val directions: List<Direction> = listOf(Direction.N, Direction.S, Direction.W, Direction.E)
fun part1(input: List<String>): Int {
val grove = mapInput(input)
for (i in 0 until 10) {
val newElves = move(grove, i)
grove.elves = newElves
}
val elvesWidth = grove.maxElfX - grove.minElfX + 1
val elvesHeight = grove.maxElfY - grove.minElfY + 1
val elvesRect = elvesWidth * elvesHeight
return elvesRect - grove.elves.count()
}
fun part2(input: List<String>): Int {
val grove = mapInput(input)
var i = 0
while (true) {
val newElves = move(grove, i)
i++
if (newElves == grove.elves) {
return i
}
grove.elves = newElves
}
}
private fun mapInput(input: List<String>): Grove {
val elves = input.flatMapIndexed { y, line ->
line.mapIndexedNotNull() { x, c ->
if (c == '.') {
return@mapIndexedNotNull null
}
Vector2d(x, y)
}
}.toSet()
return Grove(input.size, elves)
}
private fun move(grove: Grove, i: Int): MutableSet<Vector2d> {
val roundDirections = ArrayList(directions)
Collections.rotate(roundDirections, -1 * i)
val elfProposals = mutableMapOf<Vector2d, Vector2d>()
grove.elves.forEach { elf ->
val noElvesAround = Direction.values().map {
elf + it.offset
}.all {
!grove.elves.contains(it)
}
if (noElvesAround) {
elfProposals[elf] = elf
return@forEach
}
val roundDir = roundDirections.firstOrNull { potentialDirection ->
val next = dirGroups[potentialDirection]!!.map { groupDir -> elf + groupDir.offset }
next.all { !grove.elves.contains(it) }
}
if (roundDir == null) {
// no possible moves, stay where you are
elfProposals[elf] = elf
return@forEach
}
val proposal = elf + roundDir.offset
if (elfProposals.contains(proposal)) {
// another elf wants to go to that position, both stay where they are
elfProposals[elf] = elf
val originalFirstProposingElf = elfProposals[proposal]!!
elfProposals[originalFirstProposingElf] = originalFirstProposingElf
elfProposals.remove(proposal)
} else {
// propose to move to new position
elfProposals[proposal] = elf
}
}
return elfProposals.keys
}
private data class Grove(val size: Int, var elves: Set<Vector2d>) {
val minElfX: Int
get() = elves.minOf { it.x }
val maxElfX: Int
get() = elves.maxOf { it.x }
val minElfY: Int
get() = elves.minOf { it.y }
val maxElfY: Int
get() = elves.maxOf { it.y }
}
private enum class Direction(val offset: Vector2d) {
N(Vector2d(0, -1)),
NE(Vector2d(1, -1)),
NW(Vector2d(-1, -1)),
S(Vector2d(0, 1)),
SE(Vector2d(1, 1)),
SW(Vector2d(-1, 1)),
W(Vector2d(-1, 0)),
E(Vector2d(1, 0)),
}
private val dirGroups: Map<Direction, List<Direction>> = mapOf(
Direction.N to listOf(Direction.N, Direction.NW, Direction.NE),
Direction.S to listOf(Direction.S, Direction.SW, Direction.SE),
Direction.W to listOf(Direction.W, Direction.NW, Direction.SW),
Direction.E to listOf(Direction.E, Direction.SE, Direction.NE),
)
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 3,995 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2023/Day15.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2023
import checkValue
import readInputText
fun main() {
val (year, day) = "2023" to "Day15"
fun String.toSequence() = replace("\n", "").split(",")
fun String.hash() = fold(0) { hash, ch ->
((hash + ch.code) * 17) % 256
}
fun part1(input: String) = input.toSequence().sumOf { it.hash() }
fun part2(input: String): Long {
val sequence = input.toSequence()
val boxes = Array(256) { mutableListOf<Lens>() }
for (step in sequence) {
val operation = if (step.contains('-')) '-' else '='
val (label, focal) = step.split(operation)
val hash = label.hash()
when (operation) {
'=' -> {
val index = boxes[hash].indexOfFirst { it.label == label }
val lens = Lens(label, focal.toInt())
if (index >= 0) {
boxes[hash].removeAt(index)
boxes[hash].add(index, lens)
} else {
boxes[hash].add(lens)
}
}
'-' -> {
boxes[hash].indexOfFirst { it.label == label }.takeIf { it >= 0 }?.also {
boxes[hash].removeAt(it)
}
}
}
}
return boxes.withIndex().sumOf { (boxIndex, lenses) ->
lenses.foldIndexed(0L) { lensIndex, acc, lens ->
acc + (boxIndex + 1) * (lensIndex + 1) * lens.focal
}
}
}
val testInput = readInputText(name = "${day}_test", year = year)
val input = readInputText(name = day, year = year)
checkValue(part1(testInput), 1320)
println(part1(input))
checkValue(part2(testInput), 145)
println(part2(input))
}
data class Lens(val label: String, val focal: Int) | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,873 | aoc-kotlin | Apache License 2.0 |
y2023/src/main/kotlin/adventofcode/y2023/Day04.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
fun main() {
Day04.solve()
}
object Day04 : AdventSolution(2023, 4, "Scratch Cards") {
override fun solvePartOne(input: String) = parse(input).sumOf(Scratchcard::score)
override fun solvePartTwo(input: String): Int {
val cards = parse(input).map(Scratchcard::wins).toList()
val copies = IntArray(cards.size) { 1 }
cards.forEachIndexed { i, wins ->
for (next in i + 1..(i + wins).coerceAtMost(copies.lastIndex)) {
copies[next] += copies[i]
}
}
return copies.sum()
}
}
private fun parse(input: String) = input.lineSequence().map { line ->
val (idStr, own, win) = line.split(":", "|")
Scratchcard(
idStr.substringAfter("Card").trim().toInt(),
own.split(" ").filter(String::isNotBlank).map(String::toInt),
win.split(" ").filter(String::isNotBlank).map(String::toInt).toSet()
)
}
data class Scratchcard(val id: Int, val own: List<Int>, val winning: Set<Int>) {
fun wins() = own.count { it in winning }
fun score() = wins().let { if (it == 0) 0 else 1 shl it - 1 }
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,178 | advent-of-code | MIT License |
src/Day03.kt | zdenekobornik | 572,882,216 | false | null | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val (left, right) = it.chunked(it.length / 2)
val char = left.first { right.contains(it) }
if (char in 'a' .. 'z') {
char.code - 96
} else {
char.code - 38
}
}
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.sumOf { chunk ->
val char = chunk
.map { it.toSet() }
.reduce { acc, chars ->
acc.intersect(chars)
}
.first()
if (char.isLowerCase()) {
(char - 96).code
} else {
(char - 38).code
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
checkResult(part1(testInput), 157)
checkResult(part2(testInput), 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f73e4a32802fa43b90c9d687d3c3247bf089e0e5 | 1,135 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/nosswald/aoc/days/Day15.kt | 7rebux | 722,943,964 | false | {"Kotlin": 34890} | package de.nosswald.aoc.days
import de.nosswald.aoc.Day
// https://adventofcode.com/2023/day/15
object Day15 : Day<Int>(15, "Lens Library") {
private fun appendix1A(str: String): Int {
return str
.map(Char::code)
.fold(0) { acc, next -> (acc + next) * 17 % 256 }
}
override fun partOne(input: List<String>): Int {
return input
.first()
.split(",")
.sumOf(::appendix1A)
}
override fun partTwo(input: List<String>): Int {
val boxes = mutableMapOf<Int, MutableList<String>>()
val focalLengths = mutableMapOf<String, Int>()
input.first().split(",").forEach { instruction ->
if (instruction.contains('-')) {
val label = instruction.split("-").first()
val index = appendix1A(label)
boxes[index]?.remove(label)
} else {
val (label, focalLength) = instruction.split("=")
val index = appendix1A(label)
val box = boxes.getOrPut(index) { mutableListOf() }
if (!box.contains(label)) box.add(label)
focalLengths[label] = focalLength.toInt()
}
}
return boxes.toList().sumOf { (box, values) ->
values.withIndex().sumOf { (slot, label) ->
(box + 1) * (slot + 1) * focalLengths[label]!!
}
}
}
override val partOneTestExamples: Map<List<String>, Int> = mapOf(
listOf("rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7") to 1320
)
override val partTwoTestExamples: Map<List<String>, Int> = mapOf(
listOf("rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7") to 145
)
}
| 0 | Kotlin | 0 | 1 | 398fb9873cceecb2496c79c7adf792bb41ea85d7 | 1,747 | advent-of-code-2023 | MIT License |
2021/08/main.kt | chylex | 433,239,393 | false | null | import Position.BOTTOM
import Position.BOTTOM_LEFT
import Position.BOTTOM_RIGHT
import Position.MIDDLE
import Position.TOP
import Position.TOP_LEFT
import Position.TOP_RIGHT
import java.io.File
import java.util.EnumSet
fun main() {
val records = File("input.txt").readLines().map { line ->
line.split(" | ", limit = 2).map { it.split(' ') }.let { Record(it[0], it[1]) }
}
part1(records)
part2(records)
}
fun part1(records: List<Record>) {
@Suppress("ConvertLambdaToReference")
val segmentCountToDigits = allDigits
.map { it.value to it.positions.size }
.groupBy { it.second }
.mapValues { it.value.map { e -> e.first } }
val uniqueSegmentCountToDigits = segmentCountToDigits
.filterValues { it.size == 1 }
.mapValues { it.value.single() }
val simpleDigitCount = records.sumOf { r -> r.output.count { it.length in uniqueSegmentCountToDigits } }
println("Total appearances of 1,4,7,8: $simpleDigitCount")
}
fun part2(records: List<Record>) {
println("Total output: ${records.sumOf(Record::deduceOutput)}")
}
data class Digit(val value: Int, val positions: EnumSet<Position>)
enum class Position {
TOP,
TOP_LEFT,
TOP_RIGHT,
MIDDLE,
BOTTOM_LEFT,
BOTTOM_RIGHT,
BOTTOM
}
private val allDigits = listOf(
Digit(0, EnumSet.of(TOP, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM)),
Digit(1, EnumSet.of(TOP_RIGHT, BOTTOM_RIGHT)),
Digit(2, EnumSet.of(TOP, TOP_RIGHT, MIDDLE, BOTTOM_LEFT, BOTTOM)),
Digit(3, EnumSet.of(TOP, TOP_RIGHT, MIDDLE, BOTTOM_RIGHT, BOTTOM)),
Digit(4, EnumSet.of(TOP_LEFT, TOP_RIGHT, MIDDLE, BOTTOM_RIGHT)),
Digit(5, EnumSet.of(TOP, TOP_LEFT, MIDDLE, BOTTOM_RIGHT, BOTTOM)),
Digit(6, EnumSet.of(TOP, TOP_LEFT, MIDDLE, BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM)),
Digit(7, EnumSet.of(TOP, TOP_RIGHT, BOTTOM_RIGHT)),
Digit(8, EnumSet.of(TOP, TOP_LEFT, TOP_RIGHT, MIDDLE, BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM)),
Digit(9, EnumSet.of(TOP, TOP_LEFT, TOP_RIGHT, MIDDLE, BOTTOM_RIGHT, BOTTOM)),
)
data class Record(val patterns: List<String>, val output: List<String>) {
private fun deduceMapping(): Map<Char, Position> {
val mapping = mutableMapOf<Char, Position>()
// The digit 1 is made of the top right and bottom right segment.
val patternFor1 = patterns.first { it.length == 2 }
// We can deduce the mapping for both right segments by counting how many times each segment
// appears among all of the digits (top right appears in 8 digits, bottom right in 9 digits).
if (patterns.count { patternFor1[0] in it } == 8) {
mapping[patternFor1[0]] = TOP_RIGHT
mapping[patternFor1[1]] = BOTTOM_RIGHT
}
else {
mapping[patternFor1[1]] = TOP_RIGHT
mapping[patternFor1[0]] = BOTTOM_RIGHT
}
// The digit 7 is made of both right segments, and the top segment.
val patternFor7 = patterns.first { it.length == 3 }
// We can deduce the mapping for the top segment,
// since it is the only segment which is not shared with the digit 1.
mapping[patternFor7.first { it !in patternFor1 }] = TOP
// The digit 4 is made of both right segments, the top left segment, and the middle segment.
// Both right segments are already deduced, so we only want the remaining two segments.
val patternFor4MinusDeduced = patterns.first { it.length == 4 }.toSet().minus(patternFor1.toSet()).toTypedArray()
// We can deduce the mapping for the top left and middle segments by counting how many times each segment
// appears among all of the digits (top left appears in 6 digits, middle in 7 digits).
if (patterns.count { patternFor4MinusDeduced[0] in it } == 6) {
mapping[patternFor4MinusDeduced[0]] = TOP_LEFT
mapping[patternFor4MinusDeduced[1]] = MIDDLE
}
else {
mapping[patternFor4MinusDeduced[1]] = TOP_LEFT
mapping[patternFor4MinusDeduced[0]] = MIDDLE
}
// The digit 8 uses all seven segments, so we use it and remove the five segments we already know,
// keeping the remaining two segments (bottom left, and bottom).
val remainingSegments = patterns.first { it.length == 7 }.toSet().minus(mapping.keys.toSet()).toTypedArray()
// We can deduce the mapping for the bottom left and bottom segments by counting how many times each segment
// appears among all of the digits (bottom left appears in 4 digits, bottom in 7 digits).
if (patterns.count { remainingSegments[0] in it } == 4) {
mapping[remainingSegments[0]] = BOTTOM_LEFT
mapping[remainingSegments[1]] = BOTTOM
}
else {
mapping[remainingSegments[1]] = BOTTOM_LEFT
mapping[remainingSegments[0]] = BOTTOM
}
return mapping
}
fun deduceOutput(): Int {
val mapping = deduceMapping()
return output.fold(0) { total, digit ->
val positions = digit.map(mapping::getValue).toSet()
val value = allDigits.first { it.positions == positions }.value
(total * 10) + value
}
}
}
| 0 | Rust | 0 | 0 | 04e2c35138f59bee0a3edcb7acb31f66e8aa350f | 4,801 | Advent-of-Code | The Unlicense |
src/Day04.kt | touchman | 574,559,057 | false | {"Kotlin": 16512} |
fun main() {
val input = readInput("Day04")
fun part1(input: List<String>) =
input.map {
it.split(",").let {
it[0] to it[1]
}.let {
val firstSplit = it.first.split("-").map(String::toInt)
val secondSplit = it.second.split("-").map(String::toInt)
if ((firstSplit[0] <= secondSplit[0] && firstSplit[1] >= secondSplit[1]) ||
(secondSplit[0] <= firstSplit[0] && secondSplit[1] >= firstSplit[1])) {
1
} else {
0
}
}
}.reduce { acc, i -> acc + i}
fun part2(input: List<String>) =
input.map {
it.split(",").let {
it[0] to it[1]
}.let {
val firstSplit = it.first.split("-").map(String::toInt)
val secondSplit = it.second.split("-").map(String::toInt)
var firstElem = firstSplit[0]
var secondElem = secondSplit[0]
val firstSeq = generateSequence { (firstElem++).takeIf { it <= firstSplit[1] } }.toSet()
val secondSeq = generateSequence { (secondElem++).takeIf { it <= secondSplit[1] } }.toSet()
if (firstSeq.intersect(secondSeq).isNotEmpty() ||
secondSeq.intersect(firstSeq).isNotEmpty()) {
1
} else {
0
}
}
}.reduce { acc, i -> acc + i}
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 4f7402063a4a7651884be77bb9e97828a31459a7 | 1,580 | advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | import java.util.Stack
object Day13 {
fun part1(input: List<List<Item>>) {
input.mapIndexed { i, l ->
val (first, second) = l
first.compareTo(second).takeIf { it == -1 }?.let { i + 1 }
}.filterNotNull().sum().log("part1")
}
fun part2(input: List<List<Item>>) {
val sentinels = listOf(L(L(2)), L(L(6)))
(input.flatten() + sentinels).asSequence().sortedWith(Item.ItemComparator).withIndex()
.filter { (i, l) -> sentinels.any { s -> s.compareTo(l) == 0 } }
.map { it.index + 1 }.reduce(Int::times).log("part2")
}
@JvmStatic
fun main(args: Array<String>) {
val input = downloadAndReadInput("Day13", "\n\n").filter { it.isNotBlank() }
.map { l ->
l.split("\n").filter { it.isNotBlank() }.map { s ->
deserialize(s)
}
}
part1(input)
part2(input)
}
private fun deserialize(s: String): L {
val stack = Stack<L>()
s.removeSurrounding("[", "]").let {
stack.push(L())
var acc = ""
val addAccAndReset = { s: String ->
if (s.isNotBlank()) {
s.toI().let { stack.peek().add(it) }
acc = ""
}
}
it.forEach { c ->
when (c) {
'[' -> stack.push(L())
']' -> {
addAccAndReset(acc)
stack.pop().let { stack.peek().add(it) }
}
else -> {
if (c.isDigit()) acc += c
if (c == ',') {
addAccAndReset(acc)
}
}
}
}
addAccAndReset(acc)
}
return stack.pop()
}
sealed interface Item : Comparable<Item> {
object ItemComparator : Comparator<Item> {
override fun compare(o1: Item, o2: Item): Int {
return o1.compareTo(o2)
}
}
}
data class L(val list: MutableList<Item>) : Item {
constructor(i: Int) : this(mutableListOf(I(i)))
constructor(l: L) : this(mutableListOf(l))
constructor() : this(mutableListOf())
fun add(itm: Item) = list.add(itm)
override fun compareTo(other: Item): Int {
return when (other) {
is I -> compareTo(L(other.item))
is L -> {
var i = 0
var cmp = 0
while (i < list.size) {
val left = list[i]
val right = other.list.getOrNull(i)
if (right == null) {
cmp = 1
break
}
cmp = left.compareTo(right)
if (cmp != 0) {
break
}
i++
}
if (i == list.size && i < other.list.size) {
cmp = -1
}
return cmp
}
}
}
override fun toString(): String = "[${list.joinToString(",") { it.toString() }}]"
}
private fun String.toI() = this.toInt().let { I(it) }
data class I(val item: Int) : Item {
override fun compareTo(other: Item): Int {
return when (other) {
is I -> item.compareTo(other.item)
is L -> L(item).compareTo(other)
}
}
override fun toString(): String = "$item"
}
}
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 3,796 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/executeNameCmds.kt | sam-hoodie | 534,831,633 | false | {"Kotlin": 43732} | fun main() {
val data = parseCongressFile(true)
interpretNameCommand("-get congress.serving.names.shortest.frist", data)
}
fun interpretNameCommand(command: String, data: List<Person>) {
// -get congress.names.shortest.first
// -get congress.names.shortest.last
// -get congress.names.longest.first
// -get congress.names.longest.last
val commandParameters = command.split('.')
if (commandParameters[3] == "shortest") {
if (commandParameters[4] == "first") {
println(" The shortest first name is " + getShortestFirst(data))
return
}
if (commandParameters[4] == "first") {
println(" The shortest last name is " + getShortestLast(data))
return
}
} else if (commandParameters[3] == "longest") {
if (commandParameters[4] == "first") {
println(" The longest first name is " + getLongestFirst(data))
return
}
if (commandParameters[4] == "last") {
println(" The longest last name is " + getLongestLast(data))
return
}
}
printAutocorrect(command)
}
fun getShortestFirst(data: List<Person>): String {
var shortestFirstName = data[1].name.first
for (i in 1 until data.size) {
val currentName = data[i].name.first
if (currentName.length < shortestFirstName.length) {
shortestFirstName = currentName
}
}
return shortestFirstName
}
fun getLongestFirst(data: List<Person>): String {
var longestFirstName = data[1].name.first
for (i in 1 until data.size) {
val currentName = data[i].name.first
if (currentName.length > longestFirstName.length) {
longestFirstName = currentName
}
}
return longestFirstName
}
fun getShortestLast(data: List<Person>): String {
var shortestLastName = data[1].name.last
for (i in 1 until data.size) {
val currentName = data[i].name.last
if (currentName.length < shortestLastName.length) {
shortestLastName = currentName
}
}
return shortestLastName
}
fun getLongestLast(data: List<Person>): String {
var longestLastName = data[1].name.last
for (i in 1 until data.size) {
val currentName = data[i].name.last
if (currentName.length > longestLastName.length) {
longestLastName = currentName
}
}
return longestLastName
} | 0 | Kotlin | 0 | 0 | 9efea9f9eec55c1e61ac1cb11d3e3460f825994b | 2,452 | congress-challenge | Apache License 2.0 |
kotlin/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.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} | /*
* DFS Solution
*/
class Solution {
fun minReorder(n: Int, connections: Array<IntArray>): Int {
val neighbors = ArrayList<ArrayList<Int>>().apply {
for (i in 0 until n)
this.add(ArrayList<Int>())
for ((u,v) in connections) {
this.get(u).apply { this.add(v) }
this.get(v).apply { this.add(u) }
}
}
val edges = HashSet<String>().apply {
for ((u,v) in connections)
this.add("$u:$v")
}
var changes = 0
val visited = BooleanArray(n)
fun dfs(n: Int) {
for (nei in neighbors[n]) {
if (visited[nei] == true)
continue
if ("$nei:$n" !in edges)
changes++
visited[nei] = true
dfs(nei)
}
}
visited[0] = true
dfs(0)
return changes
}
}
/*
* BFS Solution
*/
class Solution {
fun minReorder(n: Int, connections: Array<IntArray>): Int {
// node -> (adjacentNode,isArtificialEdge)
val adjacencyList = mutableMapOf<Int, MutableList<Pair<Int, Boolean>>>()
connections.forEach { (u, v) -> // O(E)
adjacencyList.getOrPut(u) { mutableListOf() }.add(Pair(v, false))
adjacencyList.getOrPut(v) { mutableListOf() }.add(Pair(u, true))
}
val queue = LinkedList<Int>().apply { add(0) }
val visitedNodes = hashSetOf<Int>().apply { add(0) }
var minNumberOfEdgesToReOrient = 0
while (queue.isNotEmpty()) {
val removedNode = queue.remove()
for ((adjacentNode, isConnectedArtificially) in adjacencyList[removedNode] ?: mutableListOf()) {
if (adjacentNode in visitedNodes) continue
if (!isConnectedArtificially) minNumberOfEdgesToReOrient++
visitedNodes.add(adjacentNode)
queue.add(adjacentNode)
}
}
return minNumberOfEdgesToReOrient
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 2,058 | leetcode | MIT License |
src/main/kotlin/days/Day4.kt | hughjdavey | 725,972,063 | false | {"Kotlin": 76988} | package days
class Day4 : Day(4) {
private val cards = inputList.map(this::parseCard)
override fun partOne(): Any {
return cards.sumOf { it.getPoints() }
}
override fun partTwo(): Any {
var cardCount = 0
val cachedWins = cards.associate { it.id to it.getCardWins() }
var cardIds = cards.map { it.id }
while (cardIds.isNotEmpty()) {
cardCount += cardIds.size
cardIds = cardIds.flatMap { id -> cachedWins[id].orEmpty() }
}
return cardCount
}
fun parseCard(str: String): Card {
val colon = str.indexOf(':')
val id = str.substring(str.indexOf(' ') + 1, colon).trim().toInt()
val (winningNumbers, numbers) = str.substring(colon + 2).split('|')
.map { it.split(' ').filter { it.isNotEmpty() }.map { it.toInt() } }
return Card(id, winningNumbers, numbers)
}
data class Card(val id: Int, val winningNumbers: List<Int>, val numbers: List<Int>) {
fun getPoints(): Int {
System.err.println(winningNumbers.count { numbers.contains(it) })
return numbers.fold(0) { points, number -> if (winningNumbers.contains(number)) double(points) else points }
}
fun getCardWins(): List<Int> {
val matches = winningNumbers.count { numbers.contains(it) }
return (0 until matches).map { id.toInt() + 1 + it }
}
private fun double(points: Int) = if (points == 0) 1 else points * 2
}
}
| 0 | Kotlin | 0 | 0 | 330f13d57ef8108f5c605f54b23d04621ed2b3de | 1,513 | aoc-2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/Day3.kt | maldoinc | 726,264,110 | false | {"Kotlin": 14472} | import kotlin.io.path.Path
import kotlin.io.path.readLines
/**
* For part 1, find numbers and for every digit added to the number
* check if there was an adjacent symbol,
* when done keep or discard depending on if a symbol was found.
*/
fun getPart1Nums(input: List<String>): List<Int> {
val res: List<Int> = mutableListOf()
val current = StringBuilder()
var symbolSeen = false
val isSymbol: (Char) -> Boolean = { !(it == '.' || it.isDigit()) }
for (y in input.indices) {
for (x in input[y].indices) {
val char = input[y][x]
if (char == '.' || !char.isDigit()) {
if (symbolSeen && current.isNotEmpty()) {
res.addLast(current.toString().toInt())
}
current.clear()
symbolSeen = false
continue
}
if (char.isDigit()) {
current.append(char)
for (dx in -1..1) {
for (dy in -1..1) {
val xx = x + dx
val yy = y + dy
if (yy in input.indices && xx in input[yy].indices) {
symbolSeen = symbolSeen or isSymbol(input[yy][xx])
}
}
}
}
}
}
if (current.isNotEmpty()) {
res.addLast(current.toString().toInt())
}
return res
}
/**
* Given a star location, find all digits around it and return their product
* only if there's exactly two of them.
*/
fun findGearRatio(input: MutableList<MutableList<Char>>, y: Int, x: Int): Int {
if (input[y][x] != '*') {
return 0
}
val parts: List<Int> = mutableListOf()
for (dx in -1..1) {
for (dy in -1..1) {
val xx = x + dx
val yy = y + dy
if (yy in input.indices && xx in input[y].indices && input[yy][xx].isDigit()) {
val chars = buildString {
var cx = xx
while (cx >= 0 && input[yy][cx].isDigit()) {
append(input[yy][cx])
input[yy][cx] = '.'
cx -= 1
}
reverse()
cx = xx + 1
while (cx < input[yy].size && input[yy][cx].isDigit()) {
append(input[yy][cx])
input[yy][cx] = '.'
cx += 1
}
}
parts.addLast(chars.toInt())
if (parts.size > 2) {
return 0
}
}
}
}
return when (parts.size) {
2 -> parts[0] * parts[1]
else -> 0
}
}
/**
* Part 2 takes the opposite approach to part 1, for every star find all digits around it.
*/
fun getPart2Nums(input: MutableList<MutableList<Char>>): Int =
input.flatMapIndexed { y, row ->
List(row.size) { x -> findGearRatio(input, y, x) }
}.sum()
fun main(args: Array<String>) {
val lines = Path(args[0]).readLines()
println(getPart1Nums(lines).sum())
println(getPart2Nums(lines.map { it.toMutableList() }.toMutableList()))
}
| 0 | Kotlin | 0 | 1 | 47a1ab8185eb6cf16bc012f20af28a4a3fef2f47 | 3,264 | advent-2023 | MIT License |
src/main/kotlin/pl/bizarre/day5_2.kt | gosak | 572,644,357 | false | {"Kotlin": 26456} | package pl.bizarre
import pl.bizarre.common.loadInput
fun main() {
val input = loadInput(5)
println("result ${day5_2(input)}")
}
fun day5_2(input: List<String>): String {
val piles = input.numberOfPiles()
val storage = input.take(piles).map { line ->
line.findCrates(piles)
}.fold((0 until piles).map { mutableListOf<Char>() }) { acc, value ->
value.forEachIndexed { index, char ->
if (char != ' ') {
acc[index] += char
}
}
acc
}.map { it.reversed().toMutableList() }
val orders = input.takeLast(input.size - input.indexOf("") - 1).map { it.toOrder() }
val executor = Day5OrdersExecutor2(storage)
orders.forEach {
executor(it)
}
return executor.printLastCrates()
}
private fun List<String>.numberOfPiles() = this[indexOf("") - 1].count { it != ' ' }
private fun String.findCrates(piles: Int) =
(0 until piles).map {
this[1 + it * 4]
}
data class Day5Move2(
private val cratesToMove: Int,
private val fromPileIndex: Int,
private val toPileIndex: Int,
) : Day5Order() {
override fun invoke(storage: List<MutableList<Char>>) {
val move = storage[fromPileIndex].takeLast(cratesToMove)
storage[toPileIndex].addAll(move)
repeat(cratesToMove) {
storage[fromPileIndex].removeLast()
}
}
companion object {
val regex = "move ([0-9]+) from ([0-9]+) to ([0-9]+)".toRegex()
}
}
class Day5OrdersExecutor2(
private val storage: List<MutableList<Char>>,
) {
operator fun invoke(order: Day5Order) {
order.invoke(storage)
}
fun printLastCrates() = storage.fold("") { acc, chars -> acc + chars.last() }
}
private fun String.toOrder() =
when {
contains("move") -> {
val groups = Day5Move.regex.find(this)!!.groups
Day5Move2(
cratesToMove = groups[1]!!.value.toInt(),
fromPileIndex = groups[2]!!.value.toInt() - 1,
toPileIndex = groups[3]!!.value.toInt() - 1,
)
}
else -> error("Unknown order.")
}
| 0 | Kotlin | 0 | 0 | aaabc56532c4a5b12a9ce23d54c76a2316b933a6 | 2,148 | adventofcode2022 | Apache License 2.0 |
src/Day12.kt | syncd010 | 324,790,559 | false | null | import kotlin.math.abs
class Day12: Day {
private fun convert(input: List<String>) : List<Position> {
val regexp = """<x=([+-]?\d+), y=([+-]?\d+), z=([+-]?\d+)>""".toRegex()
return input.map {
val m = regexp.find(it)!!
return@map Position(m.groupValues[1].toInt(), m.groupValues[2].toInt(), m.groupValues[3].toInt())
}
}
private fun Position.energy() : Int = abs(x) + abs(y) + abs(z)
override fun solvePartOne(input: List<String>): Int {
val positions = convert(input).toMutableList()
val numBodies = positions.size
val velocities = MutableList(numBodies) { Position(0, 0, 0) }
val comb = (0 until numBodies).toSet().combinations(2)
for (step in 1..1000) {
for (c in comb) {
val idx1 = c.elementAt(0)
val idx2 = c.elementAt(1)
val diff = positions[idx1] - positions[idx2]
velocities[idx1] -= diff.sign()
velocities[idx2] += diff.sign()
}
for (i in 0 until positions.size)
positions[i] += velocities[i]
}
return positions.zip(velocities).sumBy { it.first.energy() * it.second.energy() }
}
private fun getKeys(positions: List<Position>, velocities: List<Velocity>): Triple<List<Int>, List<Int>, List<Int>> {
val keyX = mutableListOf<Int>()
val keyY = mutableListOf<Int>()
val keyZ = mutableListOf<Int>()
for (i in positions.indices) {
keyX.add (positions[i].x)
keyX.add (velocities[i].x)
keyY.add (positions[i].y)
keyY.add (velocities[i].y)
keyZ.add (positions[i].z)
keyZ.add (velocities[i].z)
}
return Triple(keyX, keyY, keyZ)
}
override fun solvePartTwo(input: List<String>): Long {
val positions = convert(input).toMutableList()
val numBodies = positions.size
val velocities = MutableList(numBodies) { Position(0, 0, 0) }
val comb = (0 until numBodies).toSet().combinations(2)
val periods = LongArray(3) { -1 }
val seenX = emptyMap<List<Int>, Long>().toMutableMap()
val seenY = emptyMap<List<Int>, Long>().toMutableMap()
val seenZ = emptyMap<List<Int>, Long>().toMutableMap()
var step = 0L
val (keyX, keyY, keyZ) = getKeys(positions, velocities)
seenX[keyX] = step
seenY[keyY] = step
seenZ[keyZ] = step
while (periods.any { it == -1L }) {
step++
for (c in comb) {
val idx1 = c.elementAt(0)
val idx2 = c.elementAt(1)
val diff = positions[idx1] - positions[idx2]
velocities[idx1] -= diff.sign()
velocities[idx2] += diff.sign()
}
for (i in 0 until positions.size)
positions[i] += velocities[i]
val (keyX, keyY, keyZ) = getKeys(positions, velocities)
if (periods[0] == -1L)
if (keyX in seenX) {
periods[0] = step
} else {
seenX[keyX] = step
}
if (periods[1] == -1L)
if (keyY in seenY) {
periods[1] = step
} else {
seenY[keyY] = step
}
if (periods[2] == -1L)
if (keyZ in seenZ) {
periods[2] = step
} else {
seenZ[keyZ] = step
}
}
return lcm(lcm(periods[2], periods[1]), periods[0])
}
} | 0 | Kotlin | 0 | 0 | 11c7c7d6ccd2488186dfc7841078d9db66beb01a | 3,786 | AoC2019 | Apache License 2.0 |
src/Day08.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | fun main() {
fun part1(input: List<String>): Int {
var n = input.size;
var m = input[0].length;
var set = mutableSetOf<Pair<Int, Int>>();
for (i in 0 until n) {
var lst = -1;
for (j in 0 until m) {
var h = input[i][j].code - '0'.code;
if (lst < h) {
set.add(Pair(i, j));
}
lst = lst.coerceAtLeast(h);
}
lst = -1;
for (j in m - 1 downTo 0) {
var h = input[i][j].code - '0'.code;
if (lst < h) {
set.add(Pair(i, j));
}
lst = lst.coerceAtLeast(h);
}
}
for (j in 0 until m) {
var lst = -1;
for (i in 0 until n) {
var h = input[i][j].code - '0'.code;
if (lst < h) {
set.add(Pair(i, j));
}
lst = lst.coerceAtLeast(h);
}
lst = -1;
for (i in n - 1 downTo 0) {
var h = input[i][j].code - '0'.code;
if (lst < h) {
set.add(Pair(i, j));
}
lst = lst.coerceAtLeast(h);
}
}
return set.size;
}
fun part2(input: List<String>): Int {
var n = input.size;
var m = input[0].length;
var maxScore = 0;
var dy = listOf<Int>(1, 0, -1, 0);
var dx = listOf<Int>(0, 1, 0, -1);
for (i in 0 until n) {
for (j in 0 until m) {
var score = 1;
var h = input[i][j].code - '0'.code;
for (k in 0 until 4) {
var y = i + dy[k];
var x = j + dx[k];
var dist = 0;
while (y in 0 until n && x in 0 until m) {
dist++;
var h2 = input[y][x].code - '0'.code;
if (h2 >= h) break;
y += dy[k];
x += dx[k];
}
score *= dist;
}
maxScore = maxScore.coerceAtLeast(score);
}
}
return maxScore;
}
val input = readInput("Day08")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 2,399 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SuccessfulPairs.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.TreeMap
/**
* 2300. Successful Pairs of Spells and Potions
* @see <a href="https://leetcode.com/problems/successful-pairs-of-spells-and-potions/">Source</a>
*/
fun interface SuccessfulPairs {
operator fun invoke(spells: IntArray, potions: IntArray, success: Long): IntArray
}
/**
* Complexity
* Time O(mlogm + nlogm)
* Space O(n)
*/
class SuccessfulPairsSF : SuccessfulPairs {
override operator fun invoke(spells: IntArray, potions: IntArray, success: Long): IntArray {
potions.sort()
val map = TreeMap<Long, Int>()
map[Long.MAX_VALUE] = potions.size
for (i in potions.size - 1 downTo 0) {
map[potions[i].toLong()] = i
}
for (i in spells.indices) {
val need = (success + spells[i] - 1) / spells[i]
spells[i] = potions.size - map.ceilingEntry(need).value
}
return spells
}
}
/**
* Solution II: Two Sum
* Time O(nlogn + mlogm)
* Space O(n)
*/
class SuccessfulPairsTwoSum : SuccessfulPairs {
override operator fun invoke(spells: IntArray, potions: IntArray, success: Long): IntArray {
val spells0 = spells.clone()
potions.sort()
spells.sort()
val count = HashMap<Int, Int>()
val n: Int = spells.size
val m: Int = potions.size
var j = m - 1
val res = IntArray(n)
for (i in 0 until n) {
while (j >= 0 && 1L * spells[i] * potions[j] >= success) j--
count[spells[i]] = m - j - 1
}
for (i in 0 until n) {
res[i] = count[spells0[i]]!!
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,276 | kotlab | Apache License 2.0 |
src/Day02.kt | MisterTeatime | 561,848,263 | false | {"Kotlin": 20300} | fun main() {
fun part1(input: List<String>): Int {
return input.fold(0) { total, gift ->
val (length, width, height) = gift.split("x").map { it.toInt() }
val side1 = length * width
val side2 = width * height
val side3 = height * length
total + 2 * side1 + 2 * side2 + 2 * side3 + minOf(side1, side2, side3)
}
}
fun part2(input: List<String>): Int {
return input.fold(0) { total, gift ->
val (length, width, height) = gift.split("x").map { it.toInt() }.sorted()
total + (length + length + width + width) + (length * width * height)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part2(testInput) == 48)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d684bd252a9c6e93106bdd8b6f95a45c9924aed6 | 912 | AoC2015 | Apache License 2.0 |
src/day03/Solution.kt | abhabongse | 576,594,038 | false | {"Kotlin": 63915} | /* Solution to Day 3: Rucksack Reorganization
* https://adventofcode.com/2022/day/3
*/
package day03
import java.io.File
fun main() {
val fileName =
// "day03_sample.txt"
"day03_input.txt"
val rucksacks = readInput(fileName)
// Part 1: sum of priorities for item types
// that appear in both compartments of each rucksack
val p1SumPriorities = rucksacks
.asSequence()
.map { it.firstCompartment.toSet() intersect it.secondCompartment.toSet() }
.flatten()
.map(ItemPriority::lookup)
.sum()
println("Part 1: $p1SumPriorities")
// Part 2: sum of priorities for item types
// that appear in each group of three consecutive rucksacks
val p2SumPriorities = rucksacks
.asSequence()
.chunked(3)
.map { it[0].content.toSet() intersect it[1].content.toSet() intersect it[2].content.toSet() }
.flatten()
.map(ItemPriority::lookup)
.sum()
println("Part 2: $p2SumPriorities")
}
/**
* Reads and parses input data according to the problem statement.
*/
fun readInput(fileName: String): List<Rucksack> {
return File("inputs", fileName)
.readLines()
.asSequence()
.map { Rucksack(it.trim()) }
.toList()
}
| 0 | Kotlin | 0 | 0 | 8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb | 1,276 | aoc2022-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2018/FourDimensionalAdventure.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2018
import komu.adventofcode.utils.nonEmptyLines
import kotlin.math.abs
fun fourDimensionalAdventure1(input: String): Int {
val stars = input.nonEmptyLines().map { Point4.parse(it) }
val constellations = stars.map { Constellation(listOf(it)) }.toMutableList()
do {
val oldSize = constellations.size
mergeConstellations(constellations)
} while (oldSize != constellations.size)
return constellations.size
}
private fun mergeConstellations(constellations: MutableList<Constellation>) {
for ((i, c1) in constellations.withIndex()) {
for (j in i + 1..constellations.lastIndex) {
val c2 = constellations[j]
if (c1.isSameAs(c2)) {
constellations.removeAt(j)
constellations.removeAt(i)
constellations.add(c1.merge(c2))
return
}
}
}
}
private class Constellation(val stars: List<Point4>) {
fun isSameAs(c: Constellation): Boolean =
stars.any { s1 -> c.stars.any { s2 -> s1.manhattanDistance(s2) <= 3 } }
fun merge(c: Constellation): Constellation {
return Constellation(stars + c.stars)
}
}
private data class Point4(val x: Int, val y: Int, val z: Int, val w: Int) {
override fun toString() = "<$x,$y,$z,$w>"
fun manhattanDistance(p: Point4): Int =
abs(x - p.x) + abs(y - p.y) + abs(z - p.z) + abs(w - p.w)
companion object {
private val regex = Regex("""(-?\d+),(-?\d+),(-?\d+),(-?\d+)""")
fun parse(s: String): Point4 {
val (x, y, z, w) = regex.matchEntire(s)?.destructured ?: error("no match '$s'")
return Point4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
}
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,761 | advent-of-code | MIT License |
advent/src/test/kotlin/org/elwaxoro/advent/y2015/Dec15.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2015
import org.elwaxoro.advent.PuzzleDayTester
import org.elwaxoro.advent.merge
import org.elwaxoro.advent.plusNull
class Dec15 : PuzzleDayTester(15, 2015) {
override fun part1(): Any = expandScoops(100L, mapOf(), parse(), null) ?: -1
override fun part2(): Any = expandScoops(100L, mapOf(), parse(), 500) ?: -1
private fun expandScoops(
remainingScoops: Long,
scooped: Map<Ingredient, Long>,
unscooped: List<Ingredient>,
targetCalories: Long?
): Long? =
if (unscooped.isEmpty()) {
// base case: all scoops are scooped
scooped.toMap().score().takeIf { targetCalories == null || scooped.calories() == targetCalories }
} else if (targetCalories != null && scooped.calories() > targetCalories) {
// base case: over calorie limit
null
} else {
(0..remainingScoops).mapNotNull {
expandScoops(
remainingScoops - it,
scooped.plus(unscooped.first() to it),
unscooped.drop(1),
targetCalories
)
}.maxOrNull()
}
private fun Map<Ingredient, Long>.calories(): Long = entries.sumOf { (ingredient, scoops) ->
ingredient.attributes.entries.single { it.key == "calories" }.value * scoops
}
private fun Map<Ingredient, Long>.score(): Long = entries.map { (ingredient, scoops) ->
ingredient.attributes.map { it.key to it.value * scoops }.toMap()
}.merge(Long::plusNull)
.filter { it.value > 0 && it.key != "calories" }.values.fold(1L) { acc, score -> acc * score }
private fun parse() = load().map {
it.split(": ").let { (name, attributes) ->
Ingredient(name, attributes.split(", ").associate {
it.split(" ").let { (attr, value) ->
attr to value.toLong()
}
})
}
}
data class Ingredient(val name: String, val attributes: Map<String, Long>)
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,068 | advent-of-code | MIT License |
src/Day02.kt | uberbinge | 572,972,800 | false | {"Kotlin": 7404} | fun main() {
firstProblem()
secondProblem()
}
fun firstProblem() {
val input = readLines("Day02")
var sum = 0
val newInput = input.asSequence().map { it.replace("A", "rock") }.map { it.replace("B", "paper") }.map { it ->
it.replace("C", "scissors")
}.map { it.replace("X", "rock") }.map { it.replace("Y", "paper") }.map {
it.replace("Z", "scissors")
}.toList()
newInput.forEach {
val first = it.split(" ")[0]
val second = it.split(" ")[1]
// check winLoseOrDraw
sum += checkWinLoseOrDraw(second, first)
// check if second is rock, paper or scissors and add to sum 1,2 or 3 respectively
sum += when (second) {
"rock" -> {
1
}
"paper" -> {
2
}
else -> {
3
}
}
}
println(sum)
check(13924 == sum)
}
fun secondProblem() {
val input = readLines("Day02")
var sum = 0
val newInput = input.asSequence().map { it.replace("A", "rock") }.map { it.replace("B", "paper") }.map { it ->
it.replace("C", "scissors")
}.map { it.replace("X", "rock") }.map { it.replace("Y", "paper") }.map {
it.replace("Z", "scissors")
}.toList()
newInput.forEach {
val first = it.split(" ")[0]
val convertedMove = when (it.split(" ")[1]) {
"rock" -> {
convertToLosingMove(first)
}
"paper" -> {
convertToDrawMove(first)
}
else -> {
convertToWinningMove(first)
}
}
// check winLoseOrDraw
sum += checkWinLoseOrDraw(convertedMove, first)
// check if second is rock, paper or scissors and add to sum 1,2 or 3 respectively
sum += when (convertedMove) {
"rock" -> {
1
}
"paper" -> {
2
}
else -> {
3
}
}
}
println(sum)
check(13448 == sum)
}
fun checkWinLoseOrDraw(player1: String, player2: String): Int {
return when {
player1 == player2 -> 3
player1 == "rock" && player2 == "scissors" -> 6
player1 == "rock" && player2 == "paper" -> 0
player1 == "paper" && player2 == "rock" -> 6
player1 == "paper" && player2 == "scissors" -> 0
player1 == "scissors" && player2 == "paper" -> 6
player1 == "scissors" && player2 == "rock" -> 0
else -> 3
}
}
fun convertToWinningMove(input: String): String {
return when (input) {
"rock" -> "paper"
"paper" -> "scissors"
"scissors" -> "rock"
else -> throw IllegalArgumentException("Invalid input")
}
}
// create a function which takes a string containing rock paper or scissors and returns what is needed to draw
fun convertToDrawMove(input: String): String {
return when (input) {
"rock" -> "rock"
"paper" -> "paper"
"scissors" -> "scissors"
else -> throw IllegalArgumentException("Invalid input")
}
}
// create a function which takes a string containing rock paper or scissors and returns what is needed to lose
fun convertToLosingMove(input: String): String {
return when (input) {
"rock" -> "scissors"
"paper" -> "rock"
"scissors" -> "paper"
else -> throw IllegalArgumentException("Invalid input")
}
}
| 0 | Kotlin | 0 | 0 | ef57861156ac4c1a097fabe03322edcfa4d2d714 | 3,495 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/adventofcode/util/graph/Graphs.kt | jwcarman | 731,408,177 | false | {"Kotlin": 183494} | /*
* Copyright (c) 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 adventofcode.util.graph
import java.util.*
private fun compareDoubles(left: Double, right: Double): Int {
if (left < right) {
return -1
}
if (right < left) {
return 1
}
return 0
}
object Graphs {
fun <V> shortestPaths(
start: V,
vertices: Set<V>,
neighbors: (V) -> List<V>,
weight: (V, V) -> Double
): ShortestPaths<V> {
val pred = mutableMapOf<V, V>()
val dist = mutableMapOf<V, Double>()
val visited = mutableSetOf<V>()
vertices.forEach { vertex -> dist[vertex] = Double.POSITIVE_INFINITY }
dist[start] = 0.0
val queue = PriorityQueue { l: V, r: V -> compareDoubles(dist[l]!!, dist[r]!!) }
queue.add(start)
while (queue.isNotEmpty()) {
val vertex = queue.poll()
visited.add(vertex)
val distanceToVertex = dist[vertex]!!
neighbors(vertex).filter { it !in visited }.forEach { neighbor ->
val distanceThroughVertex = distanceToVertex + weight(vertex, neighbor)
if (distanceThroughVertex < dist[neighbor]!!) {
pred[neighbor] = vertex
dist[neighbor] = distanceThroughVertex
queue.add(neighbor)
}
}
}
return ShortestPaths(start, dist, pred)
}
private data class Reachable<V>(val steps: Int, val vertex: V)
fun <V> reachable(start: V, maxSteps: Int = Int.MAX_VALUE, neighbors: (V) -> List<V>): Set<V> {
val visited = mutableSetOf<V>()
val queue = mutableListOf(Reachable(0, start))
while (queue.isNotEmpty()) {
val reachable = queue.removeLast()
visited += reachable.vertex
if (reachable.steps < maxSteps) {
val ns = neighbors(reachable.vertex)
.filter { it !in visited }
.map { Reachable(reachable.steps + 1, it) }
queue.addAll(ns)
}
}
return visited
}
fun <V> dfs(start: V, end: V, neighbors: (V) -> List<V>): List<V> {
return search(start, end, neighbors) { list, element -> list.add(0, element) }
}
fun <V> bfs(start: V, end: V, neighbors: (V) -> List<V>): List<V> {
return search(start, end, neighbors) { list, element -> list.add(element) }
}
private fun <V> search(
start: V,
end: V,
neighbors: (V) -> List<V>,
add: (MutableList<List<V>>, List<V>) -> Unit
): List<V> {
val visited = mutableSetOf<V>()
visited += start
val list = mutableListOf<List<V>>()
add(list, listOf(start))
while (list.isNotEmpty()) {
val current = list.removeFirst()
val terminus = current.last()
if (terminus == end) {
return current
}
neighbors(terminus).filter { it !in visited }.forEach { n ->
visited += n
add(list, current + n)
}
}
return listOf()
}
}
| 0 | Kotlin | 0 | 0 | dfb226e92a03323ad48c50d7e970d2a745b479bb | 3,703 | adventofcode2023 | Apache License 2.0 |
src/main/kotlin/currentLegislatorsCmds.kt | sam-hoodie | 534,831,633 | false | {"Kotlin": 43732} | import kotlin.collections.HashMap
fun interpretCurrentCommands(command: String, data: List<Person>) {
val cmdParts = command.split(' ')[1].split('.')
val stateToFind = stateToAbbreviation(cmdParts[3].lowercase())
var legislators = getLegislators(data, stateToFind, command)
if (legislators.isNotEmpty()) {
legislators = legislators.toSet().toList() as ArrayList<List<String>>
if (cmdParts[0] != "house") {
for (i in legislators.indices) {
when (cmdParts[0]) {
"senate" -> println(" " + legislators[i][0])
"congress" -> println(" " + legislators[i][0] + " (" + legislators[i][1] + ")")
}
}
return
} else if (cmdParts[0] == "house") {
val sorted = sortByDistrict(legislators)
for (i in sorted.indices) {
val district = sorted[i][1]
println(" " + sorted[i][0] + " (District " + district + ")")
}
return
}
}
printAutocorrect(command)
}
fun getLegislators(data: List<Person>, stateToFind: String, command: String): List<List<String>> {
val cmdParts = command.split(' ')[1].split('.')
val legislators = arrayListOf<List<String>>()
for (i in data.indices) {
val terms = data[i].terms
if (terms[terms.size - 1].state == stateToFind) {
if (cmdParts[0] == "congress") {
if (terms[terms.size - 1].type == "rep") {
val partToAdd = listOf((data[i].name.first + " " + data[i].name.last), "House")
legislators.add(partToAdd)
} else {
val partToAdd = listOf((data[i].name.first + " " + data[i].name.last), "Senate")
legislators.add(partToAdd)
}
}
if (cmdParts[0] == "senate") {
if (terms[terms.size - 1].type == "sen") {
val partToAdd = listOf((data[i].name.first + " " + data[i].name.last))
legislators.add(partToAdd)
}
}
if (cmdParts[0] == "house") {
if (terms[terms.size - 1].type == "rep") {
val partToAdd = listOf(
(data[i].name.first + " " + data[i].name.last),
terms[terms.size - 1].district.toString()
)
legislators.add(partToAdd)
}
}
}
}
return legislators
}
fun sortByDistrict(input: List<List<String>>): List<List<String>> {
var district = 1
val result = arrayListOf<List<String>>()
while (result.size != input.size) {
for (i in input.indices) {
if (input[i][1].toInt() == district) {
result.add(input[i])
}
}
district++
}
return result
}
fun stateToAbbreviation(state: String): String {
val states = HashMap<String, String>()
states["alabama"] = "AL"
states["alaska"] = "AK"
states["alberta"] = "AB"
states["american_samoa"] = "AS"
states["arizona"] = "AZ"
states["arkansas"] = "AR"
states["british_columbia"] = "BC"
states["california"] = "CA"
states["colorado"] = "CO"
states["connecticut"] = "CT"
states["delaware"] = "DE"
states["district_of_columbia"] = "DC"
states["florida"] = "FL"
states["georgia"] = "GA"
states["guam"] = "GU"
states["hawaii"] = "HI"
states["idaho"] = "ID"
states["illinois"] = "IL"
states["indiana"] = "IN"
states["iowa"] = "IA"
states["kansas"] = "KS"
states["kentucky"] = "KY"
states["louisiana"] = "LA"
states["maine"] = "ME"
states["manitoba"] = "MB"
states["maryland"] = "MD"
states["massachusetts"] = "MA"
states["michigan"] = "MI"
states["minnesota"] = "MN"
states["mississippi"] = "MS"
states["missouri"] = "MO"
states["montana"] = "MT"
states["nebraska"] = "NE"
states["nevada"] = "NV"
states["new_brunswick"] = "NB"
states["new_hampshire"] = "NH"
states["new_jersey"] = "NJ"
states["new_mexico"] = "NM"
states["new_york"] = "NY"
states["newfoundland"] = "NF"
states["north_carolina"] = "NC"
states["north_dakota"] = "ND"
states["northwest_territories"] = "NT"
states["nova_scotia"] = "NS"
states["nunavut"] = "NU"
states["ohio"] = "OH"
states["oklahoma"] = "OK"
states["ontario"] = "ON"
states["oregon"] = "OR"
states["pennsylvania"] = "PA"
states["puerto_rico"] = "PR"
states["quebec"] = "QC"
states["rhode_island"] = "RI"
states["saskatchewan"] = "SK"
states["south_carolina"] = "SC"
states["south_dakota"] = "SD"
states["tennessee"] = "TN"
states["texas"] = "TX"
states["utah"] = "UT"
states["vermont"] = "VT"
states["virgin_islands"] = "VI"
states["virginia"] = "VA"
states["washington"] = "WA"
states["west_virginia"] = "WV"
states["wisconsin"] = "WI"
states["wyoming"] = "WY"
states["yukon_territory"] = "YT"
return states[state].toString()
} | 0 | Kotlin | 0 | 0 | 9efea9f9eec55c1e61ac1cb11d3e3460f825994b | 5,148 | congress-challenge | Apache License 2.0 |
src/shreckye/coursera/algorithms/Course 1 Programming Assignment #2.kts | ShreckYe | 205,871,625 | false | {"Kotlin": 72136} | package shreckye.coursera.algorithms
import java.io.File
import kotlin.test.assertEquals
val filename = args[0]
val integers = File(filename).useLines { it.map(String::toInt).toIntArray(100_000) }
fun mergeSortAndCountNumInversions(
integers: IntArray,
left: Int = 0, right: Int = integers.size
): Pair<IntArray, Long> {
val size = right - left
if (size == 0)
return Pair(IntArray(0), 0)
if (size == 1)
return Pair(IntArray(1) { integers[left] }, 0)
val half = size / 2
val rightHalf = size - half
val mid = left + half
val (leftSortedIntegers, numLeftInversions) = mergeSortAndCountNumInversions(integers, left, mid)
val (rightSortedIntegers, numRightInversions) = mergeSortAndCountNumInversions(integers, mid, right)
val sortedIntegers = IntArray(size)
var i = 0
var j = 0
var numSplitInversions = 0L
while (i < half && j < rightHalf) {
// Equal is not needed as there no repeated values
if (leftSortedIntegers[i] <= rightSortedIntegers[j]) {
sortedIntegers[i + j] = leftSortedIntegers[i++]
numSplitInversions += j
} else {
sortedIntegers[i + j] = rightSortedIntegers[j++]
}
}
numSplitInversions += (half - i) * j
while (i < half) sortedIntegers[i + j] = leftSortedIntegers[i++]
while (j < rightHalf) sortedIntegers[i + j] = rightSortedIntegers[j++]
//println(leftSortedIntegers.contentToString() + rightSortedIntegers.contentToString() + sortedIntegers.contentToString())
return Pair(sortedIntegers, numLeftInversions + numRightInversions + numSplitInversions)
}
println(mergeSortAndCountNumInversions(integers).second)
// Test cases
for (n in 1 until 1024) {
assertEquals(0L, mergeSortAndCountNumInversions(IntArray(n) { it }).second, "n = $n")
val nL = n.toLong()
assertEquals(nL * (nL - 1) / 2, mergeSortAndCountNumInversions(IntArray(n) { n - it }).second, "n = $n")
} | 0 | Kotlin | 1 | 2 | 1746af789d016a26f3442f9bf47dc5ab10f49611 | 1,965 | coursera-stanford-algorithms-solutions-kotlin | MIT License |
src/Day03.kt | 6234456 | 572,616,769 | false | {"Kotlin": 39979} | fun main() {
val judge: (Char)->Int = {
if (it in 'a'..'z') {
it - 'a' + 1
} else{
it - 'A' + 27
}
}
fun part1(input: List<String>): Int {
return input.map {
val a = it.trim().toCharArray()
val l = a.size / 2
val m = mutableMapOf<Char, Int>()
var ret = -1
a.forEachIndexed { index, c ->
if (index < l){
m[c] = m.getOrDefault(c, 0) + 1
}else{
if (m.containsKey(c)){
ret = judge(c)
return@forEachIndexed
}
}
}
ret
}.fold(0){
acc, i ->
acc + i
}
}
fun part2(input: List<String>): Int {
var m = setOf<Char>()
return input.mapIndexed {
i, s ->
val a = s.trim().toCharArray()
var ret = 0
if (i.mod(3) == 0){
m = a.toSet()
}else if (i.mod(3) == 1){
m = m.intersect(a.toSet())
}else{
a.forEach {
if (it in m){
ret = judge(it)
return@forEach
}
}
}
ret
}.fold(0){
acc, i ->
acc + i
}
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b6d683e0900ab2136537089e2392b96905652c4e | 1,530 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/kt/kotlinalgs/app/kickstart/nov22/Electricity.ws.kts | sjaindl | 384,471,324 | false | null | var line = 0
var args: Array<String> = arrayOf()
fun readLine(): String? {
val result = args[line]
line++
return result
}
// https://codingcompetitions.withgoogle.com/kickstart/round/00000000008cb1b6/0000000000c47c8e#problem
// O(E + V) time, O(E + V) space (graph)
fun main(mainArgs: Array<String>) {
args = mainArgs
line = 0
val testCases = readLine()?.toIntOrNull() ?: 0
for (testCase in 1 until testCases + 1) {
val numJunctions = readLine()?.toIntOrNull() ?: return
val weights: List<Int> = readLine()?.split(" ")?.mapNotNull { it.toIntOrNull() } ?: listOf()
val graph = buildGraph(numJunctions, weights) ?: return
// DFS
var maxReactivated = 0
for (junction in 1 until numJunctions + 1) {
maxReactivated = Math.max(maxReactivated, dfs(junction, graph))
}
println("Case #$testCase: $maxReactivated")
}
}
fun dfs(junction: Int, graph: DirectedWeightedGraph): Int {
val vertice = graph.getVertice(junction)
if (vertice.reachable != 0) return vertice.reachable
vertice.reachable = 1
graph.neighbours(junction).forEach {
vertice.reachable += dfs(it.num, graph)
}
return vertice.reachable
}
fun buildGraph(numJunctions: Int, weights: List<Int>): DirectedWeightedGraph? {
val vertices: MutableList<Vertice> = mutableListOf()
for (index in 1 until numJunctions + 1) {
val vertice = Vertice(index, weights[index - 1])
vertices.add(vertice)
}
val graph = DirectedWeightedGraph(vertices)
// n-1 edges
for (index in 0 until numJunctions - 1) {
val (from, to) = readLine()?.split(" ")?.map { it.toInt() } ?: return null
graph.addEdge(vertices[from - 1], vertices[to - 1])
}
return graph
}
class Vertice(val num: Int, val weight: Int, var reachable: Int = 0)
class DirectedWeightedGraph(val vertices: List<Vertice>) {
val adjList: MutableMap<Vertice, MutableList<Vertice>> = mutableMapOf()
fun addEdge(from: Vertice, to: Vertice) {
if (from.weight == to.weight) return // no valid edge!
if (from.weight > to.weight) {
val list = adjList.getOrDefault(from, mutableListOf())
list.add(to)
adjList[from] = list
} else {
val list = adjList.getOrDefault(to, mutableListOf())
list.add(from)
adjList[to] = list
}
}
fun getVertice(junction: Int): Vertice {
return vertices[junction - 1]
}
fun neighbours(junction: Int): List<Vertice> {
val vertice = getVertice(junction)
return adjList.getOrDefault(vertice, mutableListOf())
}
}
main(
arrayOf(
"2",
"5",
"1 2 3 4 3",
"1 3",
"2 3",
"4 3",
"4 5",
"6",
"1 2 3 3 1 4",
"3 1",
"3 2",
"3 4",
"4 5",
"1 6"
)
)
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 2,938 | KotlinAlgs | MIT License |
aoc-2023/src/main/kotlin/aoc/aoc17.kts | triathematician | 576,590,518 | false | {"Kotlin": 615974} | import aoc.AocParser.Companion.parselines
import aoc.*
import aoc.util.*
val testInput = """
2413432311323
3215453535623
3255245654254
3446585845452
4546657867536
1438598798454
4457876987766
3637877979653
4654967986887
4564679986453
1224686865563
2546548887735
4322674655533
""".parselines
fun List<String>.parse() = map { it.map { it.digitToInt() } }
class SearchPath(val grid: List<List<Int>>, val dirs: List<Coord>, val pos: List<Coord>) {
val heatLoss = pos.drop(1).sumOf { grid[it] }
val distToEnd = (grid.size - 1 - pos.last().y) + (grid[0].size - 1 - pos.last().x)
val pathScore = heatLoss + 16 * distToEnd / 7
private val validDirections: List<Coord>
init {
if (dirs.isEmpty()) {
validDirections = listOf(RIGHT, DOWN)
} else {
val last = dirs.last()
val last3 = dirs.takeLast(3)
val turnDirs = if (last == UP || last == DOWN) listOf(LEFT, RIGHT) else listOf(UP, DOWN)
val dirs = if (last3.size == 3 && last3.toSet().size == 1) {
turnDirs
} else {
turnDirs + last
}
validDirections = dirs.filter { dir ->
val nextPos = pos.last() + dir
nextPos !in pos && nextPos.x in grid[0].indices && nextPos.y in grid.indices
}
}
}
/** Get set of next paths for part 1. */
fun nextPaths() = validDirections.map { dir ->
val nextPos = pos.last() + dir
SearchPath(grid, dirs + dir, pos + nextPos)
}
/** Get set of next paths for part 2, where you have to go 4-10 blocks in one direction before changing. */
fun nextPathsUltra(): List<SearchPath> {
return when {
dirs.isEmpty() -> nextPathsUltraRight() + nextPathsUltraDown()
dirs.last() in setOf(UP, DOWN) -> nextPathsUltraLeft() + nextPathsUltraRight()
else -> nextPathsUltraUp() + nextPathsUltraDown()
}
}
private fun nextPathsUltraLeft(): List<SearchPath> {
val lastPos = pos.last()
val searchLeft = lastPos.x - 4 >= 0
return if (searchLeft) {
(4..10).filter { lastPos.x - it >= 0 }.map {
val newDirs = (1..it).map { LEFT }
val newPos = (1..it).map { Coord(lastPos.x - it, lastPos.y) }
SearchPath(grid, dirs + newDirs, pos + newPos)
}
} else {
listOf()
}
}
private fun nextPathsUltraRight(): List<SearchPath> {
val lastPos = pos.last()
val gridCols = grid[0].size
val searchRight = lastPos.x + 4 <= gridCols - 1
return if (searchRight) {
(4..10).filter { lastPos.x + it <= gridCols - 1 }.map {
val newDirs = (1..it).map { RIGHT }
val newPos = (1..it).map { Coord(lastPos.x + it, lastPos.y) }
SearchPath(grid, dirs + newDirs, pos + newPos)
}
} else {
listOf()
}
}
private fun nextPathsUltraUp(): List<SearchPath> {
val lastPos = pos.last()
val searchUp = lastPos.y - 4 >= 0
return if (searchUp) {
(4..10).filter { lastPos.y - it >= 0 }.map {
val newDirs = (1..it).map { UP }
val newPos = (1..it).map { Coord(lastPos.x, lastPos.y - it) }
SearchPath(grid, dirs + newDirs, pos + newPos)
}
} else {
listOf()
}
}
private fun nextPathsUltraDown(): List<SearchPath> {
val lastPos = pos.last()
val searchDown = lastPos.y + 4 <= grid.size - 1
return if (searchDown) {
(4..10).filter { lastPos.y + it <= grid.size - 1 }.map {
val newDirs = (1..it).map { DOWN }
val newPos = (1..it).map { Coord(lastPos.x, lastPos.y + it) }
SearchPath(grid, dirs + newDirs, pos + newPos)
}
} else {
listOf()
}.filter {
it.pos.last() !in it.pos.dropLast(1)
}
}
}
// part 1
val TAKE_N = 1000
val REPORT_ITERS = 1000
val REPORT_ITERS_2 = 50
val START_HEAT_LOSS = 1000
val START_HEAT_LOSS_2 = 1000
val LAST_PATH_2 = 15
val bef = ANSI_CYAN
val aft = ANSI_RESET
fun List<String>.part1(): Int {
return 0
val grid = parse()
val coord0 = Coord(0, 0)
val coordN = Coord(grid[0].size - 1, grid.size - 1)
val path = SearchPath(grid, listOf(), listOf(coord0))
// store best paths by direction entering
val bestPaths = mutableMapOf(
coord0 to mutableMapOf(listOf<Coord>() to path)
)
println("Target: $bef$coordN$aft EstimatedHeatLoss: $bef${path.pathScore}$aft StartHeatLoss: $bef$START_HEAT_LOSS$aft")
val paths = mutableSetOf(path)
var i = 0
var minHeatLoss = START_HEAT_LOSS
while (paths.isNotEmpty()) {
val sorted = paths.sortedBy { it.pathScore }
val first100 = sorted.take(TAKE_N)
val pathsToSearchNow = first100.flatMap { it.nextPaths() }
val nextPaths = pathsToSearchNow.filter { newPath ->
val last = newPath.pos.last()
val last3 = newPath.dirs.takeLast(4)
val curBest = bestPaths[last]?.get(last3)
if (last == coordN) {
bestPaths.putIfAbsent(last, mutableMapOf())
bestPaths[last]!![last3] = newPath
false
} else if (newPath.heatLoss > minHeatLoss) {
false
} else if (curBest == null || newPath.pathScore < curBest.pathScore) {
bestPaths.putIfAbsent(last, mutableMapOf())
bestPaths[last]!![last3] = newPath
true
} else {
false
}
}
paths.removeAll(first100)
paths.removeAll { it.heatLoss > minHeatLoss }
paths.addAll(nextPaths)
i++
val heatloss = bestPaths[coordN]?.values?.minOfOrNull { it.heatLoss }
if (i % REPORT_ITERS == 0 || paths.isEmpty() || (heatloss != null && heatloss < minHeatLoss)) {
if (heatloss != null) minHeatLoss = heatloss
printProgress(paths, pathsToSearchNow, nextPaths, bestPaths, coordN, i)
}
}
println("Total search iterations: $i")
return bestPaths[coordN]!!.values.minOf { it.heatLoss }
}
fun printProgress(paths: Set<SearchPath>, pathsToSearchNow: List<SearchPath>, nextPaths: List<SearchPath>, bestPaths: MutableMap<Coord, MutableMap<List<Coord>, SearchPath>>, coordN: Coord, i: Int) {
val minXY = paths.minOfOrNull { it.pos.last().x + it.pos.last().y }
print("Search iteration: $bef$i$aft")
print(" PathsToSearch: $bef${paths.size}$aft")
print(" MinX+Y_Remaining: $bef$minXY$aft")
print(" HeatLoss: $bef" + bestPaths[coordN]?.values?.let { "${it.minOf { it.heatLoss }}..${it.maxOf { it.heatLoss }}$aft" })
print(" Lengths: $bef" + bestPaths[coordN]?.values?.let { "${it.minOf { it.pos.size }}..${it.maxOf { it.pos.size }}$aft" })
print(" CasesCovered: $bef${bestPaths.entries.sumOf { it.value.size }}$aft")
print(" $ANSI_BRIGHT_GREEN|||$ANSI_RESET")
print(" PathsAdded: $bef${nextPaths.size} of ${pathsToSearchNow.size}$aft")
print(" HeatLoss: $bef${nextPaths.minOfOrNull { it.heatLoss }}..${nextPaths.maxOfOrNull { it.heatLoss }}$aft")
print(" Lengths: $bef${nextPaths.minOfOrNull { it.pos.size }}..${nextPaths.maxOfOrNull { it.pos.size }}$aft")
print(" DistToGo: $bef${nextPaths.minOfOrNull { it.distToEnd }}..${nextPaths.maxOfOrNull { it.distToEnd }}$aft")
print(" Scores: $bef${nextPaths.minOfOrNull { it.pathScore }}..${nextPaths.maxOfOrNull { it.pathScore }}$aft")
print(" BestPath: ")
val bestPath = bestPaths[coordN]?.values?.minByOrNull { it.pathScore }
if (bestPath != null) {
val bestPathStr = bestPath.dirs.joinToString("") { when(it) {
UP -> "^"
DOWN -> "v"
LEFT -> "<"
RIGHT -> ">"
else -> throw IllegalStateException()
} }
print("$ANSI_GREEN${bestPathStr}$aft")
if (bestPath.pos.toSet().size != bestPath.pos.toList().size) {
print(" $ANSI_RED(some positions duplicated)$aft")
}
}
println()
}
// part 2
fun List<String>.part2(): Int {
val grid = parse()
val coord0 = Coord(0, 0)
val coordN = Coord(grid[0].size - 1, grid.size - 1)
val path = SearchPath(grid, listOf(), listOf(coord0))
// store best paths by direction entering
val bestPaths = mutableMapOf(
coord0 to mutableMapOf(listOf<Coord>() to path)
)
println("Target: $bef$coordN$aft EstimatedHeatLoss: $bef${path.pathScore}$aft StartHeatLoss: $bef$START_HEAT_LOSS_2$aft")
val paths = mutableSetOf(path)
var i = 0
var minHeatLoss = START_HEAT_LOSS_2
while (paths.isNotEmpty()) {
val sorted = paths.sortedBy { it.pathScore }
val first100 = sorted.take(TAKE_N)
val pathsToSearchNow = first100.flatMap { it.nextPathsUltra() }
val nextPaths = pathsToSearchNow.filter { newPath ->
val last = newPath.pos.last()
// keep track of the best paths entering a coordinate from each direction
val lastChange = newPath.dirs.indices.drop(1).lastOrNull { newPath.dirs[it] != newPath.dirs[it - 1] }
val last3 = if (lastChange == null) newPath.dirs.toList() else newPath.dirs.takeLast(newPath.dirs.size - lastChange)
val curBest = bestPaths[last]?.get(last3)
if (last == coordN) {
bestPaths.putIfAbsent(last, mutableMapOf())
if (curBest == null || newPath.heatLoss < curBest.heatLoss)
bestPaths[last]!![last3] = newPath
false
} else if (newPath.heatLoss > minHeatLoss) {
false
} else if (curBest == null || newPath.pathScore < curBest.pathScore) {
bestPaths.putIfAbsent(last, mutableMapOf())
bestPaths[last]!![last3] = newPath
true
} else {
false
}
}
paths.removeAll(first100)
paths.removeAll { it.heatLoss > minHeatLoss }
paths.addAll(nextPaths)
i++
val heatloss = bestPaths[coordN]?.values?.minOfOrNull { it.heatLoss }
if (i % REPORT_ITERS_2 == 0 || paths.isEmpty() || (heatloss != null && heatloss < minHeatLoss)) {
if (heatloss != null) minHeatLoss = heatloss
printProgress(paths, pathsToSearchNow, nextPaths, bestPaths, coordN, i)
}
}
println("Total search iterations: $i")
return bestPaths[coordN]!!.values.minOf { it.heatLoss }
}
// calculate answers
val day = 17
val input = getDayInput(day, 2023)
val testResult = testInput.part1().also { it.print }
val testResult2 = testInput.part2().also { it.print }
val answer1 = input.part1().also { it.print }
val answer2 = input.part2().also { it.print }
// print results
AocRunner(day,
test = { "$testResult, $testResult2" },
part1 = { answer1 },
part2 = { answer2 }
).run()
| 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 11,073 | advent-of-code | Apache License 2.0 |
solutions/qualifications/moons-and-umbrellas/src/main/kotlin/solutions.moons.and.umbrellas/MoonsAndUmbrellasSolution.kt | Lysoun | 351,224,145 | false | null | import kotlin.math.min
fun main(args: Array<String>) {
val casesNumber = readLine()!!.toInt()
for (i in 1..casesNumber) {
// Ignore first line of case
val inputLine = readLine()!!.split(" ")
println("Case #$i: ${computeMuralCost(ProblemInput(
inputLine[0].toInt(),
inputLine[1].toInt(),
inputLine[2]
))}")
}
}
fun computeMuralCost(problemInput: ProblemInput): Int {
var totalCost = 0
var currentState = State(problemInput.mural[0], false)
for(drawing in problemInput.mural.subSequence(1, problemInput.mural.length)) {
val result = computeCost(currentState, drawing, problemInput.cjCost, problemInput.jcCost)
currentState = result.first
totalCost += result.second
}
return totalCost
}
fun computeCost(state: State, drawing: Char, cjCost: Int, jcCost: Int): Pair<State, Int> {
if (state.lastDrawing == '?') {
return State(drawing, false) to 0
}
if(drawing == '?') {
return State(state.lastDrawing, true) to 0
}
val newState = State(drawing, false)
return newState to computeCost(state.lastDrawing, drawing, cjCost, jcCost)
}
fun computeCost(lastDrawing: Char, drawing: Char, cjCost: Int, jcCost: Int): Int {
if (lastDrawing == drawing) {
return 0
}
if (lastDrawing == 'C') {
return cjCost
}
return jcCost
}
data class ProblemInput(val cjCost: Int, val jcCost: Int, val mural: String)
data class State(val lastDrawing: Char, val spaceSinceLastDrawing: Boolean) | 0 | Kotlin | 0 | 0 | 98d39fcab3c8898bfdc2c6875006edcf759feddd | 1,571 | google-code-jam-2021 | MIT License |
src/Day09.kt | Fenfax | 573,898,130 | false | {"Kotlin": 30582} | import java.awt.Point
import kotlin.math.sign
fun main() {
fun solve(input: List<Pair<Direction, Int>>, pointCount: Int): Int {
val points = (0 until pointCount).map { Point() }
val tailPointsVisited = mutableSetOf(Point())
for (command in input) {
for (unused in (1..command.second)) {
when (command.first) {
Direction.R -> points[0].translate(1, 0)
Direction.L -> points[0].translate(-1, 0)
Direction.U -> points[0].translate(0, 1)
Direction.D -> points[0].translate(0, -1)
}
for (i in (1 until pointCount)) {
if (points[i - 1].distance(points[i]) > 1.5) {
val translateX = points[i - 1].x - points[i].x
val translateY = points[i - 1].y - points[i].y
points[i].translate(translateX.sign, translateY.sign)
if (i == pointCount - 1) {
tailPointsVisited.add(Point(points[i]))
}
}
}
}
}
return tailPointsVisited.size
}
val input = readInput("Day09").map { cmd -> cmd.split(" ").let { Pair(Direction.valueOf(it[0]), it[1].toInt()) } }
println(solve(input, 2))
println(solve(input, 10))
}
private enum class Direction {
R,
L,
U,
D
} | 0 | Kotlin | 0 | 0 | 28af8fc212c802c35264021ff25005c704c45699 | 1,468 | AdventOfCode2022 | Apache License 2.0 |
2022/src/day09/day09.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day09
import GREEN
import RESET
import printTimeMillis
import readInput
import kotlin.math.abs
data class Point(var x: Int, var y: Int) {
private fun right() { x += 1 }
private fun left() { x-= 1 }
private fun up() { y -= 1 }
private fun down() { y += 1 }
fun executeInstruction(inst: String) {
when (inst) {
"R" -> right()
"U" -> up()
"L" -> left()
"D" -> down()
else -> throw IllegalStateException("Wrong move")
}
}
fun follow(other: Point) {
when {
other.x == x -> {
when {
other.y > y + 1 -> y += 1
other.y < y - 1 -> y -= 1
}
}
other.y == y -> {
when {
other.x > x + 1 -> x += 1
other.x < x - 1 -> x -= 1
}
}
else -> { // diagonals
val diffX = other.x - x
val diffY = other.y - y
if (abs(diffX) > 1 || abs(diffY) > 1) {
if (diffX > 0) { x += 1
} else { x -= 1 }
if (diffY > 0) { y += 1
} else { y -= 1 }
}
}
}
}
}
fun part1(input: List<String>, ropeSize: Int = 2): Int {
val tailPos = mutableSetOf<Pair<Int, Int>>()
val rope = List(ropeSize) { Point(0, 0) }
input.forEach {
val inst = it.split(" ")
repeat(inst.last().toInt()) {
rope.first().executeInstruction(inst.first())
for (i in rope.indices.drop(1)) {
rope[i].follow(rope[i - 1])
}
tailPos.add(Pair(rope.last().x, rope.last().y))
}
}
return tailPos.size
}
fun part2(input: List<String>) = part1(input, 10)
fun main() {
val testInput = readInput("day09_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day09.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 2,302 | advent-of-code | Apache License 2.0 |
kotlin/2359-find-closest-node-to-given-two-nodes.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 closestMeetingNode(edges: IntArray, node1: Int, node2: Int): Int {
val adj = HashMap<Int, MutableList<Int>>().apply {
for ((u, v) in edges.withIndex()) {
this[u] = getOrDefault(u, mutableListOf<Int>()).apply { add(v) }
}
}
fun bfs(node: Int, distMap: HashMap<Int, Int>) {
with (LinkedList<Pair<Int, Int>>()) {
addLast(node to 0)
distMap[node] = 0
while (isNotEmpty()) {
val (node, dist) = removeFirst()
adj[node]?.forEach { nei ->
if (nei !in distMap) {
addLast(nei to dist + 1)
distMap[nei] = dist + 1
}
}
}
}
}
val node1Dist = HashMap<Int, Int>()
val node2Dist = HashMap<Int, Int>()
bfs(node1, node1Dist)
bfs(node2, node2Dist)
var res = -1
var resDist = Integer.MAX_VALUE
for (i in edges.indices) {
if (i in node1Dist && i in node2Dist) {
val dist = maxOf(node1Dist[i]!!, node2Dist[i]!!)
if (dist < resDist) {
res = i
resDist = dist
}
}
}
return res
}
}
// bfs, but omitting the adjecency graph since it's not needed. We know that every node has at most 1 outgoing edge,
// so we can use the edge list to find the next node.
class Solution {
fun closestMeetingNode(edges: IntArray, node1: Int, node2: Int): Int {
fun bfs(node: Int, distMap: HashMap<Int, Int>) {
with (LinkedList<Pair<Int, Int>>()) {
addLast(node to 0)
distMap[node] = 0
while (isNotEmpty()) {
val (node, dist) = removeFirst()
val nei = edges[node]
if (nei != -1 && nei !in distMap) {
addLast(nei to dist + 1)
distMap[nei] = dist + 1
}
}
}
}
val node1Dist = HashMap<Int, Int>()
val node2Dist = HashMap<Int, Int>()
bfs(node1, node1Dist)
bfs(node2, node2Dist)
var res = -1
var resDist = Integer.MAX_VALUE
for (i in edges.indices) {
if (i in node1Dist && i in node2Dist) {
val dist = maxOf(node1Dist[i]!!, node2Dist[i]!!)
if (dist < resDist) {
res = i
resDist = dist
}
}
}
return res
}
}
// dfs
class Solution {
fun closestMeetingNode(edges: IntArray, node1: Int, node2: Int): Int {
fun dfs(node: Int, distMap: HashMap<Int, Int>, dist: Int) {
val nei = edges[node]
if (nei != -1 && nei !in distMap) {
distMap[nei] = dist + 1
dfs(nei, distMap, dist + 1)
}
}
val node1Dist = HashMap<Int, Int>().apply { this[node1] = 0 }
val node2Dist = HashMap<Int, Int>().apply { this[node2] = 0 }
dfs(node1, node1Dist, 0)
dfs(node2, node2Dist, 0)
var res = -1
var resDist = Integer.MAX_VALUE
for (i in edges.indices) {
if (i in node1Dist && i in node2Dist) {
val dist = maxOf(node1Dist[i]!!, node2Dist[i]!!)
if (dist < resDist) {
res = i
resDist = dist
}
}
}
return res
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 3,681 | leetcode | MIT License |
ceria/12/src/main/kotlin/Solution.kt | VisionistInc | 317,503,410 | false | null | import java.io.File
import kotlin.math.roundToInt
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 currPos = Pair<Int, Int>(0, 0)
var facing = 'E'
val directionOrder = listOf<Char>('E', 'S', 'W', 'N')
val degreeTranslater = mapOf<Int, Int>(90 to 1, 180 to 2, 270 to 3, 360 to 4)
for (nav in input) {
val units = nav.substring(1).toInt()
when (nav[0]) {
'N' -> { currPos = Pair<Int, Int>(currPos.first, currPos.second + units) }
'S' -> { currPos = Pair<Int, Int>(currPos.first, currPos.second - units) }
'E' -> { currPos = Pair<Int, Int>(currPos.first + units, currPos.second) }
'W' -> { currPos = Pair<Int, Int>(currPos.first - units, currPos.second) }
'L' -> {
val currDirPtr = directionOrder.indexOf(facing)
val dirOrderPtr = degreeTranslater.get(units)!!
facing = directionOrder.get( Math.floorMod( currDirPtr - dirOrderPtr, directionOrder.size) )
}
'R' -> {
val currDirPtr = directionOrder.indexOf(facing)
val dirOrderPtr = degreeTranslater.get(units)!!
facing = directionOrder.get( Math.floorMod( currDirPtr + dirOrderPtr, directionOrder.size) )
}
'F' -> {
when (facing) {
'N' -> { currPos = Pair<Int, Int>(currPos.first, currPos.second + units) }
'S' -> { currPos = Pair<Int, Int>(currPos.first, currPos.second - units) }
'E' -> { currPos = Pair<Int, Int>(currPos.first + units, currPos.second) }
'W' -> { currPos = Pair<Int, Int>(currPos.first - units, currPos.second) }
}
}
}
}
return Math.abs(currPos.first) + Math.abs(currPos.second)
}
private fun solution2(input :List<String>) :Int {
var currPos = Pair<Int, Int>(0, 0)
var wayPoint = Pair<Int, Int>(10, 1)
val degreeTranslater = mapOf<Int, Int>(90 to 270, 180 to 180, 270 to 90, 360 to 0)
for (nav in input) {
val units = nav.substring(1).toInt()
when (nav[0]) {
'N' -> { wayPoint = Pair<Int, Int>(wayPoint.first, wayPoint.second + units) }
'S' -> { wayPoint = Pair<Int, Int>(wayPoint.first, wayPoint.second - units) }
'E' -> { wayPoint = Pair<Int, Int>(wayPoint.first + units, wayPoint.second) }
'W' -> { wayPoint = Pair<Int, Int>(wayPoint.first - units, wayPoint.second) }
'L' -> {
var x = (wayPoint.first * Math.cos(Math.toRadians(units.toDouble()))) - (wayPoint.second * Math.sin(Math.toRadians(units.toDouble())))
var y = (wayPoint.second * Math.cos(Math.toRadians(units.toDouble()))) + (wayPoint.first * Math.sin(Math.toRadians(units.toDouble())))
wayPoint = Pair<Int, Int>(x.roundToInt(), y.roundToInt())
}
'R' -> {
var x = (wayPoint.first * Math.cos(Math.toRadians(degreeTranslater.get(units)!!.toDouble()))) - (wayPoint.second * Math.sin(Math.toRadians(degreeTranslater.get(units)!!.toDouble())))
var y = (wayPoint.second * Math.cos(Math.toRadians(degreeTranslater.get(units)!!.toDouble()))) + (wayPoint.first * Math.sin(Math.toRadians(degreeTranslater.get(units)!!.toDouble())))
wayPoint = Pair<Int, Int>(x.roundToInt(), y.roundToInt())
}
'F' -> {
for (i in 0 until units) {
currPos = Pair<Int, Int>(currPos.first + wayPoint.first, currPos.second + wayPoint.second)
}
}
}
}
return Math.abs(currPos.first) + Math.abs(currPos.second)
}
| 0 | Rust | 0 | 0 | 002734670384aa02ca122086035f45dfb2ea9949 | 3,929 | advent-of-code-2020 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindAnagrams.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.ALPHABET_LETTERS_COUNT
/**
* 438. Find All Anagrams in a String
* @see <a href="https://leetcode.com/problems/find-all-anagrams-in-a-string/">Source</a>
*/
fun interface FindAnagrams {
operator fun invoke(s: String, p: String): List<Int>
}
class FindAnagramsHashTable : FindAnagrams {
override operator fun invoke(s: String, p: String): List<Int> {
val list: MutableList<Int> = ArrayList()
if (p.length > s.length) return list // Base Condition
val n: Int = s.length // Array1 of s
val m: Int = p.length // Array2 of p
val count = freq(p) // initialize only 1 time
val currentCount = freq(s.substring(0, m)) // freq function, update every-time according to sliding window
// areSame function
if (areSame(count, currentCount)) {
list.add(0)
}
var i: Int = m
while (i < n) {
// going from 3 to 9 in above example
currentCount[s[i - m] - 'a']-- // blue pointer, decrement frequency
currentCount[s[i] - 'a']++ // red pointer, increment frequency
if (areSame(count, currentCount)) { // now check, both array are same
list.add(i - m + 1) // if we find similar add their index in our list
}
i++
}
return list
}
private fun areSame(x: IntArray, y: IntArray): Boolean {
for (i in 0 until ALPHABET_LETTERS_COUNT) {
// compare all the frequency & doesn't find any di-similar frequency return true otherwise false
if (x[i] != y[i]) {
return false
}
}
return true
}
private fun freq(s: String): IntArray {
val count = IntArray(ALPHABET_LETTERS_COUNT) // create array of size 26
for (element in s) {
count[element.code - 'a'.code]++ // update acc. to it's frequency
}
return count // and return count
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,623 | kotlab | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year18/Day12.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year18
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.nth
fun PuzzleSet.day12() = puzzle(day = 12) {
fun String.parse() = map { it == '#' }.withIndex().filter { it.value }.map { it.index }
val (initPart, rulesPart) = input.split("\n\n")
val initial = initPart.substringAfter(": ").parse()
data class Rule(val pattern: List<Int>, val to: Boolean)
val rules = rulesPart.lines().map { l ->
val (pattern, to) = l.split(" => ")
Rule(pattern.parse().map { it - 2 }, to == "#")
}
fun List<Int>.next(): List<Int> {
val result = mutableListOf<Int>()
for (idx in first() - 2..last() + 2) {
val currentPattern = (-2..2).filter { it + idx in this }
if (rules.find { (pattern) -> currentPattern == pattern }?.to == true) result += idx
}
return result
}
fun seq() = generateSequence(initial) { it.next() }
partOne = seq().nth(20).sumOf { it.toLong() }.s()
fun checkRepeat(old: List<Int>, new: List<Int>) = old.size == new.size &&
old.mapIndexed { idx, v -> new[idx] - v }.toSet().size == 1
val (old, new) = seq().withIndex().zipWithNext().first { (a, b) -> checkRepeat(a.value, b.value) }
val shift = new.value.first() - old.value.first()
val iterationsLeft = 50000000000 - new.index
partTwo = new.value.sumOf { it.toLong() + (shift.toLong() * iterationsLeft) }.s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,455 | advent-of-code | The Unlicense |
src/main/java/challenges/cracking_coding_interview/bit_manipulation/flip_bit_to_win/QuestionC.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.bit_manipulation.flip_bit_to_win
import kotlin.math.max
/**
* You have an integer, and you can flip exactly one bit from a 0 to a 1.
* Write code to find the length of the longest sequence of ls you could create.
* EXAMPLE
* Input: 1775 (or: 11011101111) Output: 8
*/
object QuestionC {
var SEQUENCE_LENGTH = 32
/* Given set of three sequences ordered as {0s, then 1s, then 0s},
* find max sequence that can be formed. */
private fun getMaxSequence(sequences: IntArray): Int { /* 1s, then 0s, then [old] ones */
return if (sequences[1] == 1) { // a single 0 -> merge sequences
sequences[0] + sequences[2] + 1
} else if (sequences[1] == 0) { // no 0s -> take one side
max(sequences[0], sequences[2])
} else { // many 0s -> take side, add 1 (flip a bit)
max(sequences[0], sequences[2]) + 1
}
}
fun shift(sequences: IntArray) {
sequences[2] = sequences[1]
sequences[1] = sequences[0]
sequences[0] = 0
}
fun longestSequence(n: Int): Int {
var n = n
var searchingFor = 0
val sequences = intArrayOf(0, 0, 0) // Counts of last 3 sequences
var maxSequence = 1
for (i in 0 until SEQUENCE_LENGTH) {
if (n and 1 != searchingFor) {
if (searchingFor == 1) { // End of 1s + 0s + 1s sequence
maxSequence = max(maxSequence, getMaxSequence(sequences))
}
searchingFor = n and 1 // Flip 1 to 0 or 0 to 1
shift(sequences) // Shift sequences
}
sequences[0]++
n = n ushr 1
}
/* Check final set of sequences */if (searchingFor == 0) {
shift(sequences)
}
val finalSequence = getMaxSequence(sequences)
maxSequence = max(finalSequence, maxSequence)
return maxSequence
}
@JvmStatic
fun main(args: Array<String>) {
val originalNumber = Int.MAX_VALUE
val newNumber = longestSequence(originalNumber)
println(Integer.toBinaryString(originalNumber))
println(newNumber)
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,203 | CodingChallenges | Apache License 2.0 |
src/main/kotlin/day21.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getText
class Dirac(private val startPlayer1: Int, private val startPlayer2: Int, private val dice: Dice){
private val cache = mutableMapOf<DiracState, Wins>()
private fun playerTurn(state: DiracState, steps: Int){
val currentPlayer = if(state.player1Turn) state.player1 else state.player2
currentPlayer.move(steps)
currentPlayer.addScore()
state.player1Turn = !state.player1Turn
}
fun playDeterministic(): Int{
val state = DiracState(DiracPlayer(1, startPlayer1, 0), DiracPlayer(2, startPlayer2, 0), true, 1000)
while(state.getWinner() == null){
playerTurn(state, dice.throw1x())
}
return state.getLooser()!!.score * dice.rolled
}
fun playQuantum(): Long{
val state = DiracState(DiracPlayer(1, startPlayer1, 0), DiracPlayer(2, startPlayer2, 0), true, 21)
val wins = findWins(state)
return maxOf(wins.player1, wins.player2)
}
private fun findWins(state: DiracState): Wins{
if(state.getWinner()?.nr == 1) return Wins(1, 0)
if(state.getWinner()?.nr == 2) return Wins(0, 1)
if(cache.containsKey(state)) return cache[state]!!
val wins = Wins(0, 0)
for(steps in dice.throw3x()){
val copyState = state.copy(player1 = state.player1.copy(), player2 = state.player2.copy())
playerTurn(copyState, steps)
val newWins = findWins(copyState)
wins.player1 += newWins.player1
wins.player2 += newWins.player2
}
cache[state] = wins
return wins
}
}
interface Dice{
var rolled: Int
fun throw1x(): Int
fun throw3x(): List<Int>
}
class DeterministicDice: Dice{
private var value = 1
get(){
return field.also {
rolled++
field++
if(field == 101) field = 1
}
}
override var rolled = 0
override fun throw1x() = value + value + value
override fun throw3x() = throw Exception("should not be used")
}
class QuantumDice: Dice{
override var rolled = 0
override fun throw3x(): List<Int> {
val sumOptions = mutableListOf<Int>()
for(d1 in 1..3) {
for (d2 in 1..3) {
for (d3 in 1..3) {
sumOptions.add(d1+d2+d3)
}
}
}
return sumOptions
}
override fun throw1x() = throw Exception("should not be used")
}
fun main(){
val input = getText("day21.txt")
val startPos = startPositions(input)
val deterministic = Dirac(startPos.first, startPos.second, DeterministicDice())
val task1 = deterministic.playDeterministic()
println(task1)
val quantum = Dirac(startPos.first, startPos.second, QuantumDice())
val task2 = quantum.playQuantum()
println(task2)
}
fun startPositions(input: String): Pair<Int, Int> {
val regex = Regex("""\d+$""")
val startPlayer1 = regex.find(input.lines()[0])!!.value.toInt()
val startPlayer2 = regex.find(input.lines()[1])!!.value.toInt()
return Pair(startPlayer1, startPlayer2)
}
private data class DiracState(val player1: DiracPlayer, val player2: DiracPlayer, var player1Turn: Boolean, val winAt: Int = 1000){
fun getWinner(): DiracPlayer?{
if(player1.score >= winAt) return player1
if(player2.score >= winAt) return player2
return null
}
fun getLooser(): DiracPlayer?{
if(player1.score >= winAt) return player2
if(player2.score >= winAt) return player1
return null
}
}
private data class DiracPlayer(val nr: Int, var pos: Int, var score: Int){
fun move(times: Int){
pos = (pos + times) % 10
if(pos == 0) pos = 10
}
fun addScore(){
score += pos
}
}
private data class Wins(var player1: Long, var player2: Long) | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 3,870 | AdventOfCode2021 | MIT License |
src/Day03.kt | Kietyo | 573,293,671 | false | {"Kotlin": 147083} |
fun Char.toPriority(): Int {
if (this in 'a'..'z') {
return this.code - 96
} else if (this in 'A'..'Z') {
return this.code - 65 + 27
}
TODO()
}
fun main() {
fun part1(input: List<String>): Unit {
var sum = 0
input.forEach {line ->
val halfSize = line.length / 2
val (s1, s2) = line.chunked(halfSize).map { it.toSet() }
val intersect = s1.intersect(s2)
require(intersect.size == 1)
sum += intersect.first().toPriority()
println(s1.intersect(s2))
}
// println(input)
// println('a'.code)
// println('z'.code)
// println('A'.code)
// println('Z'.code)
// println('a'.toPriority())
// println('z'.toPriority())
// println('A'.toPriority())
// println('Z'.toPriority())
println(sum)
}
fun part2(input: List<String>): Unit {
val ans = input.chunked(3).sumOf { window ->
window.map { it.toSet() }.reduce { acc, chars ->
acc.intersect(chars)
}.first().toPriority()
}
println(ans)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day3_test")
part1(testInput)
part2(testInput)
val input = readInput("day3_input")
// part1(input)
// part2(input)
}
| 0 | Kotlin | 0 | 0 | dd5deef8fa48011aeb3834efec9a0a1826328f2e | 1,396 | advent-of-code-2022-kietyo | Apache License 2.0 |
src/main/day1/Day01.kt | Derek52 | 572,850,008 | false | {"Kotlin": 22102} | package main.day1
import main.readInput
fun main() {
val input = readInput("day1/day1_part1")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
var highestCalorieCount = 0
var currentCalorieCount = 0
for (line in input) {
if (line == "") {
if (currentCalorieCount > highestCalorieCount) {
println("$currentCalorieCount is higher than highest: $highestCalorieCount")
highestCalorieCount = currentCalorieCount
}
currentCalorieCount = 0
} else {
currentCalorieCount += line.toInt()
}
}
return highestCalorieCount
}
fun part2(input: List<String>): Int {
var currentCalorieCount = 0
val highestTotalList = MutableList<Int>(3) { 0 }
for (line in input) {
if (line == "") {
if (currentCalorieCount > highestTotalList[0]) {
highestTotalList[0] = currentCalorieCount
bubbleSort(highestTotalList)
}
currentCalorieCount = 0
} else {
currentCalorieCount += line.toInt()
}
}
return sumList(highestTotalList)
}
fun bubbleSort(list: MutableList<Int>) {
var highestValue = 0
var indexOfHighest = 0
for (i in list.size - 1 downTo 2) {
for (j in 0 until i) {
val a = list[j]
val b = list[j+1]
if (a > b) {
list[j] = b
list[j+1] = a
}
}
}
}
fun sumList(list: List<Int>) : Int {
var currentSum = 0
list.forEach {
currentSum += it
}
return currentSum
} | 0 | Kotlin | 0 | 0 | c11d16f34589117f290e2b9e85f307665952ea76 | 1,671 | 2022AdventOfCodeKotlin | Apache License 2.0 |
src/main/kotlin/sschr15/aocsolutions/Day21.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.*
/**
* AOC 2023 [Day 21](https://adventofcode.com/2023/day/21)
* Challenge: The farmer elf needs to figure out where is traversable in their infinitely large field...
*/
object Day21 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 21) {
// test()
fun <T> Grid<T>.getNeighborsInfinity(point: Point) =
listOf(point.up(), point.down(), point.left(), point.right()).associateWith {
Point(it.x mod width, it.y mod height)
}
fun Grid<*>.coercePoint(point: Point) = Point(point.x mod width, point.y mod height)
val grid: Grid<Char>
part1 {
grid = inputLines.toGrid()
var locations = setOf(grid.toPointMap().filterValues { it == 'S' }.keys.single())
repeat(64) {
locations = locations.asSequence()
.flatMap { grid.getNeighbors(it, includeDiagonals = false).entries }
.filter { it.value != '#' }
.map { it.key }
.map { it.toPoint() }
.toSet()
}
locations.size
}
part2 {
val start = grid.toPointMap().filterValues { it == 'S' }.keys.single()
val everyPointValidNeighbors = grid.toPointMap().filterValues { it != '#' }.mapValues { (pt, _) ->
listOf(pt.up(), pt.down(), pt.left(), pt.right())
.associateWith { grid.coercePoint(it) }
.filterValues { grid[it] != '#' }
.map { (k, v) ->
when { // Pair of (point in grid, grid "offset")
k.x < 0 -> v to Point(-1, 0)
k.x >= grid.width -> v to Point(1, 0)
k.y < 0 -> v to Point(0, -1)
k.y >= grid.height -> v to Point(0, 1)
else -> v to Point(0, 0)
}
}
}
// each state point refers to a given copy of the grid
var currentState = everyPointValidNeighbors.keys.associateWith { emptySet<Point>() }.toMutableMap()
currentState[start] = setOf(Point.origin) // original grid
val threeValues = LongArray(3)
repeat(131 * 2 + 65) { i ->
val nextState = mutableMapOf<Point, Set<Point>>()
currentState.filterValues(Set<*>::isNotEmpty).forEach { (pt, current) ->
val neighbors = everyPointValidNeighbors[pt]!!
for ((neighbor, gridOffset) in neighbors) {
val newOffsets = current.map { it + gridOffset }
nextState[neighbor] = (nextState[neighbor] ?: emptySet()) + newOffsets
}
}
currentState = nextState
if (i % 131 == 64) {
val value = currentState.values.sumOf(Set<*>::size)
threeValues[i / 131] = value.toLong()
}
}
// funky arithmetic somehow makes it work for 26501365 steps
val (a, b, c) = threeValues
val x = 202300L // 26501365 / 131 (rounded down)
// i need to learn how this works instead of just seeing something about triangle numbers and asking others for help
(
a
+ (b - a) * x
+ (c - 2 * b + a) * x * (x - 1) / 2
)
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 3,686 | advent-of-code | MIT License |
src/Day11.kt | SnyderConsulting | 573,040,913 | false | {"Kotlin": 46459} | fun main() {
fun part1(input: List<String>): Int {
val monkeyConfigs = mutableListOf<MutableList<String>>()
input.forEach { line ->
if (line.startsWith("Monkey")) {
monkeyConfigs.add(mutableListOf())
} else if (line.isNotBlank()) {
monkeyConfigs.last().add(line)
}
}
val monkeys = monkeyConfigs.map { config ->
Monkey.from(config)
}
repeat(20) {
monkeys.forEach { monkey ->
monkey.takeTurn(monkeys)
}
}
val monkeyBusiness = monkeys.map { it.inspectionCount }.sortedDescending().let {
it[0] * it[1]
}
return monkeyBusiness
}
fun part2(input: List<String>): Int {
return 0
}
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
data class Monkey(
val items: MutableList<Long>,
val inspectionOperation: Any,
val test: Test
) {
var inspectionCount = 0
private fun inspectItem(idx: Int) {
inspectionCount++
increaseWorryValue(idx)
reduceWorryValue(idx)
}
private fun increaseWorryValue(idx: Int) {
inspectionOperation.also {
when (it) {
is Add -> {
items[idx] = items[idx] + it.value
}
is Multiply -> {
items[idx] = items[idx] * it.value
}
is Square -> {
items[idx] = items[idx] * items[idx]
}
}
}
}
private fun reduceWorryValue(idx: Int) {
items[idx] = items[idx].floorDiv(3)
}
private fun testItem(idx: Int): Int {
return if (items[idx] % test.value == 0L) {
test.trueMonkey
} else {
test.falseMonkey
}
}
private fun throwItem(idx: Int, other: Monkey) {
other.items.add(items[idx])
}
fun takeTurn(monkeys: List<Monkey>) {
items.forEachIndexed { idx, item ->
inspectItem(idx)
val monkeyToThrowTo = testItem(idx)
throwItem(idx, monkeys[monkeyToThrowTo])
}
items.clear()
}
companion object {
fun from(config: List<String>): Monkey {
val startingItems = config[0].split(":")[1].split(",").map { it.trim().toLong() }.toMutableList()
val operation = config[1].split("=")[1].let { string ->
if (string.endsWith("old")) {
//squaring
Square
} else if (string.contains("+")) {
//adding
val value = string.split("+")[1].trim().toInt()
Add(value)
} else {
//multiplying
val value = string.split("*")[1].trim().toInt()
Multiply(value)
}
}
val test = Test()
config[2].split(" ").last().trim().toInt().also { test.value = it }
config[3].split(" ").last().trim().toInt().also { test.trueMonkey = it }
config[4].split(" ").last().trim().toInt().also { test.falseMonkey = it }
return Monkey(
startingItems,
operation,
test
)
}
}
}
class Add(val value: Int)
class Multiply(val value: Int)
object Square
data class Test(var value: Int = 0, var trueMonkey: Int = 0, var falseMonkey: Int = 0) | 0 | Kotlin | 0 | 0 | ee8806b1b4916fe0b3d576b37269c7e76712a921 | 3,579 | Advent-Of-Code-2022 | Apache License 2.0 |
calendar/day11/Day11.kt | maartenh | 572,433,648 | false | {"Kotlin": 50914} | package day11
import Day
import Lines
class Day11 : Day() {
override fun part1(input: Lines): Any {
val monkeys = createMonkeys()
val worryMod = monkeys.values.map { it.testDivisibleBy }.fold(1L) { acc, b -> acc * b }
(1..20).forEach { round ->
monkeys.keys.sorted().forEach { monkeyNumber ->
monkeys[monkeyNumber]!!.playTurn(monkeys, true, worryMod)
}
}
return monkeys.entries.map { it.key to it.value.inspectionCount }
.sortedByDescending { it.second }
.take(2)
.map { it.second}
.fold(1) { acc, b -> acc * b }
}
override fun part2(input: Lines): Any {
val monkeys = createMonkeys()
val worryMod = monkeys.values.map { it.testDivisibleBy }.fold(1L) { acc, b -> acc * b }
(1..10000).forEach { round ->
monkeys.keys.sorted().forEach { monkeyNumber ->
monkeys[monkeyNumber]!!.playTurn(monkeys, false, worryMod)
}
}
return monkeys.entries.map { it.key to it.value.inspectionCount }
.sortedByDescending { it.second }
.take(2)
.map { it.second}
.fold(1.toBigInteger()) { acc, b -> acc * b.toBigInteger() }
}
companion object {
fun createMonkeys(): Map<Int, Monkey> =
mapOf(
0 to Monkey(
listOf(64),
{ c -> c * 7 },
13,
1,
3
),
1 to Monkey(
listOf(60, 84, 84, 65),
{ c -> c + 7 },
19,
2,
7
),
2 to Monkey(
listOf(52, 67, 74, 88, 51, 61),
{ c -> c * 3 },
5,
5,
7
),
3 to Monkey(
listOf(67, 72),
{ c -> c + 3 },
2,
1,
2
),
4 to Monkey(
listOf(80, 79, 58, 77, 68, 74, 98, 64),
{ c -> c * c },
17,
6,
0
),
5 to Monkey(
listOf(62, 53, 61, 89, 86),
{ c -> c + 8 },
11,
4,
6
),
6 to Monkey(
listOf(86, 89, 82),
{ c -> c + 2 },
7,
3,
0
),
7 to Monkey(
listOf(92, 81, 70, 96, 69, 84, 83),
{ c -> c + 4 },
3,
4,
5
),
)
}
}
class Monkey(
var items: List<Long>,
val inspect: (Long) -> Long,
val testDivisibleBy: Long,
val trueTarget: Int,
val falsetarget: Int
) {
var inspectionCount = 0
fun catch(item: Long) {
items += item
}
fun playTurn(monkeys: Map<Int, Monkey>, applyRelief: Boolean, worryMod: Long) {
items.forEach { item ->
val newWorry = inspect(item)
val finalWorry = if (applyRelief) { relief(newWorry) % worryMod } else newWorry % worryMod
if (finalWorry % testDivisibleBy == 0L) {
monkeys[trueTarget]!!.catch(finalWorry)
} else {
monkeys[falsetarget]!!.catch(finalWorry)
}
}
inspectionCount += items.size
items = listOf()
}
private fun relief(worry: Long): Long = worry / 3
} | 0 | Kotlin | 0 | 0 | 4297aa0d7addcdc9077f86ad572f72d8e1f90fe8 | 3,831 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | revseev | 573,354,544 | false | {"Kotlin": 9868} | fun main() {
day05task1()
day05task2()
}
fun day05task1() {
var first = true
var stacks: List<ArrayDeque<Char>>? = null
readInputAsSequenceGrouped("Day05") {
forEach { lines ->
if (first) {
stacks = parseStacks(lines.toList())
first = false
} else {
lines.forEach {
val (times, from, to) = parseCommand(it)
stacks!!.move(times, from, to)
}
first = true
}
}
}
println(stacks!!.mapNotNull { it.lastOrNull() }.joinToString(""))
}
fun day05task2() {
var first = true
var stacks: List<ArrayDeque<Char>>? = null
readInputAsSequenceGrouped("Day05") {
forEach { lines ->
if (first) {
stacks = parseStacks(lines.toList())
first = false
} else {
lines.forEach {
val (times, from, to) = parseCommand(it)
stacks!!.move2(times, from, to)
}
first = true
}
}
}
println(stacks!!.mapNotNull { it.lastOrNull() }.joinToString(""))
}
private fun parseCommand(it: String): Triple<Int, Int, Int> {
val nums = it.split(Regex("\\D+"))
return Triple(nums[1].toInt(), nums[2].toInt() - 1, nums[3].toInt() - 1)
}
private fun List<ArrayDeque<Char>>.move(times: Int, from: Int, to: Int) {
for (i in 1..times) {
get(to).addLast(get(from).removeLast())
}
}
private fun List<ArrayDeque<Char>>.move2(times: Int, from: Int, to: Int) {
val source = get(from)
val dest = get(to)
for (i in source.size - times until source.size) {
dest.addLast(source[i])
}
repeat(times) {
source.removeLast()
}
}
private fun parseStacks(stacksLines: List<String>): List<ArrayDeque<Char>> {
if (stacksLines.size < 2) throw IllegalArgumentException("Invalid input, expected size > 1")
val columns = getColumnsCount(stacksLines.first())
val stacks = List(columns) {
ArrayDeque<Char>(stacksLines.size - 1)
}
for (column in 0 until columns) {
val stack = stacks[column]
for (c in stacksLines.size - 2 downTo 0) {
val line = stacksLines[c]
val char = line.getCharForColumn(column) ?: break
stack.addLast(char)
}
}
return stacks
}
private fun getColumnsCount(line: String): Int = (line.length + 1) / 4
private fun String.getCharForColumn(column: Int): Char? {
val char = get(getIndexOfColumn(column))
return if (char.isLetter()) char else null
}
private fun getIndexOfColumn(column: Int): Int = 4 * column + 1
| 0 | Kotlin | 0 | 0 | df2e12287a30a3a7bd5a026a963bcac41a730232 | 2,721 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumFallingPathSum3.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.min
/**
* 1289. Minimum Falling Path Sum II
* @see <a href="https://leetcode.com/problems/minimum-falling-path-sum-ii/">Source</a>
*/
fun interface MinimumFallingPathSum3 {
fun minFallingPathSum(grid: Array<IntArray>): Int
}
class MinimumFallingPathSum3DP : MinimumFallingPathSum3 {
override fun minFallingPathSum(grid: Array<IntArray>): Int {
val n: Int = grid.size
val m: Int = grid[0].size
val dp = Array(n) { IntArray(m) }
var min = Int.MAX_VALUE
var minIndex = -1
var secondMin = Int.MAX_VALUE
for (i in 0 until n) {
for (j in 0 until m) {
dp[i][j] = Int.MAX_VALUE
if (i == 0) {
dp[i][j] = grid[i][j]
} else {
if (j == minIndex) {
dp[i][j] = min(secondMin + grid[i][j], dp[i][j])
} else {
dp[i][j] = min(min + grid[i][j], dp[i][j])
}
}
}
min = Int.MAX_VALUE
minIndex = -1
secondMin = Int.MAX_VALUE
for (j in 0 until m) {
if (min >= dp[i][j]) {
secondMin = min
min = dp[i][j]
minIndex = j
} else if (secondMin > dp[i][j]) {
secondMin = dp[i][j]
}
}
}
return min
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,124 | kotlab | Apache License 2.0 |
src/Day15.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
var sensors = mutableListOf<Pair<Pair<Int,Int>,Int>>()
var beacons = mutableSetOf<Pair<Int,Int>>()
for (line in input) {
if (line.isEmpty()) continue
var vs = line.split(" ").map { if (it.last() == ',' || it.last() == ':') it.dropLast(1) else it }
vs = vs.map { if (it.length > 2 && it.substring(0, 2) == "x=" || it.substring(0, 2) == "y=") it.substring(2) else it }
var x = vs[2].toInt()
var y = vs[3].toInt()
var bx = vs[8].toInt()
var by = vs[9].toInt()
sensors.add( Pair( Pair(x, y), abs(x - bx) + abs( y - by ) ) )
beacons.add( Pair(bx, by) )
}
var y = 2000000
var ans = 0
for (x in -3000000 .. 7000000) {
if (beacons.contains(Pair(x, y))) {
continue
}
for (s in sensors) {
var (sx, sy) = s.first
var dist = s.second
if (abs(sx - x) + abs(sy - y) <= dist) {
ans++
break
}
}
}
return ans
}
fun part2(input: List<String>): Long {
var sensors = mutableListOf<Pair<Pair<Int,Int>,Int>>()
var beacons = mutableSetOf<Pair<Int,Int>>()
for (line in input) {
if (line.isEmpty()) continue
var vs = line.split(" ").map { if (it.last() == ',' || it.last() == ':') it.dropLast(1) else it }
vs = vs.map { if (it.length > 2 && it.substring(0, 2) == "x=" || it.substring(0, 2) == "y=") it.substring(2) else it }
var x = vs[2].toInt()
var y = vs[3].toInt()
var bx = vs[8].toInt()
var by = vs[9].toInt()
sensors.add( Pair( Pair(x, y), abs(x - bx) + abs( y - by ) ) )
beacons.add( Pair(bx, by) )
}
val limX = 4000000
val limY = 4000000
for (s in sensors) {
var (sx, sy) = s.first
var dist = s.second
var x = sx - dist - 1
var y = sy
// left to top
while (x <= sx) {
if (x in 0 .. limX && y in 0 .. limY) {
var good = true
for (ss in sensors) {
var (ssx, ssy) = ss.first
var ddist = ss.second
if (abs(x - ssx) + abs(y - ssy) <= ddist) {
good = false
break
}
}
if (good) return (x.toLong() * limX + y).toLong()
}
x++
y++
}
// top to right
x = sx
y = sx + dist + 1
while (y >= sy) {
if (x in 0 .. limX && y in 0 .. limY) {
var good = true
for (ss in sensors) {
var (ssx, ssy) = ss.first
var ddist = ss.second
if (abs(x - ssx) + abs(y - ssy) <= ddist) {
good = false
break
}
}
if (good) return (x.toLong() * limX + y).toLong()
}
x++
y--
}
// right to bottom
x = sx + dist + 1
y = sy
while (x >= sx) {
if (x in 0 .. limX && y in 0 .. limY) {
var good = true
for (ss in sensors) {
var (ssx, ssy) = ss.first
var ddist = ss.second
if (abs(x - ssx) + abs(y - ssy) <= ddist) {
good = false
break
}
}
if (good) return (x.toLong() * limX + y).toLong()
}
x--
y--
}
// bottom to left
x = sx
y = sy - dist - 1
while (y <= sy) {
if (x in 0 .. limX && y in 0 .. limY) {
var good = true
for (ss in sensors) {
var (ssx, ssy) = ss.first
var ddist = ss.second
if (abs(x - ssx) + abs(y - ssy) <= ddist) {
good = false
break
}
}
if (good) return (x.toLong() * limX + y).toLong()
}
x--
y++
}
}
return -1
}
val input = readInput("Day15")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 4,927 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day05.kt | carloxavier | 574,841,315 | false | {"Kotlin": 14082} | fun main() {
// test if implementation meets criteria from the description sample:
val testInput = readInput("Day05_test")
check(day5(testInput) == "CMZ")
val input = readInput("Day05")
// Part 1
check(day5(input) == "LJSVLTWQM")
// Part 2
check(day5(input, shouldReverse = false) == "BRQWDBBJM")
}
private fun day5(input: List<String>, shouldReverse: Boolean = true): String {
val lineLength = input.first().length
// when only 1 stack given, line length will be 4 chars or fewer,
// just return the first crane at the top.
if (lineLength <= 4) {
return input.first()[1].toString()
}
val lineIterator = input.iterator()
val table = readInitialTable(lineIterator)
// next we have an empty line, just discard it
lineIterator.next()
// the following lines contain each a crane movement instruction,
// we read each and execute the movement on our table
while (lineIterator.hasNext()) {
val instruction = lineIterator.next()
val (numCranes, origin, destiny) = readInstruction(instruction)
moveCrane(table, origin, numCranes, destiny, shouldReverse)
}
// print top/first crane in each stack of our table
return table.map { column ->
column.first()
}.joinToString("")
}
private fun readInitialTable(
lineIterator: Iterator<String>
): MutableList<List<Char>> {
var line = lineIterator.next()
val numColumns = (line.length + 1) / 4
val table = MutableList(numColumns) { listOf<Char>() }
while (!line[1].isDigit()) {
var i = 0
line.chunked(4).forEach {
if (it[1].isLetter()) {
table[i] = table[i] + it[1]
}
i++
}
line = lineIterator.next()
}
return table
}
private fun readInstruction(instruction: String) =
instruction.split(" ")
.filter { it.first().isDigit() }
.map { it.toInt() }
private fun moveCrane(
table: MutableList<List<Char>>,
origin: Int,
numCranes: Int,
destiny: Int,
shouldReverse: Boolean = true
) {
val cranesToMove = table[origin - 1].take(numCranes)
table[origin - 1] = table[origin - 1].drop(numCranes)
table[destiny - 1] = (if (shouldReverse) cranesToMove.reversed() else cranesToMove) + table[destiny - 1]
} | 0 | Kotlin | 0 | 0 | 4e84433fe866ce1a8c073a7a1e352595f3ea8372 | 2,336 | adventOfCode2022 | Apache License 2.0 |
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day24/BugUniverse.kt | jrhenderson1988 | 289,786,400 | false | {"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37} | package com.github.jrhenderson1988.adventofcode2019.day24
import com.github.jrhenderson1988.adventofcode2019.common.Direction
class BugUniverse(grid: Map<Pair<Int, Int>, Char>) {
private val universe = mapOf(0 to grid)
private val maxY = grid.keys.map { it.second }.max()!!
private val maxX = grid.keys.map { it.first }.max()!!
private val center = Pair(maxX / 2, maxY / 2)
fun calculateTotalBugsAfterMinutes(minutes: Int) =
countBugs((0 until minutes).fold(universe) { u, _ -> mutate(u) })
private fun mutate(u: Map<Int, Map<Pair<Int, Int>, Char>>): Map<Int, Map<Pair<Int, Int>, Char>> {
val minZ = u.keys.min()!!
val maxZ = u.keys.max()!!
val mutated = mutableMapOf<Int, Map<Pair<Int, Int>, Char>>()
(minZ - 1..maxZ + 1).forEach { level ->
val grid = mutableMapOf<Pair<Int, Int>, Char>()
(0..maxY).forEach { y ->
(0..maxX).forEach { x ->
grid[Pair(x, y)] = mutateTile(
tile(x, y, level, u),
neighboursOf(x, y, level).map { tile(it.first, it.second, it.third, u) }
)
}
}
mutated[level] = grid
}
return mutated
}
fun neighboursOf(x: Int, y: Int, level: Int): Set<Triple<Int, Int, Int>> {
val neighbours = Direction.neighboursOf(Pair(x, y))
.filter { it.first in 0..maxX && it.second in 0..maxY }
.map { Triple(it.first, it.second, level) }
.toMutableSet()
val mid = Triple(center.first, center.second, level)
if (neighbours.contains(mid)) {
neighbours.remove(mid)
neighbours.addAll(when {
x == mid.first && y == mid.second - 1 -> (0..maxX).map { _x -> Triple(_x, 0, level + 1) }
x == mid.first && y == mid.second + 1 -> (0..maxX).map { _x -> Triple(_x, maxY, level + 1) }
x == mid.first - 1 && y == mid.second -> (0..maxY).map { _y -> Triple(0, _y, level + 1) }
x == mid.first + 1 && y == mid.second -> (0..maxY).map { _y -> Triple(maxX, _y, level + 1) }
else -> emptyList()
})
}
mapOf(
Triple(-1, 0, -1) to (x == 0),
Triple(0, -1, -1) to (y == 0),
Triple(1, 0, -1) to (x == maxX),
Triple(0, 1, -1) to (y == maxY)
).filter { it.value }.forEach { (delta, _) ->
neighbours.add(Triple(mid.first + delta.first, mid.second + delta.second, mid.third + delta.third))
}
return neighbours
}
private fun mutateTile(ch: Char, neighbours: List<Char>) =
when (ch) {
'#' -> if (neighbours.filter { tile -> tile == '#' }.size == 1) '#' else '.'
'.' -> if (neighbours.filter { tile -> tile == '#' }.size in setOf(1, 2)) '#' else '.'
else -> error("Invalid tile '$ch'.")
}
private fun tile(x: Int, y: Int, level: Int, u: Map<Int, Map<Pair<Int, Int>, Char>>) =
if (Pair(x, y) == center) {
'.'
} else {
(u[level] ?: mapOf())[Pair(x, y)] ?: '.'
}
private fun countBugs(u: Map<Int, Map<Pair<Int, Int>, Char>>) =
u.map { level -> level.value.filter { grid -> grid.key != center && grid.value == '#' }.size }.sum()
private fun render(u: Map<Int, Map<Pair<Int, Int>, Char>>) =
u.map { (level, grid) ->
"Level: ${level}\n" + (0..maxY).joinToString("\n") { y ->
(0..maxX).joinToString("") { x ->
(if (Pair(x, y) == center) '?' else grid[Pair(x, y)] ?: '.').toString()
}
}
}.joinToString("\n\n")
companion object {
fun parse(input: String): BugUniverse {
val grid = mutableMapOf<Pair<Int, Int>, Char>()
input.lines().forEachIndexed { y, line ->
line.forEachIndexed { x, ch ->
grid[Pair(x, y)] = ch
}
}
return BugUniverse(grid)
}
}
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 4,098 | advent-of-code | Apache License 2.0 |
src/day24/Day24.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day24
import readInput
enum class Direction(private val offset: Pair<Int, Int>) {
UP(-1 to 0), DOWN(1 to 0), LEFT(0 to -1), RIGHT(0 to 1);
fun transform(pos: Pair<Int, Int>) = Pair(pos.first + offset.first, pos.second + offset.second)
companion object {
fun fromChar(c: Char) = when (c) {
'>' -> RIGHT
'<' -> LEFT
'^' -> UP
'v' -> DOWN
else -> error("Should not happen")
}
}
}
fun Array<BooleanArray>.setIfPossible(pos: Pair<Int, Int>, value: Boolean) {
if (pos.first in indices && pos.second in this[pos.first].indices) {
this[pos.first][pos.second] = value
}
}
fun Pair<Int, Int>.wrap(maxFst: Int, maxSnd: Int): Pair<Int, Int> =
Pair((first + maxFst) % maxFst, (second + maxSnd) % maxSnd)
class Basin(
private var basin: Array<BooleanArray>,
private var blizzards: List<Pair<Pair<Int, Int>, Direction>>
) {
fun move() {
movePlayers()
moveBlizzards()
removePlayers()
}
private fun movePlayers() {
val basinNew = basin.map { it.copyOf() }.toTypedArray()
basin.forEachIndexed { x, row ->
row.forEachIndexed { y, pos ->
if (pos) {
basinNew.setIfPossible(x - 1 to y, true)
basinNew.setIfPossible(x + 1 to y, true)
basinNew.setIfPossible(x to y - 1, true)
basinNew.setIfPossible(x to y + 1, true)
}
}
}
basin = basinNew
}
fun moveBlizzards() {
blizzards = blizzards.map {
it.second.transform(it.first).wrap(basin.size, basin[0].size) to it.second
}
}
private fun removePlayers() {
blizzards.forEach {
basin[it.first.first][it.first.second] = false
}
}
fun isSet(pos: Pair<Int, Int>) = basin[pos.first][pos.second]
fun set(pos: Pair<Int, Int>) {
basin[pos.first][pos.second] = true
}
fun clear() {
basin = Array(basin.size) { BooleanArray(basin[0].size) { false } }
}
}
fun main() {
fun moveTo(basin: Basin, start: Pair<Int, Int>, end: Pair<Int, Int>): Int {
basin.clear()
basin.set(start)
var minute = 1
while (true) {
basin.move()
basin.set(start)
minute++
if (basin.isSet(end)) {
return minute + 1
}
}
}
fun part1(input: Pair<Basin, Pair<Int, Int>>): Int {
val (basin, end) = input
basin.moveBlizzards()
return moveTo(basin, 0 to 0, end)
}
fun part2(input: Pair<Basin, Pair<Int, Int>>): Int {
val (basin, end) = input
basin.moveBlizzards()
var minutes = moveTo(basin, 0 to 0, end)
repeat(2) { basin.moveBlizzards() }
minutes += moveTo(basin, end, 0 to 0)
repeat(2) { basin.moveBlizzards() }
minutes += moveTo(basin, 0 to 0, end)
return minutes
}
fun preprocess(input: List<String>): Pair<Basin, Pair<Int, Int>> {
val basin = Array(input.size - 2) { BooleanArray(input[0].length - 2) { false } }
basin[0][0] = true
val blizzards = mutableListOf<Pair<Pair<Int, Int>, Direction>>()
val end = basin.size - 1 to basin[0].size - 1
for (x in 1 until input.size - 1) {
for (y in 1 until input[x].length - 1) {
if (input[x][y] != '.') {
blizzards.add((x - 1 to y - 1) to Direction.fromChar(input[x][y]))
}
}
}
return Basin(basin, blizzards) to end
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(24, true)
check(part1(preprocess(testInput)) == 18)
val input = readInput(24)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) == 54)
println(part2(preprocess(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 3,990 | advent-of-code-2022 | Apache License 2.0 |
src/aoc23/Day05.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc23.day05
import kotlin.math.max
import kotlin.math.min
import lib.Collections.headTail
import lib.Solution
import lib.Strings.extractLongs
import lib.Strings.longs
enum class Category {
SEED, SOIL, FERTILIZER, WATER, LIGHT, TEMPERATURE, HUMIDITY, LOCATION;
companion object {
fun parse(categoryStr: String) = Category.valueOf(categoryStr.uppercase())
}
}
data class Item(val category: Category, val number: Long)
data class RangeMap(val srcRange: LongRange, val destRange: LongRange) {
constructor(destRangeStart: Long, srcRangeStart: Long, rangeLength: Long) :
this(
srcRangeStart..<srcRangeStart + rangeLength,
destRangeStart..<destRangeStart + rangeLength
)
fun apply(srcNumber: Long): Long =
when (srcNumber) {
in srcRange -> srcNumber + destRange.first - srcRange.first
else -> srcNumber
}
companion object {
fun parse(rangeMapStr: String): RangeMap {
val (destRangeStart, srcRangeStart, rangeLength) = rangeMapStr.longs()
return RangeMap(destRangeStart, srcRangeStart, rangeLength)
}
}
}
data class CategoryMap(
val srcCategory: Category,
val destCategory: Category,
val rangeMaps: List<RangeMap>,
) {
fun apply(srcItem: Item): Item =
when (srcItem.category) {
srcCategory -> Item(destCategory, applyRangeMaps(srcItem.number))
else -> srcItem
}
private fun applyRangeMaps(srcNumber: Long): Long =
rangeMaps
.firstOrNull { srcNumber in it.srcRange }
?.apply(srcNumber)
?: srcNumber
companion object {
fun parse(categoryMapStr: String): CategoryMap {
val (headerStr, rangesStr) = categoryMapStr.lines().headTail()
val (srcCategoryStr, destCategoryStr) = HEADER_REGEX.matchEntire(headerStr!!)!!.destructured
val srcCategory = Category.parse(srcCategoryStr)
val destCategory = Category.parse(destCategoryStr)
val rangeMaps = rangesStr.map(RangeMap.Companion::parse)
return CategoryMap(srcCategory, destCategory, rangeMaps)
}
private val HEADER_REGEX = """(\w+)-to-(\w+) map:""".toRegex()
}
}
data class Almanac(val seeds: List<Long>, val categoryMaps: List<CategoryMap>) {
fun convert(item: Item, destCategory: Category): Item {
var convertedItem = item
while (convertedItem.category != destCategory) {
convertedItem = categoryMaps
.first { it.srcCategory == convertedItem.category }
.apply(convertedItem)
}
return convertedItem
}
companion object {
fun parse(almanacStr: String): Almanac {
val (seedsStr, categoriesStr) = almanacStr.split("\n\n").headTail()
val seeds = seedsStr!!.extractLongs()
val categoryMaps = categoriesStr.map(CategoryMap.Companion::parse)
return Almanac(seeds, categoryMaps)
}
}
}
typealias Input = Almanac
typealias Output = Long
private val solution = object : Solution<Input, Output>(2023, "Day05") {
override fun parse(input: String): Input = Almanac.parse(input)
override fun format(output: Output): String = "$output"
override fun part1(input: Input): Output =
input.seeds.map { seed ->
input.convert(Item(Category.SEED, seed), Category.LOCATION)
}.minOf {
it.number
}
override fun part2(input: Input): Output {
var result = Long.MAX_VALUE
// Check all seeds in the given range which potentially skipping over some seeds.
fun check(range: LongProgression): Long? {
var minSeed: Long? = null
var minLocation = result
for (seed in range) {
val location = input.convert(Item(Category.SEED, seed), Category.LOCATION)
if (location.number < minLocation) {
minSeed = seed
minLocation = location.number
}
}
result = min(result, minLocation)
return minSeed
}
input.seeds.chunked(2)
.forEach { (start, length) ->
if (length < 1000000) {
// For small ranges, check all seeds.
check(start..<start + length)
} else {
// For large ranges, check in two stages.
// Stage 1: Jump by 1,000 to get closer to the minimum seed.
check(start..<start + length step 1000)?.let { minSeed ->
// Stage 2: Check last 1,000 seeds (inclusive of minSeed) which we skipped earlier.
// Care should be taken to not go past start.
check(max(minSeed - 999, start)..minSeed)
}
}
}
return result
}
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 4,535 | aoc-kotlin | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day3/Day3.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day3
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 3](https://adventofcode.com/2021/day/3)
*/
object Day3 : DayOf2021(3) {
override fun first(): Any? {
val length = lines.first().length
val counts = lines
.map { line -> line.map { ch -> ch.digitToInt() } }
.fold(List(length) { 0 }) { acc, value ->
acc.zip(value) { a, b -> a + b }
}
val gamma = counts.joinToString(separator = "") { if (it * 2 >= lines.size) "1" else "0" }.toInt(2)
val epsilon = counts.joinToString(separator = "") { if (it * 2 >= lines.size) "0" else "1" }.toInt(2)
return gamma * epsilon
}
override fun second(): Any? {
val length = lines.first().length
val oxygen = (0..<length)
.fold(lines) { acc, position ->
if (acc.size == 1) return@fold acc
val sum = acc.sumOf { it[position].digitToInt() }
val char = if (sum * 2 >= acc.size) '1' else '0'
return@fold acc.filter { it[position] == char }
}
.first()
.toInt(2)
val co2 = (0..<length)
.fold(lines) { acc, position ->
if (acc.size == 1) return@fold acc
val sum = acc.sumOf { it[position].digitToInt() }
val char = if (sum * 2 < acc.size) '1' else '0'
return@fold acc.filter { it[position] == char }
}
.first()
.toInt(2)
return oxygen * co2
}
}
fun main() = SomeDay.mainify(Day3)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,482 | adventofcode | MIT License |
src/main/kotlin/leetcode/kotlin/binarysearch/33. Search in Rotated Sorted Array.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.binarysearch
private fun search(nums: IntArray, target: Int): Int {
if (nums.isEmpty()) return -1
// find smallest element, use it's index as rotation count
var l = 0
var r = nums.lastIndex
var mid = 0
while (l < r) {
mid = l + (r - l) / 2
if (nums[mid] > nums[r]) l = mid + 1
else r = mid
}
var rot = l
l = 0
r = nums.lastIndex
while (l < r) {
mid = l + (r - l) / 2
var realmid = (mid + rot) % nums.size
if (nums[realmid] < target) l = mid + 1
else r = mid
}
return if (nums[(l + rot) % nums.size] == target) (l + rot) % nums.size else -1
}
// from solution
// https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14435/Clever-idea-making-it-simple
private fun search2(nums: IntArray, target: Int): Int {
if (nums.isEmpty()) return -1
var l = 0
var r = nums.lastIndex
var m = 0
var MAX = Int.MAX_VALUE
var MIN = Int.MIN_VALUE
while (l < r) {
m = l + (r - l) / 2
var num = when {
nums[m] < nums[0] == target < nums[0] -> nums[m]
target < nums[0] -> MIN
else -> MAX
}
if (num < target) l = m + 1
else r = m
}
return if (nums[l] == target) l else -1
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 1,314 | kotlinmaster | Apache License 2.0 |
src/main/arrays/SpecialNumbers.kt | dremme | 162,006,465 | false | {"Kotlin": 24254} | package arrays
/**
* Finds the minimum and maximum values. Elements can be any integer.
*
* @return a tuple of `(min, max)` or `null` if the array is empty.
*/
fun IntArray.findMinMaxNumbers(): Pair<Int, Int>? {
if (isEmpty()) return null
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
forEach {
min = if (min > it) it else min
max = if (max < it) it else max
}
return min to max
}
/**
* Finds all prime numbers. Elements are greater than zero.
*
* @return an array of prime numbers.
*/
fun IntArray.findPrimeNumbers(): IntArray {
require(all { it > 0 })
var primeArray = intArrayOf()
forEach { if (it.isPrime()) primeArray += it }
return primeArray
}
/**
* Almost any halfway efficient prime algorithm is acceptable here, but the steps required should not exceed the square
* root of the number.
*/
private fun Int.isPrime(): Boolean {
if (this == 1) return false
(2..sqrt()).forEach { if (this % it == 0) return false }
return true
}
/**
* Square root rounded to the nearest lower integer.
*/
private fun Int.sqrt() = Math.sqrt(toDouble()).toInt()
/**
* Determines the deepness of an array of arrays. A flat array (even if empty) has a deepness of `1`.
*/
fun Array<*>.deepness(): Int {
return map { if (it is Array<*>) 1 + it.deepness() else 1 }.max() ?: 1
}
| 0 | Kotlin | 0 | 0 | 1bdd6639502e3a5317a76bb5c0c116f04123f047 | 1,357 | coding-kotlin | MIT License |
src/Day05.kt | Lonexera | 573,177,106 | false | null | fun main() {
fun String.getAllNumbers(): List<Int> {
val decimals = "1234567890"
return map {
if (it in decimals) it else " "
}
.joinToString("")
.split(" ")
.filter { it.isNotBlank() }
.map { it.toInt() }
}
fun part1(instructions: List<String>): String {
val scheme = cratesScheme.toMutableList()
instructions.map { instruction ->
instruction.getAllNumbers()
}
.forEach {
val numberOfCrates = it[0]
val from = it[1] - 1
val to = it[2] - 1
val cratesToMove = scheme[from].take(numberOfCrates)
// remove crates from stack
scheme[from] = scheme[from].removePrefix(cratesToMove)
// add crates to new stack
scheme[to] = cratesToMove.reversed() + scheme[to]
}
return scheme
.mapNotNull { it.firstOrNull() }
.joinToString(separator = "")
}
fun part2(instructions: List<String>): String {
val scheme = cratesScheme.toMutableList()
instructions.map { instruction ->
instruction.getAllNumbers()
}
.forEach {
val numberOfCrates = it[0]
val from = it[1] - 1
val to = it[2] - 1
val cratesToMove = scheme[from].take(numberOfCrates)
// remove crates from stack
scheme[from] = scheme[from].removePrefix(cratesToMove)
// add crates to new stack
scheme[to] = cratesToMove + scheme[to]
}
return scheme
.mapNotNull { it.firstOrNull() }
.joinToString(separator = "")
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
private val cratesScheme = listOf(
"JZGVTDBN",
"FPWDMRS",
"ZSRCV",
"GHPZJTR",
"FQZDNJCT",
"MFSGWPVN",
"QPBVCG",
"NPBZ",
"JPW"
)
private val exampleScheme = listOf(
"NZ",
"DCM",
"P"
) | 0 | Kotlin | 0 | 0 | c06d394cd98818ec66ba9c0311c815f620fafccb | 2,289 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | Misano9699 | 572,108,457 | false | null | const val TOTAL_DISKSPACE = 70000000
const val FREE_DISKSPACE_NEEDED = 30000000
fun main() {
var root = Dir("/")
var currentDirectory: Dir = root
var directoriesWithSizes = mutableListOf<Pair<String, Int>>()
fun reset() {
root = Dir("/")
currentDirectory = root
directoriesWithSizes = mutableListOf()
}
fun changeDir(directory: String) {
when (directory) {
"/" -> currentDirectory = root
".." -> currentDirectory.parent?.let { dir -> currentDirectory = dir }
"." -> {} // current directory stays the same
else -> {
if (currentDirectory.nodes[directory] != null) {
currentDirectory = currentDirectory.nodes[directory] as Dir
} else {
throw IllegalStateException("Directory $directory unknown")
}
}
}
}
fun processCommand(command: String) {
if (command.startsWith("cd ")) changeDir(command.substring(3))
// ls does nothing except showing files and directories which are processed separately
}
fun processDirectory(name: String) {
if (!currentDirectory.nodes.containsKey(name)) {
val directory = Dir(name)
directory.parent = currentDirectory
currentDirectory.nodes[name] = directory
} else {
println("Directory already added")
}
}
fun processFile(line: String) {
val split = line.split(" ")
val size = split[0].toInt()
val name = split[1]
if (!currentDirectory.nodes.containsKey(split[1])) {
currentDirectory.nodes[name] = File(name, size)
} else {
println("File already added")
}
}
fun createDirectoryStructure(input: List<String>) {
input.forEach { line ->
when {
line.startsWith("$ ") -> processCommand(line.substring(2))
line.startsWith("dir ") -> processDirectory(line.substring(4))
else -> processFile(line)
}
}
}
fun calculateSize(totalSize: Int, dir: Dir): Int {
dir.totalSize = dir.nodes.values.sumOf {
when (it) {
is File -> it.size
is Dir -> calculateSize(totalSize, it)
else -> 0 // should not happen
}
}
directoriesWithSizes.add(Pair(dir.name, dir.totalSize))
return dir.totalSize
}
fun createListOfDirectoriesWithSizes(input: List<String>): Int {
reset()
createDirectoryStructure(input)
return calculateSize(0, root)
}
fun part1(input: List<String>): Int {
val totalDiskspaceUsed = createListOfDirectoriesWithSizes(input)
println("total diskspace used: $totalDiskspaceUsed")
return directoriesWithSizes.filter { it.second <= 100000 }
.sumOf { it.second }
}
fun part2(input: List<String>): Int {
val totalDiskspaceUsed = createListOfDirectoriesWithSizes(input)
println("total diskspace used: $totalDiskspaceUsed")
val spaceToDelete = FREE_DISKSPACE_NEEDED - (TOTAL_DISKSPACE - totalDiskspaceUsed)
println("space to delete: $spaceToDelete")
return directoriesWithSizes.filter { it.second > spaceToDelete }
.minOf { it.second }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
val input = readInput("Day07")
println("---- PART 1 ----")
check(part1(testInput).also { println("Answer test input part1: $it") } == 95437)
println("Answer part1: " + part1(input))
println("---- PART 2 ----")
check(part2(testInput).also { println("Answer test input part2: $it") } == 24933642)
println("Answer part2: " + part2(input))
}
open class Node(val name: String) {
override fun toString(): String {
return name
}
}
class Dir(name: String) : Node(name) {
var parent: Dir? = null // needed to navigate a directory up
var nodes: MutableMap<String, Node> = mutableMapOf()
var totalSize: Int = 0
override fun toString(): String {
return super.toString() + ", nodes=[$nodes]"
}
}
class File(name: String, val size: Int) : Node(name) | 0 | Kotlin | 0 | 0 | adb8c5e5098fde01a4438eb2a437840922fb8ae6 | 4,328 | advent-of-code-2022 | Apache License 2.0 |
ceria/14/src/main/kotlin/Solution.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File;
import java.util.Stack;
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
var startPoly = input.first()
var polymers = mutableMapOf<String, String>()
for ( p in 2..input.size - 1) {
val poly = input.get(p).split(" -> ")
polymers.put(poly[0], poly[1])
}
println("Solution 1: ${solution1(startPoly, polymers)}")
println("Solution 1: ${solution2(startPoly, polymers)}")
}
/* This does not scale for part 2 :( Which, I had a feeling it wouldn't cause this is AOC after all */
private fun solution1(start: String, polymers: Map<String, String>) :Int {
var steps = 10
var startPoly = StringBuilder(start)
for (x in 1..steps) {
var windows = startPoly.windowed(size = 2, step = 1)
var insertAt = startPoly.length - 1
// start with the end of the list so that our indexes for insertion are correct
val itr: ListIterator<String> = windows.listIterator(windows.size)
while (itr.hasPrevious()) {
var p = itr.previous()
val newP = polymers.get(p)?.let{
polymers.get(p)
} ?: ""
if (!newP.isEmpty()) {
startPoly = startPoly.insert(insertAt, newP)
}
insertAt -= 1
}
}
var polyCounts = startPoly.groupingBy{ it }.eachCount()
return polyCounts.values.maxOf { it } - polyCounts.values.minOf { it }
}
private fun solution2(start: String, polymers: Map<String, String>) :Long {
var steps = 40
// Loop through the start string, ignoring the beginning and end of it
// since those values will never change, and seed the frequency map of windows
var frequencies = start.drop(1).dropLast(1).windowed(size = 2, step = 1).groupingBy{ it }.eachCount().mapValues{ it.value.toLong() }
// The first and last windows are special
var firstWindow = start.take(2)
var lastWindow = start.takeLast(2)
for (i in 0..steps - 1) {
var newFrequencies = mutableMapOf<String, Long>()
// Count the frequencies of the windows for this step
// For each known polymer in the frequency map, look up it's insert value,
// create two new windows using the insert value and the poylmer and update
// the frequencies for those new windows
for (polymer in frequencies.keys) {
val insertVal = polymers.getOrDefault(polymer, "")
// Don't know if this can happen... the insertVal was not in our lookup map, i.e it wasn't in the input
if (insertVal.isEmpty()) {
continue
}
// the new window created by the first character of the current polymer from frequencies and the insertVal
val leftInsert = polymer[0] + insertVal
// the new window created by the second character of the current polymer from frequencies and the insertVal
val rightInsert = insertVal + polymer[1]
// sum the frequencies for the forward and backward windows
newFrequencies[leftInsert] = newFrequencies.getOrDefault(leftInsert, 0) + frequencies.getOrDefault(polymer, 0)
newFrequencies[rightInsert] = newFrequencies.getOrDefault(rightInsert, 0) + frequencies.getOrDefault(polymer, 0)
}
// need to treat the first and last windows special
// the first character of the last window is he only character of the two that needs to be updated
val lastInsert = polymers.getOrDefault(lastWindow, "")
val lastLeftInsert = lastWindow.first() + lastInsert
newFrequencies[lastLeftInsert] = newFrequencies.getOrDefault(lastLeftInsert, 0) + 1
// the last character of the first window is he only character of the two that needs to be updated
val firstInsert = polymers.getOrDefault(firstWindow, "")
val lastFirstInsert = firstInsert + firstWindow.last()
newFrequencies[lastFirstInsert] = newFrequencies.getOrDefault(lastFirstInsert, 0) + 1
// update the first and last windows with the new windows
firstWindow = firstWindow.first() + firstInsert
lastWindow = lastInsert + lastWindow.last()
frequencies = newFrequencies
}
// count the polymers -- make Pairs using the first character of each window, to their counts
//i.e. ('B', 72), ('B' 120) and then sum all the pairs with the same "first" character
val polymerCounts = frequencies
.map{ Pair<Char, Long>(it.key.first(), it.value) }
.groupBy { it.first }
.mapValues { p -> p.value.sumOf { it.second } }
.toMutableMap()
// add in the very first character of the very first window -- it was dropped/ignroed in the loop
polymerCounts[firstWindow.first()] = polymerCounts.getOrDefault(firstWindow.first(), 0) + 1
// add in the next to last character of the very last window -- it was just not counted in the last loop iteration.
polymerCounts[lastWindow.first()] = polymerCounts.getOrDefault(lastWindow.first(), 0) + 1
// add in the very last character of the very last window -- it was dropped/ignored in the loop
polymerCounts[lastWindow.last()] = polymerCounts.getOrDefault(lastWindow.last(), 0) + 1
return polymerCounts.values.maxOf { it } - polymerCounts.values.minOf { it }
} | 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 5,346 | advent-of-code-2021 | MIT License |
src/main/kotlin/com/jacobhyphenated/advent2023/day3/Day3.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day3
import com.jacobhyphenated.advent2023.Day
import com.jacobhyphenated.advent2023.product
/**
* Day 3: Gear Ratios
*
* A 2d array contains numbers, periods, and symbols.
* Continuous numbers for a single integer, periods are empty spaces.
*
* A Part number is any number that is adjacent (including diagonally) to a symbol
* example:
* 467..114..
* ...*......
* ..35..633.
* ......#...
*
* 114 is not a part number, the others are
*/
class Day3: Day<List<List<Char>>> {
private val digits = ('0' .. '9').toSet()
override fun getInput(): List<List<Char>> {
return readInputFile("3").lines().map { it.toCharArray().toList() }
}
/**
* Part 1: What is the sum of all the part numbers?
*
* loop through the grid, when we encounter digits, construct the integer number
* while check to see if a symbol is adjacent to any digit within the number
*
*/
override fun part1(input: List<List<Char>>): Int {
var partNumbers = 0
for (row in input.indices) {
var buffer = ""
var adjacentToSymbol = false
for (col in input[row].indices) {
if (input[row][col] !in digits) {
if (buffer != "" && adjacentToSymbol) {
partNumbers += buffer.toInt()
}
buffer = ""
adjacentToSymbol = false
} else {
buffer += input[row][col]
adjacentToSymbol = adjacentToSymbol || hasAdjacentSymbol(input, row, col)
}
}
// don't forget to check the buffer at the end of the row, in case the last character was a digit
if (buffer != "" && adjacentToSymbol) {
partNumbers += buffer.toInt()
}
}
return partNumbers
}
/**
* Part 2: A gear as a * symbol with exactly 2 adjacent numbers. The gear ratio is the product of those two numbers
* Add up the gear ratios for all gears in the input
*/
override fun part2(input: List<List<Char>>): Int {
var gearRatio = 0
for (row in input.indices) {
for (col in input[row].indices) {
if (input[row][col] == '*') {
findGearNumbers(input, row, col)?.let { positions ->
gearRatio += positions
.map { (r,c) -> fullNumberAtPosition(input, r, c) }
.product()
}
}
}
}
return gearRatio
}
/**
* Helper function to find all adjacent positions including diagonals
* @param input the grid/puzzle input
* @param row the baseline row we are looking around
* @param col the baseline column we are looking around
*
* @return a list of positions (row, col) as a pair that are adjacent to the input row and column
*/
private fun findAdjacentPositions(input: List<List<Char>>, row: Int, col: Int): List<Pair<Int,Int>> {
val adjacent = mutableListOf<Pair<Int,Int>>()
for (r in (row - 1).coerceAtLeast(0) .. (row + 1).coerceAtMost(input.size - 1)) {
for (c in (col - 1).coerceAtLeast(0) .. (col + 1).coerceAtMost(input[r].size - 1)) {
if (r == row && c == col) {
continue
}
adjacent.add(Pair(r,c))
}
}
return adjacent
}
/**
* Check all the adjacent positions to see if any are a symbol. Return false otherwise
*/
private fun hasAdjacentSymbol(input: List<List<Char>>, row: Int, col:Int): Boolean {
return findAdjacentPositions(input, row, col).any { (r,c) -> input[r][c] != '.' && input[r][c] !in digits }
}
/**
* Gears are * symbols with exactly two adjacent numbers. The input row/col represent a * symbol.
* Return the position (row,col) of the adjacent numbers if there are exactly two, null otherwise
*/
private fun findGearNumbers(input: List<List<Char>>, row: Int, col:Int): List<Pair<Int,Int>>? {
val adjacent = findAdjacentPositions(input, row, col)
var lastNumberPosition: Pair<Int,Int>? = null
// track the last adjacent digit to prevent duplicate entries for the same integer
val adjacentNumbers = mutableListOf<Pair<Int, Int>>()
for ((r,c) in adjacent) {
if (input[r][c] in digits) {
// if the digit also has a digit in the preceding column (that is adjacent to this symbol), it's a duplicate
if (lastNumberPosition == null || lastNumberPosition.first != r || lastNumberPosition.second != c - 1) {
adjacentNumbers.add(Pair(r,c))
}
lastNumberPosition = Pair(r,c)
}
}
return if (adjacentNumbers.size == 2) { adjacentNumbers } else { null }
}
/**
* The input row/col represents a single digit in the integer.
* The integer may be composed of additional digits both before and after this digit.
* Find and return the full integer
*/
private fun fullNumberAtPosition(input: List<List<Char>>, row: Int, col: Int): Int {
var startIndex = col
while (startIndex >= 0 && input[row][startIndex] in digits) {
startIndex--
}
var endIndex = col
while (endIndex < input[row].size && input[row][endIndex] in digits) {
endIndex++
}
return (startIndex + 1 until endIndex).map { input[row][it] }.joinToString("").toInt()
}
override fun warmup(input: List<List<Char>>) {
part1(input)
part2(input)
}
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
Day3().run()
} | 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 5,301 | advent2023 | The Unlicense |
src/main/kotlin/days/aoc2020/Day19.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2020
import days.Day
class Day19 : Day(2020, 19) {
override fun partOne(): Any {
val ruleMap = createRuleMap(inputList)
val regexString = generateRegex(ruleMap["0"] ?: error("no rule 0"), ruleMap)
val regex = Regex(regexString)
return inputList.subList(inputList.indexOfFirst { it.isBlank() } + 1, inputList.size).map {
regex.matches(it)
}.count { it }
}
private fun createRuleMap(input: List<String>): Map<String,String> {
var i = 0
val ruleMap = mutableMapOf<String,String>()
input.takeWhile { it.isNotBlank() }.forEach {
val (key,value) = it.split(":")
ruleMap[key] = value.trim()
}
return ruleMap
}
private fun generateRegex(rule: String, ruleMap: Map<String, String>): String {
when {
rule.contains('|') -> {
val subrules = rule.split("|").map { it.trim() }
return "(" + generateRegex(subrules[0], ruleMap) + "|" + generateRegex(subrules[1], ruleMap) + ")"
}
rule.contains(' ') -> {
return rule.split(" ").map { it.trim() }.joinToString("") {
val result = generateRegex(it, ruleMap)
result
}
}
rule.contains('"') -> {
return rule.substring(1, 2)
}
else -> {
return generateRegex(ruleMap[rule] ?: error("no rule"), ruleMap)
}
}
}
private fun validateInput(input: String, ruleMap: Map<String,String>, rules: List<String>): Boolean {
if (input.isBlank()) {
return rules.isEmpty()
} else if (rules.isEmpty()) {
return false
}
return (ruleMap[rules[0]] ?: error("no rule for $rules[0]")).let { rule ->
when {
rule.contains('"') ->
if (input[0] == rule[1]) {
validateInput(input.substring(1), ruleMap, rules.drop(1))
} else {
false
}
else -> {
rule.split("|").map { it.trim() }.any { subrule ->
validateInput(input, ruleMap, subrule.split(" ") + rules.drop(1))
}
}
}
}
}
override fun partTwo(): Any {
val ruleMap = mutableMapOf<String,String>()
ruleMap.putAll(createRuleMap(inputList))
ruleMap["8"] = "42 | 42 8"
ruleMap["11"] = "42 31 | 42 11 31"
return inputList.subList(inputList.indexOfFirst { it.isBlank() } + 1, inputList.size).count {
validateInput(it, ruleMap, listOf("0"))
}
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 2,783 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/Day03.kt | wlghdu97 | 573,333,153 | false | {"Kotlin": 50633} | fun main() {
fun priority(compartment: Char): Int {
return when (compartment) {
in ('a'..'z') -> compartment.code - 96
in ('A'..'Z') -> compartment.code - 38
else -> throw IllegalArgumentException()
}
}
fun part1(input: List<String>): Int {
return input.sumOf {
val middle = it.length / 2
val first = it.substring(0, middle).toCharArray()
val second = it.substring(middle).toCharArray().toSet()
priority(first.intersect(second).first())
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { rucksacks ->
val badge = rucksacks.map { it.toCharArray().toSet() }.reduce { acc, chars ->
acc.intersect(chars)
}.first()
priority(badge)
}
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2b95aaaa9075986fa5023d1bf0331db23cf2822b | 953 | aoc-2022 | Apache License 2.0 |
2016/main/day_20/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_20_2016
import java.io.File
fun part1(input: List<UIntRange>) {
var inputs = input.sortedBy { it.first }
var index: UInt = 0u
while (index < inputs.maxBy { it.last }.last) {
index = inputs[0].last + 1u
inputs = inputs.filter { it.last > index }
if (index < inputs[0].first) {
println(index)
break
}
}
}
fun part2(input: List<UIntRange>) {
input.sortedBy { it.first }
.map { it.first to it.last }
.fold(emptyList<Pair<UInt, UInt>>()) { ranges, range ->
if (ranges.isEmpty() || (ranges.last().second < (range.first - 1u))) {
ranges + range
} else {
ranges.last().let { last ->
ranges.dropLast(1) + (last.first to maxOf(range.second, last.second))
}
}
}.sumOf { it.second - it.first + 1u }
.let { print("The number of valid IPs is ${4294967296u - it}") }
// too high
// 4279991501
// 4206688754
// 102
// 100 wrong (not too high, so close?)
}
private operator fun UIntRange.component2(): UInt {
return last
}
private operator fun UIntRange.component1(): UInt {
return first
}
fun main(){
val inputFile = File("2016/inputs/Day_20.txt")
print("\n----- Part 1 -----\n")
part1(inputFile.readLines().map { it.split('-')[0].toUInt()..it.split('-')[1].toUInt() })
print("\n----- Part 2 -----\n")
part2(inputFile.readLines().map { it.split('-')[0].toUInt()..it.split('-')[1].toUInt() })
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 1,556 | AdventofCode | MIT License |
src/year2021/day02/Day02.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2021.day02
import readInputFileByYearAndDay
import readTestFileByYearAndDay
fun main() {
fun part1(input: List<String>): Int {
fun sumNumbersByPrefix(input: List<String>, prefix: String): Int = input.filter { it.startsWith(prefix) }
.map { it.split(" ")[1] }
.map { it.toInt() }
.sum()
val horizontal = sumNumbersByPrefix(input, "forward")
val depth = sumNumbersByPrefix(input, "down") - sumNumbersByPrefix(input, "up")
return horizontal * depth
}
fun part2(input: List<String>): Int {
var aim = 0
var depth = 0
var horizontal = 0
input.forEach {
val parts = it.split(" ")
val magnitude = parts[1].toInt()
when (parts[0]) {
"up" -> aim += magnitude
"down" -> aim -= magnitude
else -> {
horizontal += magnitude
depth -= aim * magnitude
}
}
}
return horizontal * depth
}
val testInput = readTestFileByYearAndDay(2021, 2)
check(part1(testInput) == 150)
check(part2(testInput) == 900)
val input = readInputFileByYearAndDay(2021, 2)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 1,304 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/g0701_0800/s0741_cherry_pickup/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0701_0800.s0741_cherry_pickup
// #Hard #Array #Dynamic_Programming #Matrix
// #2023_03_03_Time_196_ms_(100.00%)_Space_37.3_MB_(100.00%)
class Solution {
fun cherryPickup(grid: Array<IntArray>): Int {
val dp = Array(grid.size) {
Array(grid.size) {
IntArray(
grid.size
)
}
}
val ans = solve(0, 0, 0, grid, dp)
return ans.coerceAtLeast(0)
}
private fun solve(r1: Int, c1: Int, r2: Int, arr: Array<IntArray>, dp: Array<Array<IntArray>>): Int {
val c2 = r1 + c1 - r2
if (r1 >= arr.size || r2 >= arr.size || c1 >= arr[0].size || c2 >= arr[0].size || arr[r1][c1] == -1 ||
arr[r2][c2] == -1
) {
return Int.MIN_VALUE
}
if (r1 == arr.size - 1 && c1 == arr[0].size - 1) {
return arr[r1][c1]
}
if (dp[r1][c1][r2] != 0) {
return dp[r1][c1][r2]
}
var cherries = 0
cherries += if (r1 == r2 && c1 == c2) {
arr[r1][c1]
} else {
arr[r1][c1] + arr[r2][c2]
}
val a = solve(r1, c1 + 1, r2, arr, dp)
val b = solve(r1 + 1, c1, r2 + 1, arr, dp)
val c = solve(r1, c1 + 1, r2 + 1, arr, dp)
val d = solve(r1 + 1, c1, r2, arr, dp)
cherries += a.coerceAtLeast(b).coerceAtLeast(c.coerceAtLeast(d))
dp[r1][c1][r2] = cherries
return cherries
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,474 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/github/aoc/AOCD4P2.kt | frikit | 317,914,710 | false | null | package com.github.aoc
import com.github.aoc.utils.InputDay4Problem2
import com.github.aoc.utils.InputParser
import com.github.aoc.utils.Result
fun main() {
// TC
// byr valid: 2002
// byr invalid: 2003
//
// hgt valid: 60in
// hgt valid: 190cm
// hgt invalid: 190in
// hgt invalid: 190
//
// hcl valid: #123abc
// hcl invalid: #123abz
// hcl invalid: 123abc
//
// ecl valid: brn
// ecl invalid: wat
//
// pid valid: 000000001
// pid invalid: 0123456789
//byr
assert(isValidPassport(mapOf("byr" to "2002")))
assert(!isValidPassport(mapOf("byr" to "2003")))
//hgt
assert(isValidPassport(mapOf("hgt" to "60in")))
assert(isValidPassport(mapOf("hgt" to "190cm")))
assert(!isValidPassport(mapOf("hgt" to "190in")))
assert(!isValidPassport(mapOf("hgt" to "190")))
//hcl
assert(isValidPassport(mapOf("hcl" to "#123abc")))
assert(!isValidPassport(mapOf("hcl" to "#123abz")))
assert(!isValidPassport(mapOf("hcl" to "123abz")))
//ecl
assert(isValidPassport(mapOf("ecl" to "brn")))
assert(!isValidPassport(mapOf("ecl" to "wat")))
//pid
assert(isValidPassport(mapOf("pid" to "000000001")))
assert(!isValidPassport(mapOf("pid" to "0123456789")))
//actual input
val input = InputParser.parseInput(InputDay4Problem2, "\n\n")
.map { it.replace("\n", " ") }
.map { it.replace("\r", " ") }
val map = input.map {
it.split(" ").map { elem ->
val key = elem.split(":")[0].trim()
val value = elem.split(":")[1].trim()
key to value
}
}.map {
val res = hashMapOf<String, String>()
it.forEach { pair ->
res[pair.first] = pair.second
}
res
}
val valids = map.map { validatePassport(it) }.filter { it }.count()
Result.stopExecutionPrintResult(valids)
}
/**
* byr (Birth Year)
* iyr (Issue Year)
* eyr (Expiration Year)
* hgt (Height)
* hcl (Hair Color)
* ecl (Eye Color)
* pid (Passport ID)
* cid (Country ID) - Optional
*/
private fun validatePassport(userMap: Map<String, String>): Boolean {
val requiredProps = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid").sorted()
val keyWithValues = userMap.map { (key, _) -> key }.sorted()
return if (keyWithValues.containsAll(requiredProps)) {
isValidPassport(userMap)
} else {
false
}
}
/**
byr (Birth Year) - four digits; at least 1920 and at most 2002.
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
hgt (Height) - a number followed by either cm or in:
If cm, the number must be at least 150 and at most 193.
If in, the number must be at least 59 and at most 76.
hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
pid (Passport ID) - a nine-digit number, including leading zeroes.
cid (Country ID) - ignored, missing or not.
*/
private fun isValidPassport(userMap: Map<String, String>): Boolean {
userMap.forEach { (key, value) ->
if (key == "byr" && (value.length != 4 || value.length == 4 && value.toInt() !in 1920..2002)) {
return false
}
if (key == "iyr" && (value.length != 4 || value.length == 4 && value.toInt() !in 2010..2020)) {
return false
}
if (key == "eyr" && (value.length != 4 || value.length == 4 && value.toInt() !in 2020..2030)) {
return false
}
if (key == "hgt" && value.contains("cm")) {
val v = value.trim().replace("cm", "")
if (v.length != 3 || v.length == 3 && v.toInt() !in 150..193) {
return false
}
} else if (key == "hgt" && value.contains("in")) {
val v = value.trim().replace("in", "")
if (v.length != 2 || v.length == 2 && v.toInt() !in 59..76) {
return false
}
} else if (key == "hgt") {
return false
}
if (key == "hcl" && !value.matches("\\#[a-f0-9]{6}".toRegex())) {
return false
}
val validEyeColors = "amb blu brn gry grn hzl oth".split(" ").toList()
if (key == "ecl" && !validEyeColors.contains(value)) {
return false
}
if (key == "pid" && !value.matches("[0-9]{9}".toRegex())) {
return false
}
}
return true
}
| 0 | Kotlin | 0 | 0 | 2fca82225a19144bbbca39247ba57c42a30ef459 | 4,512 | aoc2020 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/WaysToBuildRooms.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
/**
* 1916. Count Ways to Build Rooms in an Ant Colony
* @see <a href="https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/">Source</a>
*/
fun interface WaysToBuildRooms {
operator fun invoke(prevRoom: IntArray): Int
}
class WaysToBuildRoomsDFS : WaysToBuildRooms {
override operator fun invoke(prevRoom: IntArray): Int {
val n: Int = prevRoom.size
val tree: Array<ArrayList<Int>> = Array(n) { ArrayList() }
for (i in 0 until n) {
tree[i] = ArrayList()
}
// Add the directed edges
// Here each edge will be directed from room[i] to i. Denoting that we need to build room[i]
// first before room 'i'.
for (i in 1 until prevRoom.size) {
tree[prevRoom[i]].add(i)
}
// To store the subtree size for each node.
val size = IntArray(n)
dfs(tree, size, 0)
// Find n factorial
var nFact: Long = 1
for (i in 2..n) {
nFact = nFact * i % MOD
}
// Product of all the sizes of subtrees.
var den: Long = 1
for (i in 0 until n) {
den = den * size[i] % MOD
}
val d = den.toInt()
// To divide two number using modulo we find modulo inverse of denominator with mod and then multiply it with
// the numerator.
val inverse = modInverse(d)
return (nFact * inverse % MOD).toInt()
}
// To Calculate the size of subtree i.e total number of nodes below the given node in the tree.
private fun dfs(tree: Array<ArrayList<Int>>, size: IntArray, root: Int): Int {
var ans = 1
for (e in tree[root]) {
ans += dfs(tree, size, e)
}
size[root] = ans
return ans
}
private fun modInverse(a: Int): Int {
return power(a, MOD - 2, MOD)
}
private fun power(x: Int, y: Int, m: Int): Int {
if (y == 0) return 1
var p = power(x, y / 2, m) % m
p = (p * p.toLong() % m).toInt()
return if (y % 2 == 0) p else (x * p.toLong() % m).toInt()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,786 | kotlab | Apache License 2.0 |
src/Day05.kt | olezhabobrov | 572,687,414 | false | {"Kotlin": 27363} | fun main() {
fun initialForTest(): List<MutableList<Char>> {
val size = 3
val crates = arrayListOf(
mutableListOf('Z', 'N'),
mutableListOf('M', 'C', 'D'),
mutableListOf('P')
)
return crates
}
fun initial(): List<MutableList<Char>> {
val size = 9
val crates = arrayListOf(
mutableListOf('H', 'B', 'V', 'W', 'N', 'M', 'L', 'P'),
mutableListOf('M', 'Q', 'H'),
mutableListOf('N', 'D', 'B', 'G', 'F', 'Q', 'M', 'L'),
mutableListOf('Z', 'T', 'F', 'Q', 'M', 'W', 'G'),
mutableListOf('M', 'T', 'H', 'P'),
mutableListOf('C', 'B', 'M', 'J', 'D', 'H', 'G', 'T'),
mutableListOf('M', 'N', 'B', 'F', 'V', 'R'),
mutableListOf('P', 'L', 'H', 'M', 'R', 'G', 'S'),
mutableListOf('P', 'D', 'B', 'C', 'N')
)
return crates
}
// [P] [L] [T]
// [L] [M] [G] [G] [S]
// [M] [Q] [W] [H] [R] [G]
// [N] [F] [M] [D] [V] [R] [N]
// [W] [G] [Q] [P] [J] [F] [M] [C]
// [V] [H] [B] [F] [H] [M] [B] [H] [B]
// [B] [Q] [D] [T] [T] [B] [N] [L] [D]
// [H] [M] [N] [Z] [M] [C] [M] [P] [P]
// 1 2 3 4 5 6 7 8 9
fun part1(input: List<String>, isTest: Boolean): String {
val crates = if (isTest) initialForTest() else initial()
input.forEach { instruction ->
val (k, from, to) = instruction.split(" ").map { it.toIntOrNull() }.filter { it != null }.map{it!! - 1}
repeat(k + 1) {
val element = crates[from].removeLast()
crates[to].add(element)
}
}
var result = ""
crates.forEach {
result += it.last()
}
return result
}
fun part2(input: List<String>, isTest: Boolean): String {
val crates = if (isTest) initialForTest() else initial()
input.forEach { instruction ->
val (k, from, to) = instruction.split(" ").map { it.toIntOrNull() }.filter { it != null }.map{it!! - 1}
val toMove = mutableListOf<Char>()
repeat(k + 1) {
toMove.add(crates[from].removeLast())
}
toMove.reversed().forEach { crates[to].add(it) }
}
var result = ""
crates.forEach {
result += it.last()
}
return result
}
val inputTest = readInput("Day05_test")
check(part1(inputTest, true) == "CMZ")
check(part2(inputTest, true) == "MCD")
val input = readInput("Day05")
println(part1(input, false))
println(part2(input, false))
}
| 0 | Kotlin | 0 | 0 | 31f2419230c42f72137c6cd2c9a627492313d8fb | 2,689 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2021/Day5.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
import kotlin.math.abs
import kotlin.math.sign
class Day5 : AdventDay(2021, 5) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day5()
report {
day.part1()
}
report {
day.part2()
}
}
fun Int.diff(other: Int) = abs(this - other)
}
val inputLines = parseInput(inputAsLines)
fun part1(): Int {
val lines = inputLines.filter { it.isHorizontal || it.isVertical }
val points = findPoints(lines)
return points.values.count { it > 1 }
}
fun findPoints(lines: List<Line>): Map<Point, Int> {
return lines.fold(mutableMapOf()) { matches, line ->
line.allPoints.forEach {
matches.merge(it, 1) { old, new -> old + new }
}
matches
}
}
fun part2(): Int {
val points = findPoints(inputLines)
return points.values.count { it > 1 }
}
fun parseInput(input: List<String>): List<Line> {
return input.map { Line(it) }
}
data class Line(val start: Point, val end: Point) {
val signX = sign((end.x - start.x).toDouble()).toInt()
val signY = sign((end.y - start.y).toDouble()).toInt()
val delta = Point(signX, signY)
constructor(input: String) : this(
start = Point(
input.split("->").first().trim().split(",").first().toInt(),
input.split("->").first().trim().split(",").last().toInt()
),
end = Point(
input.split("->").last().trim().split(",").first().toInt(),
input.split("->").last().trim().split(",").last().toInt()
)
)
val allPoints: List<Point> =
generateSequence(start) { p ->
if (p != end) {
p + delta
} else {
null
}
}.toList()
fun covers(p: Point): Boolean = allPoints.contains(p)
val isVertical = start.x == end.x
val isHorizontal = start.y == end.y
}
data class Point(val x: Int, val y: Int) {
operator fun minus(other: Point): Point = Point(x - other.x, y - other.y)
operator fun plus(other: Point): Point = Point(x + other.x, y + other.y)
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,492 | adventofcode | MIT License |
src/main/kotlin/day23/Day23.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day23
import runDay
import utils.Point
import utils.Ring
fun main() {
fun part1(input: List<String>) =
input.toElves()
.let { allElves ->
var positions = allElves
var movesToTry = possibleMoves
repeat(10) { i ->
positions = positions.fold(mutableMapOf<Elf, List<Elf>>()) { attempts, elf ->
val next = elf.attemptToMove(positions, movesToTry)
attempts.compute(next) { _, elves ->
when (elves) {
null -> listOf(elf)
else -> elves + elf
}
}
attempts
}.flatMap { (next, originals) ->
when (originals.size) {
1 -> listOf(next)
else -> originals
}
}.toSet()
movesToTry = movesToTry.next
}
positions
}.let { elves ->
val min = Point(
x = elves.minOf { it.x },
y = elves.minOf { it.y },
)
val max = Point(
x = elves.maxOf { it.x },
y = elves.maxOf { it.y },
)
(max.x - min.x + 1) * (max.y - min.y + 1) - elves.size
}
fun part2(input: List<String>) =
input.toElves()
.let { allElves ->
var positions = allElves
var movesToTry = possibleMoves
repeat(Int.MAX_VALUE) { i ->
val oldPositions = positions
positions = positions.fold(mutableMapOf<Elf, List<Elf>>()) { attempts, elf ->
val next = elf.attemptToMove(positions, movesToTry)
attempts.compute(next) { _, elves ->
when (elves) {
null -> listOf(elf)
else -> elves + elf
}
}
attempts
}.flatMap { (next, originals) ->
when (originals.size) {
1 -> listOf(next)
else -> originals
}
}.toSet()
movesToTry = movesToTry.next
if (oldPositions.intersect(positions) == positions) {
return i + 1
}
}
Int.MAX_VALUE
}
(object {}).runDay(
part1 = ::part1,
part1Check = 110,
part2 = ::part2,
part2Check = 20,
)
}
val possibleMoves = Ring(
MovementAttempt(Elf::noneNorth) { copy(y = y - 1) },
MovementAttempt(Elf::noneSouth) { copy(y = y + 1) },
MovementAttempt(Elf::noneWest) { copy(x = x - 1) },
MovementAttempt(Elf::noneEast) { copy(x = x + 1) },
)
fun Elf.attemptToMove(allElves: Set<Elf>, possibilities: Ring<MovementAttempt>): Elf {
if (this.isAlone(allElves)) return this
for (attempt in possibilities) {
return attempt(this, allElves) ?: continue
}
return this
}
typealias Elf = Point
data class MovementAttempt(val check: Elf.(Set<Elf>) -> Boolean, val move: Elf.() -> Elf) {
operator fun invoke(elf: Elf, allElves: Set<Elf>): Elf? = when (elf.check(allElves)) {
true -> elf.move()
false -> null
}
}
fun Elf.isAlone(allElves: Set<Elf>) = listOf(
Elf(x - 1, y - 1),
Elf(x, y - 1),
Elf(x + 1, y - 1),
Elf(x + 1, y),
Elf(x + 1, y + 1),
Elf(x, y + 1),
Elf(x - 1, y + 1),
Elf(x - 1, y),
).intersect(allElves).none()
fun Elf.noneNorth(allElves: Set<Elf>) = listOf(
Elf(x - 1, y - 1),
Elf(x, y - 1),
Elf(x + 1, y - 1),
).intersect(allElves).none()
fun Elf.noneSouth(allElves: Set<Point>) = listOf(
Elf(x - 1, y + 1),
Elf(x, y + 1),
Elf(x + 1, y + 1),
).intersect(allElves).none()
fun Elf.noneWest(allElves: Set<Point>) = listOf(
Elf(x - 1, y - 1),
Elf(x - 1, y),
Elf(x - 1, y + 1),
).intersect(allElves).none()
fun Elf.noneEast(allElves: Set<Point>) = listOf(
Elf(x + 1, y - 1),
Elf(x + 1, y),
Elf(x + 1, y + 1),
).intersect(allElves).none()
fun List<String>.toElves() = flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, cell ->
when (cell) {
'#' -> Point(x, y)
else -> null
}
}
}.toSet() | 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 4,667 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/EvaluateDivision.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
/**
* 399. Evaluate Division
* @see <a href="https://leetcode.com/problems/evaluate-division/">Source</a>
*/
fun interface EvaluateDivision {
fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray
}
class EvaluateDivisionDFS : EvaluateDivision {
override fun calcEquation(
equations: List<List<String>>,
values: DoubleArray,
queries: List<List<String>>,
): DoubleArray {
val m: MutableMap<String?, MutableMap<String, Double>> = HashMap()
for (i in values.indices) {
m.putIfAbsent(equations[i][0], HashMap())
m.putIfAbsent(equations[i][1], HashMap())
m[equations[i][0]]!![equations[i][1]] = values[i]
m[equations[i][1]]!![equations[i][0]] = 1 / values[i]
}
val r = DoubleArray(queries.size)
for (i in queries.indices) {
r[i] = dfs(queries[i][0], queries[i][1], 1.0, m, HashSet())
}
return r
}
private fun dfs(
s: String,
t: String,
r: Double,
m: Map<String?, Map<String, Double>>,
seen: MutableSet<String?>,
): Double {
if (!m.containsKey(s) || !seen.add(s)) return (-1).toDouble()
if (s == t) return r
val next = m[s]!!
for (c in next.keys) {
val result = dfs(c, t, r * next[c]!!, m, seen)
if (result != -1.0) return result
}
return (-1).toDouble()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,136 | kotlab | Apache License 2.0 |
day17/src/main/kotlin/App.kt | ascheja | 317,918,055 | false | null | package net.sinceat.aoc2020.day17
fun main() {
run {
var grid = Grid(readInput("testinput.txt") { x, y -> GridPoint3d(x, y, 0) }, ::drawGrid3d)
(1 .. 6).forEach {
grid = grid.evolve()
}
println(grid.countActive())
println()
}
run {
var grid = Grid(readInput("input.txt") { x, y -> GridPoint3d(x, y, 0) }, ::drawGrid3d)
(1 .. 6).forEach {
grid = grid.evolve()
}
println(grid.countActive())
println()
}
run {
var grid = Grid(readInput("testinput.txt") { x, y -> GridPoint4d(x, y, 0, 0) }, ::drawGrid4d)
(1 .. 6).forEach {
grid = grid.evolve()
}
println(grid.countActive())
println()
}
run {
var grid = Grid(readInput("input.txt") { x, y -> GridPoint4d(x, y, 0, 0) }, ::drawGrid4d)
(1 .. 6).forEach {
grid = grid.evolve()
}
println(grid.countActive())
println()
}
}
fun <T> readInput(fileName: String, mapper: (Int, Int) -> T): Map<T, Char> {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
lines.filter(String::isNotEmpty).flatMapIndexed { yIndex, line ->
line.toCharArray().mapIndexed { xIndex, char -> if (char == '#') mapper(xIndex, yIndex) else null }.filterNotNull()
}.associateWith { '#' }
}
}
fun <T : GridPoint<T>> Grid<T>.evolve(): Grid<T> {
val allActive = data.filterValues { it == '#' }.keys
val remainingActive = allActive.filter { gridPoint ->
gridPoint.neighbors().filter { it in allActive }.count() in 2 .. 3
}
val goingActive = allActive.flatMap { activeNeighbor ->
val inactiveNeighbors = activeNeighbor.neighbors().filter { it !in allActive }
inactiveNeighbors.map { inactiveNeighbor -> Pair(inactiveNeighbor, activeNeighbor) }
}.groupBy { it.first }
.mapValues { (_, pairs) -> pairs.map { it.second }.distinct().count() }
.filterValues { it == 3 }
.keys
return Grid((remainingActive + goingActive).associateWith { '#' }, formatter)
}
fun <T : GridPoint<T>> Grid<T>.countActive(): Int {
return data.size
}
fun drawGrid3d(data: Map<GridPoint3d, Char>) = buildString {
if (data.isEmpty()) {
return ""
}
val xs = data.keys.map(GridPoint3d::x)
val ys = data.keys.map(GridPoint3d::y)
val zs = data.keys.map(GridPoint3d::z)
val xRange = xs.minOrNull()!! .. xs.maxOrNull()!!
val yRange = ys.minOrNull()!! .. ys.maxOrNull()!!
val zRange = zs.minOrNull()!! .. zs.maxOrNull()!!
for (z in zRange) {
appendLine("z=$z")
for (y in yRange) {
for (x in xRange) {
append(data[GridPoint3d(x, y, z)] ?: '.')
}
appendLine()
}
appendLine()
}
}
fun drawGrid4d(data: Map<GridPoint4d, Char>) = buildString {
if (data.isEmpty()) {
return ""
}
val xs = data.keys.map(GridPoint4d::x)
val ys = data.keys.map(GridPoint4d::y)
val zs = data.keys.map(GridPoint4d::z)
val ws = data.keys.map(GridPoint4d::w)
val xRange = xs.minOrNull()!! .. xs.maxOrNull()!!
val yRange = ys.minOrNull()!! .. ys.maxOrNull()!!
val zRange = zs.minOrNull()!! .. zs.maxOrNull()!!
val wRange = ws.minOrNull()!! .. ws.maxOrNull()!!
for (w in wRange) {
for (z in zRange) {
appendLine("z=$z,w=$w")
for (y in yRange) {
for (x in xRange) {
append(data[GridPoint4d(x, y, z, w)] ?: '.')
}
appendLine()
}
appendLine()
}
}
}
interface GridPoint<T : GridPoint<T>> {
fun neighbors(): List<T>
operator fun compareTo(other: T): Int
}
data class GridPoint3d(val x: Int, val y: Int, val z: Int) : GridPoint<GridPoint3d> {
override fun neighbors(): List<GridPoint3d> {
return sequence {
for (nx in (x - 1) .. (x + 1)) {
for (ny in (y - 1) .. (y + 1)) {
for (nz in (z - 1) .. (z + 1)) {
if (nx == x && ny == y && nz == z) {
continue
}
yield(GridPoint3d(nx, ny, nz))
}
}
}
}.toList()
}
override fun compareTo(other: GridPoint3d): Int {
val xCmp = x.compareTo(other.x)
if (xCmp != 0) {
return xCmp
}
val yCmp = y.compareTo(other.y)
if (yCmp != 0) {
return yCmp
}
return z.compareTo(other.z)
}
}
data class GridPoint4d(val x: Int, val y: Int, val z: Int, val w: Int) : GridPoint<GridPoint4d> {
override fun neighbors(): List<GridPoint4d> {
return sequence {
for (nx in (x - 1) .. (x + 1)) {
for (ny in (y - 1) .. (y + 1)) {
for (nz in (z - 1) .. (z + 1)) {
for (nw in (w - 1) .. (w + 1)) {
if (nx == x && ny == y && nz == z && nw == w) {
continue
}
yield(GridPoint4d(nx, ny, nz, nw))
}
}
}
}
}.toList()
}
override fun compareTo(other: GridPoint4d): Int {
val cmp3d = reduce().compareTo(other.reduce())
if (cmp3d != 0) return cmp3d
return w.compareTo(other.w)
}
private fun reduce(): GridPoint3d = GridPoint3d(x, y, z)
}
class Grid<T : GridPoint<T>>(val data: Map<T, Char>, val formatter: (Map<T, Char>) -> String) {
override fun toString(): String = formatter(data)
}
| 0 | Kotlin | 0 | 0 | f115063875d4d79da32cbdd44ff688f9b418d25e | 5,784 | aoc2020 | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year18/Day15.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year18
import com.grappenmaker.aoc.*
import java.util.*
fun PuzzleSet.day15() = puzzle(day = 15) {
val initialGrid = inputLines.asCharGrid().mapIndexedElements { p, v ->
when (v) {
'.' -> EmptySquare
'#' -> Wall
else -> Battler(v == 'E', p)
}
}
val toDiscuss = initialGrid.points.filterNot { initialGrid[it] == Wall }
data class State(val grid: Grid<Square>, val canContinue: Boolean = true, val elfDied: Boolean = false)
// stupidly bad code ahead
fun State.step(): State {
var newElfDied = elfDied
return State(grid.asMutableGrid().apply {
val readingOrder = compareBy<Point> { it.y }.thenBy { it.x }
val neighbors = { p: Point -> p.adjacentSides().filter { this[it] == EmptySquare } }
val justMoved = hashSetOf<Point>()
for (p in toDiscuss) {
if (p in justMoved) continue
val battler = this[p] as? Battler ?: continue
val targets = elements.filterIsInstance<Battler>().filter { it.elf != battler.elf }
if (targets.isEmpty()) return State(asGrid(), false, newElfDied)
val inRange = targets.flatMap {
it.point.adjacentSides().filter { t -> this[t] == EmptySquare || t == p }
}
val newPosition = if (p !in inRange) {
val ourNeighbors = neighbors(p).toSet()
val chosen = inRange.minWithOrNull(compareBy<Point> { t ->
bfsDistance(p, { it == t }, neighbors).dist.takeIf { it != -1 } ?: Int.MAX_VALUE
}.then(readingOrder)) ?: continue
val poss = fillDistance(chosen, neighbors).filterKeys { it in ourNeighbors }
val dist = poss.values.minOrNull() ?: continue
val moveTo = poss.filterValues { it == dist }.keys.minWith(readingOrder)
Collections.swap(elements, p.toIndex(), moveTo.toIndex())
this[moveTo] = battler.copy(point = moveTo)
moveTo.also { justMoved += it }
} else p
val adjacent = newPosition.adjacentSides().toSet()
val toAttack = targets.filter { it.point in adjacent }.minWithOrNull(
compareBy<Battler> { it.hp }.thenBy(readingOrder) { it.point }
) ?: continue
val newHP = toAttack.hp - battler.power
this[toAttack.point] = if (newHP <= 0) {
if (toAttack.elf) newElfDied = true
EmptySquare
} else toAttack.copy(hp = newHP)
}
}.asGrid(), true, newElfDied)
}
fun Grid<Square>.healthSum() = elements.filterIsInstance<Battler>().sumOf { it.hp }
fun IndexedValue<State>.outcome() = (index - 1) * value.grid.healthSum()
partOne = generateSequence(State(initialGrid)) { it.step() }
.takeUntil { it.canContinue }.withIndex().last().outcome().s()
partTwo = generateSequence(4, Int::inc).firstNotNullOf { elfPower ->
val improvedGrid = initialGrid.mapElements { if (it is Battler && it.elf) it.copy(power = elfPower) else it }
val result = generateSequence(State(improvedGrid)) { it.step() }
.takeUntil { it.canContinue && !it.elfDied }.withIndex().last()
if (result.value.elfDied) null else result.outcome()
}.s()
}
sealed interface Square
data class Battler(val elf: Boolean, val point: Point, val hp: Int = 200, val power: Int = 3) : Square
data object EmptySquare : Square
data object Wall : Square | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 3,684 | advent-of-code | The Unlicense |
src/day05/Day05.kt | gagandeep-io | 573,585,563 | false | {"Kotlin": 9775} | package day05
import readInput
import java.util.Stack
fun main() {
fun part1(input: List<String>): String {
val index = input.indexOfFirst { it.isBlank() || it.isEmpty() }
val cratesDiagram:List<String> = input.subList(0, index)
val lastLine = cratesDiagram.last()
val numberOfCrates = lastLine.trim().last().code - 48
val crates: MutableList<Stack<Char>> = ArrayList(numberOfCrates)
repeat(numberOfCrates) {
crates.add(Stack<Char>())
}
for (lineNum in (cratesDiagram.size - 2) downTo 0) {
val inputLine = cratesDiagram[lineNum]
inputLine.updateCrates(crates)
}
crates.forEachIndexed { index, crate -> println("Crate ${index + 1} has $crate") }
input.subList(index + 1, input.size).forEach {
val parts = it.trimEnd().split(" ")
val nCratesToBeMoved = parts[1].toInt()
val source = parts[3].toInt()
val destination = parts[5].toInt()
val sourceCrate = crates[source - 1]
val destinationCrate = crates[destination - 1]
val tempCrate = Stack<Char>()
repeat(nCratesToBeMoved) {
tempCrate.push(sourceCrate.pop())
}
repeat(nCratesToBeMoved) {
destinationCrate.push(tempCrate.pop())
}
}
return crates.joinToString("") { it.peek().toString() }
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
/*val testInput = readInput("DayN_test")
check(part1(testInput) == 1)*/
val input = readInput("day05/Day05_test")
println(part1(input))
println(part2(input))
}
private fun String.updateCrates(crates: List<Stack<Char>>) {
var index = 1
var crateNumber = 0
while (index < trimEnd().length && crateNumber < crates.size) {
val crate = crates[crateNumber]
if (this[index] != ' ') {
crate.push(this[index])
}
index += 4
crateNumber++
}
} | 0 | Kotlin | 0 | 0 | 952887dd94ccc81c6a8763abade862e2d73ef924 | 2,123 | aoc-2022-kotlin | Apache License 2.0 |
src/year2022/03/Day03.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`03`
import readInput
const val ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun main() {
val ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun part1(input: List<String>): Int {
return input
.map { s1 ->
val mid: Int = s1.length / 2
s1.substring(0, mid) to s1.substring(mid)
}
.sumOf { (s1, s2) ->
val union = s1.toSet().intersect(s2.toSet())
union.sumOf { ALPHABET.indexOf(it).inc() }
}
}
fun part2(input: List<String>): Int {
val windowSize = 3
return input
.windowed(windowSize, windowSize)
.sumOf { rucksacks ->
val unique = rucksacks
.map { it.toSet() }
.reduce { init, item -> init.intersect(item) }
unique.sumOf { ALPHABET.indexOf(it).inc() }
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
val part2Test = part2(testInput)
println(part2Test)
check(part2Test == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 1,277 | KotlinAdventOfCode | Apache License 2.0 |
src/Day03.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} |
fun Char.toPriority() = when (this) {
in 'a'..'z' -> this-'a'+1
in 'A'..'Z' -> this-'A'+27
else -> error("Invalid item $this")
}
private fun part1(lines: List<String>) = lines.sumOf { l ->
val a = l.substring(0, l.length / 2)
val b = l.substring(l.length / 2)
a.first { it in b }.toPriority()
}
private fun part2(lines: List<String>) = lines.chunked(3).sumOf { (a, b, c) ->
a.first { it in b && it in c }.toPriority()
}
fun main() {
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input)) // 7917
println(part2(input)) // 2585
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 686 | aoc2022 | Apache License 2.0 |
solutions/src/Day10.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | fun main() {
fun part1(input: List<String>): Int {
val cycleValues = mutableListOf<Int>()
var cycle = 0
var x = 1
input.forEach { line ->
val instruction = line.substring(0, 4)
when (instruction) {
"addx" -> {
val (_, number) = line.split(" ")
if (cycle % 40 == 18 && cycle <= 220) {
cycleValues.add(x * (cycle + 2))
} else if (cycle % 40 == 19 && cycle <= 220) {
cycleValues.add(x * (cycle + 1))
}
x += number.toInt()
cycle += 2
}
"noop" -> {
if (cycle % 40 == 19 && cycle <= 220) {
cycleValues.add(x * (cycle + 1))
}
cycle++
}
}
}
return cycleValues.sum()
}
fun part2(input: List<String>) {
var cycle = 1
var x = 1
fun charToDraw(): String {
return if (cycle - 1 >= x - 1 && cycle - 1 <= x + 1) {
"#"
} else {
"."
}
}
input.flatMap { line ->
val charsToDraw = mutableListOf<String>()
if (cycle == 41) {
cycle = 1
}
charsToDraw.add(charToDraw())
val instruction = line.substring(0, 4)
when (instruction) {
"addx" -> {
val (_, number) = line.split(" ")
cycle++
if (cycle == 41) {
cycle = 1
}
charsToDraw.add(charToDraw())
x += number.toInt()
cycle++
}
"noop" -> cycle++
}
charsToDraw
}.chunked(40).forEach { println(it.joinToString("")) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13_140)
part2(testInput)
val input = readInput("Day10")
println(part1(input))
part2(input)
} | 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 2,255 | advent-of-code-22 | Apache License 2.0 |
ShortestPalindrome.kt | ncschroeder | 604,822,497 | false | {"Kotlin": 19399} | /*
https://leetcode.com/problems/shortest-palindrome/
You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.
Return the shortest palindrome you can find by performing this transformation.
Examples:
Input: s = "aacecaaa"
Output: "aaacecaaa"
Input: s = "abcd"
Output: "dcbabcd"
*/
/*
Find the longest palindrome that can be made by dropping chars from the right. Start by "dropping" 0 chars. When a palindrome is found:
get a string of the dropped chars, reverse it, and prepend it to the param string. When we drop all chars besides the 1st one, the string
formed as a result will always be a palindrome.
*/
fun String.isPalindrome(): Boolean =
(0 until length / 2).all { this[it] == this[lastIndex - it] }
// Original solution
fun shortestPalindrome1(s: String): String {
if (s.length in 0..1) {
return s
}
// isPalindrome was a normal function for this solution, instead of an extension function
val i: Int? = (0..s.length - 2).firstOrNull { isPalindrome(s.dropLast(it)) }
if (i != null) {
return s.takeLast(i).reversed() + s
}
val j: Int = (1..s.lastIndex).first { s[it] != s.first() }
return s.drop(j).reversed() + s
}
// Refactored solution
fun shortestPalindrome2(s: String): String =
if (s.isEmpty()) s
else (s.length downTo 1)
.first { s.take(it).isPalindrome() }
.let { s.drop(it).reversed() + s } | 0 | Kotlin | 0 | 0 | c77d0c8bb0595e61960193fc9b0c7a31952e8e48 | 1,476 | Coding-Challenges | MIT License |
src/main/kotlin/Day03.kt | michaeljwood | 572,560,528 | false | {"Kotlin": 5391} | fun main() {
fun part1(input: List<String>) = input.filter { it.isNotBlank() }
.map {
Pair(
it.substring(0, it.length / 2).toCharArray().toSet(),
it.substring(it.length / 2).toCharArray().toSet()
)
}
.map { it.first.intersect(it.second) }
.sumOf { chars.indexOf(it.first()) + 1 }
fun part2(input: List<String>) = input.filter { it.isNotBlank() }
.chunked(3)
.map { it.first().toCharArray().intersect(it[1].toCharArray().toSet()).intersect(it[2].toCharArray().toSet()) }
.sumOf { chars.indexOf(it.first()) + 1 }
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("day3/test")
check(part1(testInput) == 157)
val input = readInputLines("day3/input")
println(part1(input))
println(part2(input))
}
private val chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()
| 0 | Kotlin | 0 | 0 | 8df2121f12a5a967b25ce34bce6678ab9afe4aa7 | 979 | advent-of-code-2022 | Apache License 2.0 |
kotlin/1425-constrained-subsequence-sum.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | // Time O(nlogn) and space O(n) using max heap
class Solution {
fun constrainedSubsetSum(nums: IntArray, k: Int): Int {
var res = nums[0]
val maxHeap = PriorityQueue<IntArray>() { a, b -> b[0] - a[0] }
maxHeap.add(intArrayOf(nums[0], 0))
for (i in 1 until nums.size) {
while (i - maxHeap.peek()[1] > k)
maxHeap.poll()
var curMax = maxOf(nums[i], nums[i] + maxHeap.peek()[0])
res = maxOf(res, curMax)
maxHeap.add(intArrayOf(curMax, i))
}
return res
}
}
// Time O(n) and space O(n) using monotonic array/list
class Solution {
fun constrainedSubsetSum(nums: IntArray, k: Int): Int {
var win = LinkedList<Int>()
var res = Integer.MIN_VALUE
for (i in 0 until nums.size) {
nums[i] += (win.peekFirst() ?: 0)
res = maxOf(res, nums[i])
while (win.isNotEmpty() && win.peekLast() < nums[i])
win.removeLast()
if (nums[i] > 0)
win.addLast(nums[i])
if (i >= k && win.isNotEmpty() && win.peekFirst() == nums[i - k])
win.removeFirst()
}
return res
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,219 | leetcode | MIT License |
src/test/kotlin/chapter6/solutions/ex7/listing.kt | DavidGomesh | 680,857,367 | false | {"Kotlin": 204685} | package chapter6.solutions.ex7
import chapter3.Cons
import chapter3.List
import chapter3.Nil
import chapter3.foldRight
import chapter6.RNG
import chapter6.Rand
import chapter6.rng1
import chapter6.solutions.ex6.map2
import chapter6.unit
import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.WordSpec
//tag::init[]
//using a simpler recursive strategy, could blow the stack
fun <A> sequence(fs: List<Rand<A>>): Rand<List<A>> = { rng ->
when (fs) {
is Nil -> unit(List.empty<A>())(rng)
is Cons -> {
val (a, nrng) = fs.head(rng)
val (xa, frng) = sequence(fs.tail)(nrng)
Cons(a, xa) to frng
}
}
}
//a better approach using foldRight
fun <A> sequence2(fs: List<Rand<A>>): Rand<List<A>> =
foldRight(fs, unit(List.empty()), { f, acc ->
map2(f, acc, { h, t -> Cons(h, t) })
})
fun ints2(count: Int, rng: RNG): Pair<List<Int>, RNG> {
fun go(c: Int): List<Rand<Int>> =
if (c == 0) Nil
else Cons({ r -> 1 to r }, go(c - 1))
return sequence2(go(count))(rng)
}
//end::init[]
class Solution7 : WordSpec({
"sequence" should {
"""combine the results of many actions using
foldRight and map2""" {
val combined: Rand<List<Int>> =
sequence2(
List.of(
unit(1),
unit(2),
unit(3),
unit(4)
)
)
combined(rng1).first shouldBe List.of(1, 2, 3, 4)
}
"combine the results of many actions using recursion" {
val combined: Rand<List<Int>> =
sequence(
List.of(
unit(1),
unit(2),
unit(3),
unit(4)
)
)
combined(rng1).first shouldBe List.of(1, 2, 3, 4)
}
}
"ints" should {
"generate a list of ints of a specified length" {
ints2(4, rng1).first shouldBe
List.of(1, 1, 1, 1)
}
}
})
| 0 | Kotlin | 0 | 0 | 41fd131cd5049cbafce8efff044bc00d8acddebd | 2,212 | fp-kotlin | MIT License |
src/Day10/Day10.kt | AllePilli | 572,859,920 | false | {"Kotlin": 47397} | package Day10
import checkAndPrint
import measureAndPrintTimeMillis
import readInput
import kotlin.math.abs
fun main() {
fun List<String>.prepareInput(): List<Operation> {
val addxRgx = """addx (-?\d+)""".toRegex()
val noopRgx = "noop".toRegex()
return map { line ->
addxRgx.matchEntire(line)?.groupValues?.drop(1)?.let { (amt) ->
Operation.Addx(amt.toInt())
} ?: noopRgx.matchEntire(line)?.let { Operation.NoOp() }
?: error("could not match line $line")
}
}
fun part1(input: List<Operation>): Int {
var x = 1
var cycle = 0
return buildList {
fun postValue() {
if (cycle == 20 || (cycle - 20).coerceAtLeast(1) % 40 == 0) add(cycle * x)
}
input.forEach { op ->
repeat(op.completionTime) {
cycle++
postValue()
}
if (op is Operation.Addx) x += op.amt
}
}.sum()
}
fun part2(input: List<Operation>) {
var x = 1
var crtX = 0
var cycle = 0
input.forEach { op ->
repeat(op.completionTime) {
cycle++
print(if (abs(x - crtX) > 1) "." else "#")
crtX = cycle % 40
if (crtX == 0) println()
}
if (op is Operation.Addx) x += op.amt
}
}
val testInput = readInput("Day10_test").prepareInput()
check(part1(testInput) == 13140)
part2(testInput)
println()
val input = readInput("Day10").prepareInput()
measureAndPrintTimeMillis {
checkAndPrint(part1(input), 13720)
}
measureAndPrintTimeMillis {
part2(input) // should be FBURHZCH
}
}
private sealed class Operation(val completionTime: Int) {
class Addx(val amt: Int): Operation(2)
class NoOp: Operation(1)
} | 0 | Kotlin | 0 | 0 | 614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643 | 1,942 | AdventOfCode2022 | Apache License 2.0 |
src/Day10.kt | zhtk | 579,137,192 | false | {"Kotlin": 9893} | fun main() {
fun part1(operations: List<Int>): Int {
var x = 1
return operations.mapIndexed { index, i ->
val cycle = index + 1
val signal = if (cycle <= 220 && (cycle - 20) % 40 == 0) x * cycle else 0
x += i
signal
}.sum()
}
fun part2(operations: List<Int>): List<String> {
var x = 1
return operations.chunked(40).map {
it.mapIndexed { index, i ->
val char = if (index - 1 <= x && x <= index + 1) '#' else '.'
x += i
char
}.joinToString("") { it.toString() }
}
}
val input = readInput("Day10").flatMap {
if (it == "noop") listOf(0) else listOf(0, it.drop("addx ".length).toInt())
}
part1(input).println()
part2(input).forEach { it.println() }
}
| 0 | Kotlin | 0 | 0 | bb498e93f9c1dd2cdd5699faa2736c2b359cc9f1 | 854 | aoc2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.