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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
solutions/src/solutions/y21/day 9.kt | Kroppeb | 225,582,260 | false | null | @file:Suppress("PackageDirectoryMismatch", "UnusedImport")
package solutions.y21.d9
/*
import grid.Clock
import helpers.*
import itertools.*
import kotlin.math.*
*/
import grid.Clock
import helpers.digits
import helpers.getLines
import helpers.map2
import helpers.transpose
val xxxxx = Clock(6, 3);
/*
*/
private fun part1() {
var data = getLines(2021_09).digits()//.log()
var count = 0
var pre = data.first().map { 9 }
data = listOf(listOf(pre), data, listOf(pre)).flatten().transpose()
pre = data.first().map { 10 }
data = listOf(listOf(pre), data, listOf(pre)).flatten().transpose()
data.windowed(3) {
it.transpose().windowed(3) { (a, b, c) ->
if (a[1] > b[1] && b[1] < c[1] && b[0] > b[1] && b[1] < b[2]) count += b[1] + 1;
}
}
count.log()
}
private fun part2() {
var data = getLines(2021_09).digits()
var count = 0
var pre = data.first().map { 9 }
data = listOf(listOf(pre), data, listOf(pre)).flatten().transpose()
pre = data.first().map { 10 }
data = listOf(listOf(pre), data, listOf(pre)).flatten().transpose()
var x = true;
var uuu = data.map2 { mutableListOf(it, (if (it < 9) 1 else 0)) }
while (x) {
x = false
//uuu.log()
uuu.forEach {
it.windowed(2) { (a, b) ->
if(a[1] != 0 || b[1] != 0){
if(a[0] < b[0]){
x = x || (b[1] != 0)
a[1] += b[1]
b[1] = 0
} else {
x = x || (a[1] != 0)
b[1] += a[1]
a[1] = 0
}
}
}
}
uuu.transpose().forEach {
it.windowed(2) { (a, b) ->
if(a[1] != 0 || b[1] != 0){
if(a[0] < b[0]){
x = x || (b[1] != 0)
a[1] += b[1]
b[1] = 0
} else {
x = x || (a[1] != 0)
b[1] += a[1]
a[1] = 0
}
}
}
}
}
//uuu.map2 { it[1] }.flatten().filter { it != 0 }.sorted().log()
var (a,b,c) = uuu.map2 { it[1] }.flatten().filter { it != 0 }.sorted().reversed()
println(a * b * c)
}
fun main() {
println("Day 9: ")
part1()
part2()
}
fun <T> T.log(): T = also { println(this) } | 0 | Kotlin | 0 | 1 | 744b02b4acd5c6799654be998a98c9baeaa25a79 | 2,506 | AdventOfCodeSolutions | MIT License |
src/Day06.kt | Migge | 572,695,764 | false | {"Kotlin": 9496} | private fun part1(input: List<String>): Int = markerIndex(input.first(), 4)
private fun part2(input: List<String>): Int = markerIndex(input.first(), 14)
private fun markerIndex(input: String, length: Int) = input
.toList()
.windowed(length)
.map { it.distinct() }
.first { it.size == length }
.join()
.let { input.indexOf(it) + length }
fun main() {
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c7ca68b2ec6b836e73464d7f5d115af3e6592a21 | 578 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day6/Day6Puzzle.kt | Any1s | 433,954,562 | false | {"Kotlin": 96683} | package de.mbdevelopment.adventofcode.year2021.solvers.day6
import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver
abstract class Day6Puzzle(private val days: Int) : PuzzleSolver {
companion object {
private const val BABY_TIMER = 8
}
final override fun solve(inputLines: Sequence<String>) = lanternfishPopulationAfter80Days2(inputLines).toString();
private fun lanternfishPopulationAfter80Days(initialPopulation: Sequence<String>): Int {
val population = initialPopulation
.filter { it.isNotBlank() }
.single()
.split(',')
.map { it.toInt() }
.toMutableList()
repeat(days) {
val newLanternfish = mutableListOf<Int>()
population.replaceAll {
val newTimer = it - 1
if (newTimer < 0) {
newLanternfish += BABY_TIMER
6
} else {
newTimer
}
}
population += newLanternfish
}
return population.size
}
private fun lanternfishPopulationAfter80Days2(initialPopulation: Sequence<String>): Long {
val population = initialPopulation
.filter { it.isNotBlank() }
.single()
.split(',')
.map { it.toInt() }
.groupBy { it }
.mapValues { it.value.size.toLong() }
.toMutableMap()
repeat(days) {
val newLanternfish = population.getOrDefault(0, 0L)
(1..8).forEach { timer ->
population[timer - 1] = population.getOrDefault(timer, 0L)
}
population[8] = newLanternfish
population[6] = population.getOrDefault(6, 0L) + newLanternfish
}
return population.values.reduce(Long::plus)
}
} | 0 | Kotlin | 0 | 0 | 21d3a0e69d39a643ca1fe22771099144e580f30e | 1,872 | AdventOfCode2021 | Apache License 2.0 |
src/_2015/Day05.kt | albertogarrido | 572,874,945 | false | {"Kotlin": 36434} | package _2015
import readInput
fun main() {
runTests()
runScenario(readInput("2015", "day05"))
}
private fun runScenario(input: List<String>) {
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) =
input.filter {
it.vowelsCount() >= 3 && it.hasNiceLetters() && !it.isNaughty()
}.size
private fun Char.isVowel() = this in vowels
private fun String.vowelsCount() = sumOf {
if (it.isVowel()) 1 as Int
else 0 as Int
}
private fun String.hasNiceLetters(): Boolean {
forEachIndexed { index, c ->
if (index < length - 1 && c == get(index + 1)) {
return true
}
}
return false
}
private fun String.isNaughty(): Boolean {
naughtyLetters.forEach {
if (this.contains(it)) return true
}
return false
}
private fun part2(input: List<String>) =
input.filter {
it.pairsNotOverlapping() && it.alternateLetters()
}.size
private fun String.alternateLetters(): Boolean {
forEachIndexed { i, c ->
if (i < length - 2 && c == get(i + 2)) {
return true
}
}
return false
}
private fun String.pairsNotOverlapping(): Boolean {
chunked(2).forEachIndexed { idx, s ->
}
return false
}
private val vowels by lazy { listOf('a', 'e', 'i', 'o', 'u') }
private val naughtyLetters by lazy { listOf("ab", "cd", "pq", "xy") }
private fun runTests() {
var passed = true
runCatching {
part1(readInput("2015", "day05_test_p1")).also {
check(it == 2) {
"part 1: expected 2, obtained $it"
}
}
}.onFailure {
passed = false
System.err.println("[test failed] ${it.message}")
}
runCatching {
part2(readInput("2015", "day05_test_p2")).also {
check(it == 2) {
"part 2: expected 2, obtained $it"
}
}
}.onFailure {
passed = false
System.err.println("[test failed] ${it.message}")
}
if (passed) println("\u001B[32m>> all tests passed <<\u001B[0m")
}
| 0 | Kotlin | 0 | 0 | ef310c5375f67d66f4709b5ac410d3a6a4889ca6 | 2,093 | AdventOfCode.kt | Apache License 2.0 |
src/main/kotlin/g2901_3000/s2913_subarrays_distinct_element_sum_of_squares_i/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2913_subarrays_distinct_element_sum_of_squares_i
// #Easy #Array #Hash_Table #2023_12_27_Time_184_ms_(95.74%)_Space_36.9_MB_(97.87%)
class Solution {
fun sumCounts(nums: List<Int>): Int {
val n = nums.size
if (n == 1) {
return 1
}
val numsArr = IntArray(n)
for (i in 0 until n) {
numsArr[i] = nums[i]
}
val prev = IntArray(n)
val foundAt = IntArray(101)
var dupFound = false
var j = 0
while (j < n) {
if (((foundAt[numsArr[j]] - 1).also { prev[j] = it }) >= 0) {
dupFound = true
}
foundAt[numsArr[j]] = ++j
}
if (!dupFound) {
return (((((n + 4) * n + 5) * n) + 2) * n) / 12
}
var result = 0
for (start in n - 1 downTo 0) {
var distinctCount = 0
for (i in start until n) {
if (prev[i] < start) {
distinctCount++
}
result += distinctCount * distinctCount
}
}
return result
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,141 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/AdjacencyMatrix.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.algo.algorithms.graph
import java.util.*
fun main() {
val adjM = AdjacencyMatrix(7)
adjM.accept(Scanner(System.`in`))
adjM.display()
// adjM.dfsTrav(0)
// adjM.dfsSpanningTree(0)
// adjM.bfsSpanningTree(0)
// println("${adjM.dfsIsConnected(0)}")
println("${adjM.biPartiteGraph(0)}")
// adjM.bfsSingleSourcePathLength(0)
}
class AdjacencyMatrix(var vertCount: Int = 0) {
private var edgeCount: Int = 0
private var matrix = Array(vertCount) { Array(vertCount) { 0 } }
fun accept(sc: Scanner) {
println("Enter edge count : ")
edgeCount = sc.nextInt()
println("Enter number of " + edgeCount + "src - - dst")
for (i in 0 until edgeCount) {
val src = sc.nextInt()
val dst = sc.nextInt()
matrix[src][dst] = 1
matrix[dst][src] = 1
}
}
fun display() {
for (i in 0 until vertCount) {
println()
for (j in 0 until edgeCount) {
print("\t${matrix[i][j]} ")
}
println()
}
}
fun dfsTrav(start: Int) {
val stack = Stack<Int>()
val visited = BooleanArray(vertCount) { false }
stack.push(start)
visited[start] = true
while (stack.isNotEmpty()) {
val vert = stack.pop()
print("\t $vert")
for (i in 0 until vertCount) {
if (!visited[i]
&& matrix[vert][i] == 1
) {
stack.push(i)
visited[i] = true
}
}
}
println()
}
fun dfsIsConnected(start: Int): Boolean {
val stack = Stack<Int>()
val visited = BooleanArray(vertCount) { false }
var count = 0
stack.push(start)
visited[start] = true
count++
while (stack.isNotEmpty()) {
val vert = stack.pop()
print("\t $vert")
for (i in 0 until vertCount) {
if (!visited[i]
&& matrix[vert][i] == 1
) {
stack.push(i)
visited[i] = true
count++
if (count == vertCount) {
return true
}
}
}
}
println()
return false
}
fun dfsSpanningTree(start: Int) {
val stack = Stack<Int>()
val visited = BooleanArray(vertCount) { false }
stack.push(start)
visited[start] = true
println("DFS spanning tree")
while (stack.isNotEmpty()) {
val vert = stack.pop()
for (i in 0 until vertCount) {
if (!visited[i]
&& matrix[vert][i] == 1
) {
stack.push(i)
visited[i] = true
println("Trev $vert --> $i")
}
}
}
println()
}
fun bfsSpanningTree(start: Int) {
val queue = LinkedList<Int>()
val visited = BooleanArray(vertCount) { false }
queue.offer(start)
visited[start] = true
println("BFS spanning tree")
while (queue.isNotEmpty()) {
val vert = queue.poll()
for (i in 0 until vertCount) {
if (matrix[vert][i] == 1
&& !visited[i]
) {
visited[i] = true
queue.offer(i)
println("Trev $vert --> $i")
}
}
}
println()
}
fun bfsSingleSourcePathLength(start: Int) {
val dist = IntArray(vertCount-1) {0}
val queue = LinkedList<Int>()
val visited = BooleanArray(vertCount) {false}
queue.offer(start)
visited[start] = true
println("Singel source path")
while (queue.isNotEmpty()) {
val vert = queue.poll()
for (i in 0 until vertCount) {
if (matrix[vert][i] == 1
&& !visited[i]) {
queue.offer(i)
visited[i] = true
dist[i] = dist[vert] + 1
}
}
}
for (d in dist) {
println("Distance from $start --> $d")
}
}
fun biPartiteGraph(start: Int) : Boolean {
val noColor = 0
val yellow = 1
val green = -1
val color = IntArray(vertCount) {noColor}
val queue = LinkedList<Int>()
queue.offer(start)
color[start] = yellow
println("Is bipartite graph")
while (queue.isNotEmpty()) {
val vert = queue.poll()
for (i in 0 until vertCount) {
if (matrix[vert][i] == 1) {
if (color[i] == color[vert]) {
return false
} else if (color[i] == noColor) {
queue.offer(i)
color[i] = -1 * color[vert]
}
}
}
}
return true
}
}
//Input data
/*
7
0 1
0 2
0 3
1 2
1 4
3 4
3 5
*/ | 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 5,266 | DS_Algo_Kotlin | MIT License |
src/main/kotlin/days/Day18.kt | poqueque | 430,806,840 | false | {"Kotlin": 101024} | package days
class Day18 : Day(18) {
fun add(s1: String, s2: String): String {
var s3 = "[$s1,$s2]"
var s4 = reduce1("[$s1,$s2]")
// println("Reduced -> $s4")
while (s4 != s3) {
s3 = s4
s4 = reduce1(s4)
// println("Reduced -> $s4")
}
return s4
}
fun reduce(initS: String): String {
var s1 = initS
var s2 = reduce1(s1)
// println("Reduced -> $s2")
while (s1 != s2) {
s1 = s2
s2 = reduce1(s1)
// println("Reduced -> $s2")
}
// println("Reduce done")
return s2
}
fun reduce1(initS: String): String {
var s = explode(initS)
if (s == initS) s = split(s)
return s
}
fun explode(s1: String): String {
var newS = ""
var level = 0
var hasReplaced = false
var lastIndexN = -1
var nextIndexN = -1
var toExplode = ""
var a = 0
var b = 0
var i = 0
while (i in s1.indices) {
when (s1[i]) {
'[' -> level++
']' -> level--
in '0'..'9' -> if (level <= 4) lastIndexN = i
}
if (level > 4 && !hasReplaced)
toExplode += s1[i]
else {
if (toExplode != "") {
val (strA,strB) = toExplode.replace("[","").split(",")
a = strA.toInt()
b = strB.toInt()
if (lastIndexN > 0){
var last = newS[lastIndexN].toString().toInt()
if (newS[lastIndexN-1] in '0'..'9') last += newS[lastIndexN - 1].toString().toInt() * 10
newS = newS.substring(0, if (last >= 10) lastIndexN-1 else lastIndexN) +
(a + last) +
newS.substring(lastIndexN + 1)
}
newS += "0"
toExplode = ""
hasReplaced = true
} else {
if (hasReplaced && nextIndexN < 0 && s1[i] in '0'..'9') {
var k = s1[i].toString().toInt()
if (s1[i+1] in '0'..'9') {
k = k*10 + s1[i+1].toString().toInt()
i++
}
newS += "${b + k}"
nextIndexN = i
} else
newS += s1[i]
}
}
i++
}
return newS
}
fun split(s: String): String {
var s1 = ""
var i = 0
var replaced = false
while (i < s.length) {
when (s[i]) {
'[' -> s1 += s[i]
']' -> s1 += s[i]
',' -> s1 += s[i]
in '0'..'9' -> {
if (s[i+1] in '0'..'9' && !replaced) {
val k = s[i].toString().toInt() * 10 + s[i + 1].toString().toInt()
val a = k/2
val b = k/2 + k%2
s1 += "[$a,$b]"
replaced = true
i++
} else {
s1 += s[i]
}
}
}
i++
}
return s1
}
override fun partOne(): Any {
var s = ""
inputList.forEach {
// val rit = reduce(it)
s = if (s == "") it else add(s, it)
// println("Added $it -> $s")
}
var s1 = s
return magnitude(s1)
}
private fun magnitude(s1: String): Int {
var values = listOf<Int>()
val magnitudes = mutableMapOf<String, Int>()
var s2 = s1
while (s2.contains("[")) {
var s = s2
s = s.replace("]",",")
s = s.replace("[",",")
while (s.contains(",,")) s = s.replace(",,",",")
values = s.split(",").filter { it != "" }.map { it.toInt() }.distinct()
for (i in values)
for (j in values)
magnitudes["[$i,$j]"] = 3 * i + 2 * j
for (m in magnitudes.keys) {
s2 = s2.replace(m, magnitudes[m].toString())
}
// println(s2)
}
return s2.toInt()
}
override fun partTwo(): Any {
var s = ""
var max = 0
for (i in inputList.indices)
for (j in inputList.indices)
if (i!=j){
val m = magnitude(add(inputList[i], inputList[j]))
if (m > max) {
max = m
// println("$i,$j -> $max")
}
}
return max
}
}
| 0 | Kotlin | 0 | 0 | 4fa363be46ca5cfcfb271a37564af15233f2a141 | 4,875 | adventofcode2021 | MIT License |
Algorithms/src/main/kotlin/MaxSubArray.kt | ILIYANGERMANOV | 557,496,216 | false | {"Kotlin": 74485} | /**
* # Maximum Subarray
* Problem:
* https://leetcode.com/problems/maximum-subarray/
*/
class MaxSubArray {
fun maxSubArray(nums: IntArray): Int {
val size = nums.size
if (size == 1) return nums[0]
var sum = nums.first()
var localMax = sum
for (i in 1 until size) {
val n = nums[i]
when {
n > 0 -> if (sum > 0) {
// n(+) + sum(+) => continue the sum: n + sum
sum += n
} else {
// n(+) + sum(-) => reset to n(+)
sum = n
}
else -> {
if (sum > 0) {
// n(-) + sum(+) => we can't know if we should reset the sum,
// because we can't predict the next numbers coming
// => 1) remember local max; 2) continue the sum;
localMax = maxOf(localMax, sum)
sum += n
} else {
// sum(-)
if (n > sum) {
// n(-) is better than sum(-) => reset the sum to n(-)
sum = n
} else {
// n(-) is worse than sum(-) but we can't predict the future
// => 1) remember local max; 2) continue the sum;
localMax = maxOf(localMax, sum)
sum += n
}
}
}
}
}
return maxOf(localMax, sum)
}
} | 0 | Kotlin | 0 | 1 | 4abe4b50b61c9d5fed252c40d361238de74e6f48 | 1,662 | algorithms | MIT License |
src/main/kotlin/leetcode/kotlin/dp/5. Longest Palindromic Substring.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.dp
// dp, bottom-up
// Time:O(n^2)
private fun longestPalindrome(str: String): String {
var table = Array<BooleanArray>(str.length) { BooleanArray(str.length) }
var max = 0
var start = 0 // beginning index of max palindrome
for (k in 1..str.length) { // size of palindrome
for (i in 0..str.length - k) { // start index
var j = i + k - 1
if (k == 1) { // single length palindrome
table[i][j] = true
} else if (k == 2) {
if (str[i] == str[j]) table[i][j] = true
} else { // for more than 3 length, w'll have middle elements
if (table[i + 1][j - 1] && str[i] == str[j]) table[i][j] = true
}
// we found new bigger palindrome
if (table[i][j] && k > max) {
max = k
start = i
}
// println("i$i, j=$j, k=$k table=${table[i][j]}, max=$max, start=$start")
}
}
return str.substring(start, start + max)
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 1,047 | kotlinmaster | Apache License 2.0 |
src/Day01.kt | cjosan | 573,106,026 | false | {"Kotlin": 5721} | fun main() {
fun part1(input: String): Int {
return input
.split("\n\n")
.maxOf { elfCalories ->
elfCalories.lines().sumOf { it.toInt() }
}
}
fun part2(input: String): Int {
return input
.split("\n\n")
.map { elfCalories ->
elfCalories.lines().sumOf { it.toInt() }
}
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readFile("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readFile("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a81f7fb9597361d45ff73ad2a705524cbc64008b | 758 | advent-of-code2022 | Apache License 2.0 |
src/Day06.kt | OskarWalczak | 573,349,185 | false | {"Kotlin": 22486} | import java.util.*
fun main() {
fun allElementsUnique(col: Collection<Char>): Boolean {
for(i in col.indices){
for(j in i+1 until col.size){
if(col.elementAt(i) == col.elementAt(j)){
return false
}
}
}
return true
}
fun part1(input: List<String>): Int {
val signal: String = input[0]
val chars: Queue<Char> = LinkedList()
for(i in signal.indices){
val c: Char = signal[i]
if(chars.size == 4){
chars.poll()
}
chars.offer(c)
if(chars.size == 4){
if(allElementsUnique(chars))
return i+1
}
}
return 0
}
fun part2(input: List<String>): Int {
val signal: String = input[0]
val chars: Queue<Char> = LinkedList()
for(i in signal.indices){
val c: Char = signal[i]
if(chars.size == 14){
chars.poll()
}
chars.offer(c)
if(chars.size == 14){
if(allElementsUnique(chars))
return i+1
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 10)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d34138860184b616771159984eb741dc37461705 | 1,490 | AoC2022 | Apache License 2.0 |
kmath-core/src/commonMain/kotlin/scientifik/kmath/histogram/PhantomHistogram.kt | Zelenyy | 164,850,230 | true | {"Kotlin": 84961} | package scientifik.kmath.histogram
import scientifik.kmath.linear.Vector
import scientifik.kmath.operations.Space
import scientifik.kmath.structures.NDStructure
import scientifik.kmath.structures.asSequence
data class BinTemplate<T : Comparable<T>>(val center: Vector<T, *>, val sizes: Point<T>) {
fun contains(vector: Point<out T>): Boolean {
if (vector.size != center.size) error("Dimension mismatch for input vector. Expected ${center.size}, but found ${vector.size}")
val upper = center.context.run { center + sizes / 2.0}
val lower = center.context.run {center - sizes / 2.0}
return vector.asSequence().mapIndexed { i, value ->
value in lower[i]..upper[i]
}.all { it }
}
}
/**
* A space to perform arithmetic operations on histograms
*/
interface HistogramSpace<T : Any, B : Bin<T>, H : Histogram<T, B>> : Space<H> {
/**
* Rules for performing operations on bins
*/
val binSpace: Space<Bin<T>>
}
class PhantomBin<T : Comparable<T>>(val template: BinTemplate<T>, override val value: Number) : Bin<T> {
override fun contains(vector: Point<out T>): Boolean = template.contains(vector)
override val dimension: Int
get() = template.center.size
override val center: Point<T>
get() = template.center
}
/**
* Immutable histogram with explicit structure for content and additional external bin description.
* Bin search is slow, but full histogram algebra is supported.
* @param bins map a template into structure index
*/
class PhantomHistogram<T : Comparable<T>>(
val bins: Map<BinTemplate<T>, IntArray>,
val data: NDStructure<Number>
) : Histogram<T, PhantomBin<T>> {
override val dimension: Int
get() = data.dimension
override fun iterator(): Iterator<PhantomBin<T>> {
return bins.asSequence().map { entry -> PhantomBin(entry.key, data[entry.value]) }.iterator()
}
override fun get(point: Point<out T>): PhantomBin<T>? {
val template = bins.keys.find { it.contains(point) }
return template?.let { PhantomBin(it, data[bins[it]!!]) }
}
} | 0 | Kotlin | 0 | 0 | 9808b2800cb2c44e50e039373e028767385bd87e | 2,129 | kmath | Apache License 2.0 |
src/main/kotlin/Day9.kt | maldoinc | 726,264,110 | false | {"Kotlin": 14472} | import kotlin.io.path.Path
import kotlin.io.path.readLines
fun findScorePart1(records: List<List<Int>>): Int =
records.foldRight(0) { ints, acc -> acc + ints.last() }
fun findScorePart2(records: List<List<Int>>): Int =
records.foldRight(0) { ints, acc -> ints.first() - acc }
fun main(args: Array<String>) {
val records =
Path(args.first())
.readLines()
.map { it.split(" ").map(String::toInt) }
.map { it ->
val rows: List<List<Int>> = mutableListOf(it)
while (!rows.last().all { it == 0 }) {
val last = rows.last()
val row = (1 ..< last.size).map { last[it] - last[it - 1] }
if (row.isEmpty()) {
break
}
rows.addLast(row)
}
rows
}
println(records.sumOf { findScorePart1(it) })
println(records.sumOf { findScorePart2(it) })
}
| 0 | Kotlin | 0 | 1 | 47a1ab8185eb6cf16bc012f20af28a4a3fef2f47 | 999 | advent-2023 | MIT License |
nebulosa-watney/src/main/kotlin/nebulosa/watney/plate/solving/math/Equations.kt | tiagohm | 568,578,345 | false | {"Kotlin": 2031289, "TypeScript": 322187, "HTML": 164617, "SCSS": 10191, "Python": 2817, "JavaScript": 1119} | package nebulosa.watney.plate.solving.math
/**
* Solving least squares, for solving the plate constants.
*/
@Suppress("LocalVariableName")
fun solveLeastSquares(equationsOfCondition: List<DoubleArray>): DoubleArray {
// See: https://phys.libretexts.org/Bookshelves/Astronomy__Cosmology/Book%3A_Celestial_Mechanics_(Tatum)/01%3A_Numerical_Methods/1.08%3A_Simultaneous_Linear_Equations_N__n
val A11 = equationsOfCondition.sumOf { it[0] * it[0] }
val A12 = equationsOfCondition.sumOf { it[0] * it[1] }
val A13 = equationsOfCondition.sumOf { it[0] * it[2] }
val B1 = equationsOfCondition.sumOf { it[0] * it[3] }
val A22 = equationsOfCondition.sumOf { it[1] * it[1] }
val A23 = equationsOfCondition.sumOf { it[1] * it[2] }
val B2 = equationsOfCondition.sumOf { it[1] * it[3] }
val A33 = equationsOfCondition.sumOf { it[2] * it[2] }
val B3 = equationsOfCondition.sumOf { it[2] * it[3] }
// See: https://www.cliffsnotes.com/study-guides/algebra/algebra-ii/linear-equations-in-three-variables/linear-equations-solutions-using-determinants-with-three-variables
val denominator = A11 * (A22 * A33 - A23 * A23) - A12 * (A12 * A33 - A13 * A23) + A13 * (A12 * A23 - A13 * A22)
val dx = (-B1) * (A22 * A33 - A23 * A23) - (-B2) * (A12 * A33 - A13 * A23) + (-B3) * (A12 * A23 - A13 * A22)
val dy = A11 * ((-B2) * A33 - A23 * (-B3)) - A12 * ((-B1) * A33 - A13 * (-B3)) + A13 * ((-B1) * A23 - A13 * (-B2))
val dz = A11 * (A22 * (-B3) - (-B2) * A23) - A12 * (A12 * (-B3) - (-B1) * A23) + A13 * (A12 * (-B2) - (-B1) * A22)
val x1 = dx / denominator
val x2 = dy / denominator
val x3 = dz / denominator
return doubleArrayOf(x1, x2, x3)
}
fun lerp(v0: Double, v1: Double, t: Double) = (1 - t) * v0 + t * v1
| 0 | Kotlin | 0 | 1 | de96a26e1a79c5b6f604d9af85311223cc28f264 | 1,767 | nebulosa | MIT License |
src/main/kotlin/com/groundsfam/advent/y2020/d04/Day04.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2020.d04
import com.groundsfam.advent.DATAPATH
import kotlin.io.path.div
import kotlin.io.path.useLines
private fun parsePassports(input: Sequence<String>): List<Map<String, String>> {
val ret: MutableList<Map<String, String>> = mutableListOf()
var curr: MutableMap<String, String> = mutableMapOf()
input.forEach { line ->
if (line.isBlank()) {
ret.add(curr)
curr = mutableMapOf()
} else {
line.split(" ")
.forEach { part ->
curr[part.substringBefore(':')] = part.substringAfter(':')
}
}
}
if (curr.isNotEmpty()) ret.add(curr)
return ret
}
private fun validate(passport: Map<String, String>): Boolean {
if (!passport.keys.containsAll(requiredFields)) return false
try {
passport["byr"]?.let { byr ->
if (byr.toInt() !in 1920..2002) return false
}
passport["iyr"]?.let { iyr ->
if (iyr.toInt() !in 2010..2020) return false
}
passport["eyr"]?.let { eyr ->
if (eyr.toInt() !in 2020..2030) return false
}
passport["hgt"]?.let { hgt ->
val unitIdx = hgt.length - 2
val num = hgt.substring(0 until unitIdx).toInt()
when (hgt.substring(unitIdx)) {
"cm" -> if (num !in 150..193) return false
"in" -> if (num !in 59..76) return false
else -> return false
}
}
passport["hcl"]?.let { hcl ->
if (hcl.length != 7) return false
hcl.forEachIndexed { i, c ->
when (i) {
0 -> if (c != '#') return false
else -> if (c !in '0'..'9' && c !in 'a'..'f') return false
}
}
}
passport["ecl"]?.let { ecl ->
if (ecl !in validEyeColors) return false
}
passport["pid"]?.let { pid ->
if (pid.length != 9 || pid.any { c -> c !in '0'..'9' }) return false
}
} catch (e: Exception) {
return false
}
return true
}
private val requiredFields = setOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
private val validEyeColors = setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
fun main() {
val passports = (DATAPATH / "2020/day04.txt").useLines { parsePassports(it) }
passports
.count { it.keys.containsAll(requiredFields) }
.also { println("Part one: $it") }
passports
.count(::validate)
.also { println("Part two: $it") }
} | 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,624 | advent-of-code | MIT License |
src/Day01.kt | burtz | 573,411,717 | false | {"Kotlin": 10999} | fun main() {
fun part1(input: List<String>): Int {
var current = 0
var max = 0
input.forEach{
if(it.isNotEmpty()) current += it.toInt()
else
{
if(current > max) max = current
current = 0
}
}
return max
}
fun part2(input: List<String>): Int {
var current = 0
var elfList : MutableList<Int> = mutableListOf()
input.forEach{
if(it.isNotEmpty())
{
current += it.toInt()
}
else
{
elfList.add(current)
current = 0
}
}
elfList.sortDescending()
return elfList[0] + elfList[1] + elfList[2]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
//check(part2(testInput) == 45000)
//println(part1(testInput))
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | daac7f91e1069d1490e905ffe7b7f11b5935af06 | 1,110 | adventOfCode2022 | Apache License 2.0 |
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day08/Day08.kt | jackploeg | 736,755,380 | false | {"Kotlin": 318734} | package nl.jackploeg.aoc._2023.calendar.day08
import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory
import nl.jackploeg.aoc.utilities.leastCommonMultiple
import nl.jackploeg.aoc.utilities.readStringFile
import java.math.BigInteger
import javax.inject.Inject
class Day08 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
var directions = CharArray(0)
var nodes: Map<String, Node> = mapOf()
fun partOne(fileName: String): Int {
val lines = readStringFile(fileName)
directions = lines[0].toCharArray()
nodes = lines.subList(2, lines.size).map { parseNode(it) }.associateBy { it.name }
var node = nodes["AAA"]
var step = 0
while (node != null && node.name != "ZZZ") {
val instruction = directions[step++ % directions.size]
node = if (instruction == 'L')
nodes[node.left]
else
nodes[node.right]
}
return step
}
fun partTwo(fileName: String): BigInteger {
val lines = readStringFile(fileName)
directions = lines[0].toCharArray()
nodes = lines.subList(2, lines.size).map { parseNode(it) }.associateBy { it.name }
val currentNodes = nodes.filter { it.key.endsWith('A') }.values
val steps: MutableList<BigInteger> = mutableListOf()
currentNodes.forEach { steps.add(getStepsToZ(it)) }
return steps.reduce { acc, it -> leastCommonMultiple(acc, it) }
}
fun getStepsToZ(node: Node): BigInteger {
var step = BigInteger.ZERO
var dirPointer = 0
var currentNode = node
while (!currentNode.name.endsWith('Z')) {
val instruction = directions[dirPointer]
dirPointer++
if (dirPointer >= directions.size)
dirPointer = 0
step++
currentNode = if (instruction == 'L')
nodes[currentNode.left]!!
else
nodes[currentNode.right]!!
}
return step
}
fun parseNode(it: String): Node {
val subs = it.split(" ")
val name = subs[0]
val l = subs[2].substring(1, subs[2].length - 1)
val r = subs[3].substring(0, subs[3].length - 1)
return Node(name, l, r)
}
data class Node(val name: String, val left: String, val right: String)
}
| 0 | Kotlin | 0 | 0 | f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76 | 2,169 | advent-of-code | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem46/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem46
/**
* LeetCode page: [46. Permutations](https://leetcode.com/problems/permutations/);
*/
class Solution {
/* Complexity:
* Time O(N * N!) and Space O(N * N!) where N is the size of nums;
*/
fun permute(nums: IntArray): List<List<Int>> {
val permutes = mutableListOf(mutableListOf(nums[0]))
for (index in 1..nums.lastIndex) {
addNumberToEachPermute(nums[index], permutes)
addRotationsOfEachPermute(permutes)
}
return permutes
}
private fun addNumberToEachPermute(number: Int, permutes: MutableList<MutableList<Int>>) {
for (permute in permutes) {
permute.add(number)
}
}
private fun addRotationsOfEachPermute(permutes: MutableList<MutableList<Int>>) {
repeat(permutes.size) { index ->
addRotationsOfPermute(permutes[index], permutes)
}
}
private fun addRotationsOfPermute(permute: List<Int>, container: MutableList<MutableList<Int>>) {
val greatestShift = permute.size - 1
for (shift in 1..greatestShift) {
container.add(mutableListOf())
for (index in shift..permute.lastIndex) {
container.last().add(permute[index])
}
for (index in 0 until shift) {
container.last().add(permute[index])
}
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,418 | hj-leetcode-kotlin | Apache License 2.0 |
aoc2022/aoc2022-kotlin/src/main/kotlin/de/havox_design/aoc2022/day03/ItemValue.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2022.day03
import java.util.*
enum class ItemValue(val lowerCaseValue: Int, val upperCaseValue: Int, val symbol: String) {
A(1, 27, "A"),
B(2, 28, "B"),
C(3, 29, "C"),
D(4, 30, "D"),
E(5, 31, "E"),
F(6, 32, "F"),
G(7, 33, "G"),
H(8, 34, "H"),
I(9, 35, "I"),
J(10, 36, "J"),
K(11, 37, "K"),
L(12, 38, "L"),
M(13, 39, "M"),
N(14, 40, "N"),
O(15, 41, "O"),
P(16, 42, "P"),
Q(17, 43, "Q"),
R(18, 44, "R"),
S(19, 45, "S"),
T(20, 46, "T"),
U(21, 47, "U"),
V(22, 48, "V"),
W(23, 49, "W"),
X(24, 50, "X"),
Y(25, 51, "Y"),
Z(26, 52, "Z"),
UNDEFINED(0, 0, "UNDEFINED");
companion object {
fun getValueBySymbol(s: String): ItemValue {
for (index in ItemValue.values().indices) {
val currentFigure: ItemValue = ItemValue.values()[index]
if (currentFigure.symbol == s.uppercase(Locale.getDefault())) {
return currentFigure
}
}
return UNDEFINED
}
fun getScoreByDefault(s: String): Int {
val v: ItemValue = getValueBySymbol(s)
return if (s.isLowerCase()) {
v.lowerCaseValue
} else {
v.upperCaseValue
}
}
}
}
private fun String.isUpperCase(): Boolean =
this.uppercase(Locale.getDefault()) == this
private fun String.isLowerCase(): Boolean =
!this.isUpperCase()
| 4 | Kotlin | 0 | 1 | b94716fbc95f18e68774eb99069c0b703875615c | 1,521 | aoc2022 | Apache License 2.0 |
Day11/Day11part2.kt | knivey | 317,575,424 | false | {"Java": 19457, "C++": 6082, "Kotlin": 5478, "C": 4107, "PHP": 2198} |
import java.io.File
enum class Tile(val c: String) {
FLOOR("."),
FILLED("#"),
EMPTY("L"),
UNKNOWN("?");
fun from(c: Char) : Tile {
when (c) {
'.' -> return FLOOR
'#' -> return FILLED
'L' -> return EMPTY
}
return UNKNOWN;
}
override fun toString(): String {
return c
}
}
fun main() {
val map: ArrayList<ArrayList<Tile>> = File("input.txt").readLines().asSequence()
.map { line -> line.asSequence() }
.map { it.map {t -> Tile.UNKNOWN.from(t)} }
.map { it.toCollection(ArrayList()) }
.toCollection(ArrayList())
val maxY = map.size -1
val maxX = map[0].size -1
var changes = 1
var iterations = 0
while (changes != 0) {
changes = 0
val mapc = copyMap(map)
for ((y, row) in mapc.withIndex()) {
for ((x, tile) in row.withIndex()) {
if(tile == Tile.FLOOR) {
//print(".")
continue
}
var occupied : Int = 0
for(vec in genVecs(x, y, maxX, maxY)) {
for (v in vec) {
if (mapc[v.y][v.x] == Tile.FILLED) {
occupied++
break
}
if (mapc[v.y][v.x] == Tile.EMPTY) {
break
}
}
}
if(occupied >= 5)
if(tile != Tile.EMPTY) {
map[y][x] = Tile.EMPTY
changes++
}
if(occupied == 0)
if(tile != Tile.FILLED) {
map[y][x] = Tile.FILLED
changes++
}
//print(occupied)
}
//print("\n")
}
if(changes != 0)
iterations++
if(iterations > 100000) {
println("giving up");
break;
}
//println("Changed: $changes ------")
//map.forEach{ println(it.joinToString("")) }
//println("------------------------")
}
val filled = map
.flatten()
.filter {it == Tile.FILLED}
.count()
println("$filled seats filled")
}
fun copyMap(map: ArrayList<ArrayList<Tile>>): ArrayList<ArrayList<Tile>>{
val mapc: ArrayList<ArrayList<Tile>> = arrayListOf()
for(m: ArrayList<Tile> in map) {
mapc.add(m.clone() as java.util.ArrayList<Tile>)
}
return mapc;
}
data class Coord(val x: Int, val y: Int) {
}
//Boy this seems silly
//Will update later to make something that take (stepx, stepy)
fun genVecs(x:Int, y:Int, maxX: Int, maxY:Int) : List<List<Coord>> {
val out: MutableList<MutableList<Coord>> = mutableListOf()
/**
* 123
* 0o4
* 765
*/
for (v in 0..7) {
var list: MutableList<Coord> = mutableListOf()
when (v) {
0 -> list = (x-1 downTo 0).map { Coord(it, y) }.toMutableList()
1 -> {
for (i in x-1 downTo 0) {
val j = y - (x - i)
if (j >= 0)
list.add(Coord(i, j))
}
}
2 -> list = (y-1 downTo 0).map { Coord(x, it) }.toMutableList()
3 -> {
for (i in x+1..maxX) {
val j = y - (i - x)
if (j in 0..maxY)
list.add(Coord(i, j))
}
}
4 -> list = (x+1..maxX).map { Coord(it, y) }.toMutableList()
5 -> {
for (i in x+1..maxX) {
val j = y + (i - x)
if (j in 0..maxY)
list.add(Coord(i, j))
}
}
6 -> list = (y+1..maxY).map { Coord(x, it) }.toMutableList()
7 -> {
for (i in x-1 downTo 0) {
val j = y - (i - x)
if (j in 0..maxY)
list.add(Coord(i, j))
}
}
}
out.add(list)
}
return out
} | 0 | Java | 0 | 1 | 14a8a23c89b51dfb1dc9f160a046319cf3ca785c | 4,277 | adventofcode | MIT License |
src/Day01.kt | Moonpepperoni | 572,940,230 | false | {"Kotlin": 6305} | fun main() {
fun String.toCarriedCalories() = this.lines().sumOf { it.toInt() }
fun part1(input: List<String>): Int {
return input.maxOf(String::toCarriedCalories)
}
fun part2(input: List<String>): Int {
return input
.map(String::toCarriedCalories)
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputBlankLines("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInputBlankLines("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 946073042a985a5ad09e16609ec797c075154a21 | 678 | moonpepperoni-aoc-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/adventofcode/codeforces/KotlinHeroesPractice3.kt | 3ygun | 115,948,057 | false | null | package adventofcode.codeforces
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
object KotlinHeroesPractice3 {
// <editor-fold desc="Problem A - Restoring Three Numbers">
/*
fun main() {
val inputs = readLine()!!
.split(regex = " ".toRegex())
.map { it.toLong() }
.toSet()
val (a, b, c) = problemA(inputs)
println("$a $b $c")
}
*/
/** https://codeforces.com/contest/1298/problem/A */
fun problemA(
x1: Long,
x2: Long,
x3: Long,
x4: Long
): List<Long> {
val inputs = setOf(x1, x2, x3, x4)
return problemA(inputs)
.also { println(it) }
.toList()
}
/**
* Inputs will always have size >= 2 with the max and second highest number being there.
* Why? Because max will always be at least +1 greater then the second highest because it will
* be generate from a + b + c which all need to be positive (> 0)
*/
private fun problemA(inputs: Set<Long>): Triple<Long, Long, Long> {
val max = inputs.max()!!
val inputsWithoutMax = inputs.filterNot { it == max }.toSet()
val secondHighest = inputsWithoutMax.max()!!
val min = inputsWithoutMax.min()!!
// a >= b >= c
val c = max - secondHighest
val b = min - c
val a = max - c - b
return Triple(a, b, c)
}
// </editor-fold>
// <editor-fold desc="Problem B - Remove Duplicates">
/*
fun main() {
val numInputs = readLine()!!
val inputs = readLine()!!
val (numResults, result) = problemB(numInputs, inputs)
println(numResults)
println(result)
}
*/
/** https://codeforces.com/contest/1298/problem/B */
fun problemB(
numInputs: String,
input: String
): Pair<String, String> {
val expectedNum = numInputs.toInt()
val parsed = input
.split(regex = " ".toRegex())
.map(String::toInt)
require(parsed.size == expectedNum) { "Didn't parse input correctly: '$input' got: $parsed" }
var x = 0
val result = parsed
.associateBy({ it }) { val r = x; x ++; r }
.toList()
.sortedBy { it.second }
.map { it.first }
val num = result.size
val printed = result.joinToString(separator = " ")
return num.toString() to printed
}
// </editor-fold>
// <editor-fold desc="Problem C - File Name">
/*
fun main() {
val numInputs = readLine()!!
val inputs = readLine()!!
val result = problemC(inputs)
println(result)
}
*/
/** https://codeforces.com/contest/1298/problem/C */
fun problemC(input: String): Int {
var removed = 0
val array = input.toCharArray()
for (i in 0 until (array.size - 2)) {
if ('x' == array[i] &&
'x' == array[i+1] &&
'x' == array[i+2]) {
removed ++
}
}
return removed
}
// </editor-fold>
// <editor-fold desc="Problem D - Bus Video System">
/*
fun main() {
val bus = readLine()!!
val inputs = readLine()!!
val result = problemD(bus, inputs)
println(result)
}
*/
/** https://codeforces.com/contest/1298/problem/D */
fun problemD(
bus: String,
inputChanges: String
): Long {
// TODO : Supposedly this doesn't work
val (stops, maxPeople) = bus
.split(regex = " ".toRegex())
.map(String::toLong)
.let { it[0] to it[1] }
val changes = inputChanges
.split(regex = " ".toRegex())
.map(String::toLong)
val seenPeople = mutableListOf<Long>(0)
for (change in changes) {
val last = seenPeople.lastOrNull() ?: 0L
seenPeople.add(last + change)
}
val maximum = kotlin.math.max(seenPeople.max()!!, 0L)
val minimum = kotlin.math.min(seenPeople.min()!!, 0L)
.let { if (it < 0L) kotlin.math.abs(it) else 0L }
return when {
stops.toInt() != changes.size -> 0L
maxPeople < minimum -> 0L
maxPeople < maximum -> 0L
else -> maxPeople - maximum - minimum + 1L
}
}
// </editor-fold>
}
| 0 | Kotlin | 0 | 0 | 69f95bca3d22032fba6ee7d9d6ec307d4d2163cf | 4,438 | adventofcode | MIT License |
src/Day01.kt | Jaavv | 571,865,629 | false | {"Kotlin": 14896} | // https://adventofcode.com/2022/day/1
fun main() {
fun part1(input: List<String>): Int {
val calories = mutableListOf<Int>()
var acc = 0
input.forEach {
if (it.isBlank()) {
calories.add(acc)
acc = 0
} else {
acc += it.toInt()
}
}
// for (i in input) {
// if (i == "") {
// calories.add(acc)
// acc = 0
// } else {
// acc += i.toInt()
// }
// }
return calories.max()
}
fun part2(input: List<String>): Int {
val calories = mutableListOf<Int>()
var acc = 0
for (i in input) {
if (i == "") {
calories.add(acc)
acc = 0
} else {
acc += i.toInt()
}
}
var sumOfThree = 0
repeat(3) {
sumOfThree += calories.max()
calories.remove(calories.max())
}
return sumOfThree
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input)) //71023
println(part2(input)) //206289
} | 0 | Kotlin | 0 | 0 | 5ef23a16d13218cb1169e969f1633f548fdf5b3b | 1,322 | advent-of-code-2022 | Apache License 2.0 |
year2020/day23/part2/src/main/kotlin/com/curtislb/adventofcode/year2020/day23/part2/Year2020Day23Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
Due to what you can only assume is a mistranslation (you're not exactly fluent in Crab), you are
quite surprised when the crab starts arranging many cups in a circle on your raft - one million
(1000000) in total.
Your labeling is still correct for the first few cups; after that, the remaining cups are just
numbered in an increasing fashion starting from the number after the highest number in your list and
proceeding one by one until one million is reached. (For example, if your labeling were 54321, the
cups would be numbered 5, 4, 3, 2, 1, and then start counting up from 6 until one million is
reached.) In this way, every number from one through one million is used exactly once.
After discovering where you made the mistake in translating Crab Numbers, you realize the small crab
isn't going to do merely 100 moves; the crab is going to do ten million (10000000) moves!
The crab is going to hide your stars - one each - under the two cups that will end up immediately
clockwise of cup 1. You can have them if you predict what the labels on those cups will be when the
crab is finished.
In the above example (389125467), this would be 934001 and then 159792; multiplying these together
produces 149245887792.
Determine which two cups will end up immediately clockwise of cup 1. What do you get if you multiply
their labels together?
*/
package com.curtislb.adventofcode.year2020.day23.part2
import com.curtislb.adventofcode.common.number.product
import com.curtislb.adventofcode.year2020.day23.cups.CupCircle
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2020, day 23, part 2.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long {
val file = inputPath.toFile()
val cupCircle = CupCircle(file.readText(), fillUpTo = 1_000_000)
repeat(10_000_000) { cupCircle.performMove() }
return cupCircle.findLabelsAfter(1, count = 2).map { it.toLong() }.product()
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,087 | AdventOfCode | MIT License |
Combination_Sum_II.kt | xiekch | 166,329,519 | false | {"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349} | class Solution {
fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> {
candidates.sort()
val res = ArrayList<MutableList<Int>>()
combinationSum(candidates, target, res, 0, mutableListOf())
return res
}
private fun combinationSum(candidates: IntArray, target: Int, res: ArrayList<MutableList<Int>>, cur: Int, path: MutableList<Int>) {
// println("$path,$target")
if (target < 0) return
if (0 == target) {
res.add(path.toMutableList())
return
}
for (i in cur..candidates.lastIndex) {
if (i > cur && candidates[i] == candidates[i - 1]) continue
path.add(candidates[i])
combinationSum(candidates, target - candidates[i], res, i + 1, path)
path.removeAt(path.lastIndex)
}
}
}
fun main() {
val solution = Solution()
val testset = arrayOf(
intArrayOf(10, 1, 2, 7, 6, 1, 5),
intArrayOf(2, 5, 2, 1, 2)
)
val targets = intArrayOf(8, 5)
for (i in testset.indices) {
println(solution.combinationSum2(testset[i], targets[i]))
}
} | 0 | C++ | 0 | 0 | eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134 | 1,163 | leetcode | MIT License |
src/main/kotlin/days/Day17.kt | butnotstupid | 433,717,137 | false | {"Kotlin": 55124} | package days
class Day17 : Day(17) {
override fun partOne(): Any {
val (minX, maxX, minY, maxY) =
inputList.first().let {
Regex("""target area: x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)""")
.find(it)!!.groupValues.drop(1).map { it.toInt() }
}
return reachedYs(minX, maxX, minY, maxY).maxOrNull()!!
}
override fun partTwo(): Any {
val (minX, maxX, minY, maxY) =
inputList.first().let {
Regex("""target area: x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)""")
.find(it)!!.groupValues.drop(1).map { it.toInt() }
}
return reachedYs(minX, maxX, minY, maxY).size
}
private fun reachedYs(minX: Int, maxX: Int, minY: Int, maxY: Int) =
(0..2 * maxX).flatMap { x ->
(minY..maxX).mapNotNull { y ->
var (cx, cy) = x to y
var (posx, posy) = 0 to 0
var topY = Int.MIN_VALUE
var reached = false
while (posy >= minY) {
posx += cx
posy += cy
cx += stepToZero(cx)
cy -= 1
if (posy > topY) topY = posy
if (posx in minX..maxX && posy in minY..maxY) {
reached = true
break
}
}
if (reached) topY else null
}
}
private fun stepToZero(x: Int) = when {
x < 0 -> 1
x == 0 -> 0
x > 0 -> -1
else -> throw IllegalArgumentException("Unexpected x=$x")
}
}
| 0 | Kotlin | 0 | 0 | a06eaaff7e7c33df58157d8f29236675f9aa7b64 | 1,676 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/Day02.kt | Hotkeyyy | 573,026,685 | false | {"Kotlin": 7830} | import java.io.File
val meL = "XYZ".toList()
val opponentL = "ABC".toList()
fun main() {
fun part1(input: String) {
val rounds = input.split("\r")
var result = 0
rounds.forEach {
val me = it.split(" ").last()
val opponent = it.split(" ").first()
val p = getPoints(
Pair(
meL.indexOf(me.trim().toCharArray().first()),
opponentL.indexOf(opponent.trim().toCharArray().first())
)
)
result += p
}
println(result)
}
fun part2(input: String) {
val rounds = input.split("\r")
var result = 0
rounds.forEach {
val type = it.split(" ").last()
val opponent = it.split(" ").first()
var character = ""
when (type) {
"X" -> character = opponent.trim().characterToLose
"Y" -> character = opponent.trim().characterToDraw
"Z" -> character = opponent.trim().characterToWin
}
val p = getPoints(
Pair(
meL.indexOf(character.trim().toCharArray().first()),
opponentL.indexOf(opponent.trim().toCharArray().first())
)
)
result += p
}
println(result)
}
val input = File("src/Day02.txt").readText()
part2(input)
}
val String.characterToWin: String
get() {
if (this == "A") return "Y"
if (this == "B") return "Z"
if (this == "C") return "X"
return TODO("Provide the return value")
}
val String.characterToDraw: String
get() {
return meL[opponentL.indexOf(this.trim().toCharArray().first())].toString()
}
val String.characterToLose: String
get() {
if (this == "A") return "Z"
if (this == "B") return "X"
if (this == "C") return "Y"
return TODO("Provide the return value")
}
fun getPoints(pair: Pair<Int, Int>): Int {
val me = pair.first
val opponent = pair.second
var points = 0
if (me == opponent) points += 3
if (me == 0 && (opponent == 2)) points += 6
if (me == 1 && (opponent == 0)) points += 6
if (me == 2 && (opponent == 1)) points += 6
if (me == 0) points += 1
if (me == 1) points += 2
if (me == 2) points += 3
return points
} | 0 | Kotlin | 0 | 0 | dfb20f1254127f99bc845e9e13631c53de8784f2 | 2,409 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day9/day9.kt | lavong | 317,978,236 | false | null | /*
--- Day 9: Encoding Error ---
With your neighbor happily enjoying their video game, you turn your attention to an open data port on the little screen in the seat in front of you.
Though the port is non-standard, you manage to connect it to your computer through the clever use of several paperclips. Upon connection, the port outputs a series of numbers (your puzzle input).
The data appears to be encrypted with the eXchange-Masking Addition System (XMAS) which, conveniently for you, is an old cypher with an important weakness.
XMAS starts by transmitting a preamble of 25 numbers. After that, each number you receive should be the sum of any two of the 25 immediately previous numbers. The two numbers will have different values, and there might be more than one such pair.
For example, suppose your preamble consists of the numbers 1 through 25 in a random order. To be valid, the next number must be the sum of two of those numbers:
26 would be a valid next number, as it could be 1 plus 25 (or many other pairs, like 2 and 24).
49 would be a valid next number, as it is the sum of 24 and 25.
100 would not be valid; no two of the previous 25 numbers sum to 100.
50 would also not be valid; although 25 appears in the previous 25 numbers, the two numbers in the pair must be different.
Suppose the 26th number is 45, and the first number (no longer an option, as it is more than 25 numbers ago) was 20. Now, for the next number to be valid, there needs to be some pair of numbers among 1-19, 21-25, or 45 that add up to it:
26 would still be a valid next number, as 1 and 25 are still within the previous 25 numbers.
65 would not be valid, as no two of the available numbers sum to it.
64 and 66 would both be valid, as they are the result of 19+45 and 21+45 respectively.
Here is a larger example which only considers the previous 5 numbers (and has a preamble of length 5):
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
In this example, after the 5-number preamble, almost every number is the sum of two of the previous 5 numbers; the only number that does not follow this rule is 127.
The first step of attacking the weakness in the XMAS data is to find the first number in the list (after the preamble) which is not the sum of two of the 25 numbers before it. What is the first number that does not have this property?
--- Part Two ---
The final step in breaking the XMAS encryption relies on the invalid number you just found: you must find a contiguous set of at least two numbers in your list which sum to the invalid number from step 1.
Again consider the above example:
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
In this list, adding up all of the numbers from 15 through 40 produces the invalid number from step 1, 127. (Of course, the contiguous set of numbers in your actual list might be much longer.)
To find the encryption weakness, add together the smallest and largest number in this contiguous range; in this example, these are 15 and 47, producing 62.
What is the encryption weakness in your XMAS-encrypted list of numbers?
*/
package day9
fun main() {
val input = AdventOfCode.file("day9/input")
.lines().filterNot { it.isBlank() }.mapNotNull { it.toIntOrNull() }
val invalidNumber = solvePartOne(input)
.also { println("solution part 1: $it") }
solvePartTwo(input, invalidNumber)
?.also { println("solution part 2: $it") }
}
fun solvePartOne(input: List<Int>): Int {
return input.windowed(26)
.first { !it.lastIsSumOfAnyOther() }
.last()
}
fun solvePartTwo(input: List<Int>, invalidNumber: Int): Int? {
(2..(input.size / 2)).forEach { windowSize ->
input.windowWhichSumEquals(windowSize, invalidNumber)
?.let { return it.first() + it.last() }
}
return null
}
fun List<Int>.lastIsSumOfAnyOther(): Boolean {
return if (size > 1) {
val last = last()
dropLast(1).any { last - it in this }
} else {
false
}
}
fun List<Int>.windowWhichSumEquals(windowSize: Int, targetSum: Int): List<Int>? {
return windowed(windowSize)
.firstOrNull { it.sum() == targetSum }
?.sorted()
}
| 0 | Kotlin | 0 | 1 | a4ccec64a614d73edb4b9c4d4a72c55f04a4b77f | 4,247 | adventofcode-2020 | MIT License |
LeetCode/0198. House Robber/Solution.kt | InnoFang | 86,413,001 | false | {"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410} | /**
* Created by <NAME> on 2017/12/7.
*/
// 198
class Solution {
var memo: MutableList<Int> = MutableList(0) { -1 }
fun rob(nums: IntArray): Int {
memo.addAll(MutableList(nums.size) { -1 })
return tryRob(nums, 0)
}
private fun tryRob(nums: IntArray, index: Int): Int {
if (index >= nums.size)
return 0
if (memo[index] != -1)
return memo[index]
var res = 0
(index until nums.size).forEach {
res = maxOf(res, nums[it] + tryRob(nums, it + 2))
}
memo[index] = res
return res
}
}
class Solution2 {
fun rob(nums: IntArray): Int {
val n = nums.size
if (n == 0) return 0
val dp = Array(n) { -1 }
dp[n - 1] = nums[n - 1]
(n - 2 downTo 0).forEach { i ->
(i until n).forEach { j ->
dp[i] = maxOf(dp[i], nums[j] + (if (j + 2 < n) dp[j + 2] else 0))
}
}
return dp[0]
}
}
public class Solution3 {
fun rob(nums: IntArray): Int {
if (nums.isEmpty()) return 0
val n = nums.size
val dp = Array(nums.size) { -1 }
dp[0] = nums[0]
(1 until n).forEach { i ->
dp[i] = maxOf(dp[i - 1], nums[i] + if (i > 1) dp[i - 2] else 0)
}
// dp.forEach(::println)
return dp[n - 1]
}
}
fun main(args: Array<String>) {
val solution = Solution3()
solution.rob(intArrayOf(3, 4, 2, 1)).let(::println)
solution.rob(intArrayOf(8, 4, 5, 3, 1)).let(::println)
}
// 213. House Robber II
// 337. House Robber III
// 309. Best Time to Buy and Sell Stock with Cooldown | 0 | C++ | 8 | 20 | 2419a7d720bea1fd6ff3b75c38342a0ace18b205 | 1,661 | algo-set | Apache License 2.0 |
src/main/kotlin/days/aoc2023/Day18.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2023
import days.Day
import util.Point2d
import util.Point2dl
import util.isOdd
import util.toward
import kotlin.math.max
import kotlin.math.min
class Day18 : Day(2023, 18) {
override fun partOne(): Any {
return calculatePartOneShoelace(inputList)
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
fun calculatePartOne(input: List<String>): Int {
var cursor = Point2d(0,0)
val instructions = input.mapNotNull {
Regex("(\\w) (\\d+) \\(#(\\w+)\\)").matchEntire(it)?.destructured?.let { (direction, length, color) ->
DigInstruction(direction, length.toInt(), color)
}
}
instructions.fold(cursor) { cursor, instruction ->
instruction.calculateRangesFrom(cursor)
}
var lowerRight = Point2d(Int.MIN_VALUE, Int.MIN_VALUE)
var upperLeft = Point2d(Int.MAX_VALUE, Int.MAX_VALUE)
instructions.forEach { instruction ->
upperLeft = Point2d(
min(upperLeft.x, min(instruction.xRange.first, instruction.xRange.last)),
min(upperLeft.y, min(instruction.yRange.first, instruction.yRange.last)))
lowerRight = Point2d(
max(lowerRight.x, max(instruction.xRange.first, instruction.xRange.last)),
max(lowerRight.y, max(instruction.yRange.first, instruction.yRange.last)))
}
fun pointIsOnBoundary(point: Point2d): Boolean {
for (instruction in instructions) {
if (point.y in instruction.yRange && point.x in instruction.xRange) {
return true
}
}
return false
}
fun pointIsInside(point: Point2d): Boolean {
var crossed = 0
var horizontalsTraversed = mutableSetOf<DigInstruction>()
for (x in point.x toward upperLeft.x) {
for (instruction in instructions) {
if (point.y in instruction.yRange && x in instruction.xRange) {
if (instruction.isVertical()) {
crossed++
} else if (instruction.isHorizontal() && !horizontalsTraversed.contains(instruction)) {
horizontalsTraversed.add(instruction)
}
}
}
}
return (crossed + horizontalsTraversed.size).isOdd()
}
var startingPoint = Point2d(0, 0)
outer@for (x in upperLeft.x toward lowerRight.x) {
for (y in upperLeft.y toward lowerRight.y) {
startingPoint = Point2d(x, y)
if (!pointIsOnBoundary(startingPoint) && pointIsInside(startingPoint)) {
break@outer
}
}
}
val frontier = mutableListOf(startingPoint)
val seen = mutableListOf<Point2d>()
val inside = mutableSetOf(startingPoint)
while (frontier.isNotEmpty()) {
val current = frontier.removeFirst()
seen.add(current)
current.allNeighbors().filter { !seen.contains(it) && !frontier.contains(it) }.forEach {
if (!pointIsOnBoundary(it)) {
frontier.add(it)
}
inside.add(it)
}
}
return inside.count()
}
data class DigInstruction(val direction: String, val length: Int, val color: String) {
lateinit var xRange: IntProgression;
lateinit var yRange: IntProgression;
fun calculateRangesFrom(origin: Point2d): Point2d {
when (direction) {
"U" -> {
xRange = origin.x .. origin.x
yRange = origin.y toward origin.y - length
}
"D" -> {
xRange = origin.x .. origin.x
yRange = origin.y toward origin.y + length
}
"R" -> {
xRange = origin.x toward origin.x + length
yRange = origin.y .. origin.y
}
"L" -> {
xRange = origin.x toward origin.x - length
yRange = origin.y .. origin.y
}
}
return Point2d(xRange.last, yRange.last)
}
fun isHorizontal(): Boolean = xRange.first != xRange.last
fun isVertical(): Boolean = yRange.first != yRange.last
lateinit var start: Point2dl
lateinit var end: Point2dl
fun calculateExtrema(origin: Point2dl): Point2dl {
start = origin
when (direction) {
"U" -> {
end = start.copy(y = start.y - length)
}
"D" -> {
end = start.copy(y = start.y + length)
}
"R" -> {
end = start.copy(x = start.x + length)
}
"L" -> {
end = start.copy(x = start.x - length)
}
}
return end
}
}
data class RealDigInstruction(val encoded: String) {
val length = encoded.take(5).toInt(16)
val direction = when (encoded.last()) {
'0' -> 'R'
'1' -> 'D'
'2' -> 'L'
'3' -> 'U'
else -> throw IllegalStateException("Oops")
}.toString()
lateinit var start: Point2dl
fun calculateExtrema(origin: Point2dl): Point2dl {
start = origin
return when (direction) {
"U" -> {
start.copy(y = start.y - length)
}
"D" -> {
start.copy(y = start.y + length)
}
"R" -> {
start.copy(x = start.x + length)
}
"L" -> {
start.copy(x = start.x - length)
}
else -> throw IllegalStateException("oh dear")
}
}
}
fun calculatePartOneShoelace(input: List<String>): Long {
var cursor = Point2dl(0,0)
val instructions = input.mapNotNull {
Regex("(\\w) (\\d+) \\(#(\\w+)\\)").matchEntire(it)?.destructured?.let { (direction, length, color) ->
DigInstruction(direction, length.toInt(), color)
}
}
instructions.fold(cursor) { cursor, instruction ->
instruction.calculateExtrema(cursor)
}
var area = 0L
instructions.zipWithNext { a, b ->
area += (a.start.x * b.start.y) - (a.start.y * b.start.x)
}
val last = instructions.last()
val first = instructions.first()
//area += (last.start.x * first.start.y) - (last.start.y * first.start.x)
return (area / 2) + (instructions.sumOf { it.length } / 2) + 1
}
fun calculatePartTwo(input: List<String>): Long {
var cursor = Point2dl(0,0)
val instructions = input.mapNotNull {
Regex("(\\w) (\\d+) \\(#(\\w+)\\)").matchEntire(it)?.destructured?.let { (_, _, encoded) ->
RealDigInstruction(encoded)
}
}
instructions.fold(cursor) { cursor, instruction ->
instruction.calculateExtrema(cursor)
}
var area = 0L
instructions.zipWithNext { a, b ->
area += (a.start.x * b.start.y) - (a.start.y * b.start.x)
}
val last = instructions.last()
val first = instructions.first()
area += (last.start.x * first.start.y) - (last.start.y * first.start.x)
return return (area / 2) + (instructions.sumOf { it.length } / 2) + 1
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 7,821 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day14.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.head
import nl.jstege.adventofcode.aoccommon.utils.extensions.isEven
import nl.jstege.adventofcode.aoccommon.utils.extensions.scan
import java.util.*
class Day14 : Day(title = "Chocolate Charts") {
private companion object {
private val INITIAL = arrayOf(3, 7)
}
override fun first(input: Sequence<String>): Any {
return RecipeSequence()
.drop(input.head.toInt())
.take(10)
.joinToString("")
}
override fun second(input: Sequence<String>): Any {
val pattern = input.head
val target = input.head.toLong()
val mod = pow(10, pattern.length.toLong())
return RecipeSequence()
.scan(0L to 0) { (current, i), v ->
(10 * current + v) % mod to i + 1
}
.first { it.first == target }
.let { (_, i) -> i - pattern.length }
}
private tailrec fun pow(a: Long, b: Long, acc: Long = 1): Long = when {
b == 0L -> acc
b.isEven -> pow(a * a, b ushr 1, acc)
else -> pow(a * a, b ushr 1, acc * a)
}
class RecipeSequence : Sequence<Int> {
override fun iterator(): Iterator<Int> = object : Iterator<Int> {
var scores = mutableListOf(*INITIAL)
var remaining = ArrayDeque<Int>(scores)
var i = 0
var j = 1
override fun hasNext(): Boolean = true
override fun next(): Int {
if (remaining.isNotEmpty()) {
return remaining.removeFirst()
}
val x = scores[i] + scores[j]
if (x >= 10) {
scores.add(1)
scores.add(x - 10)
remaining.add(x - 10)
i = (i + 1 + scores[i]) % scores.size
j = (j + 1 + scores[j]) % scores.size
return 1
}
scores.add(x)
i = (i + 1 + scores[i]) % scores.size
j = (j + 1 + scores[j]) % scores.size
return x
}
}
}
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 2,265 | AdventOfCode | MIT License |
2022/src/test/kotlin/Day19.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import io.kotest.assertions.all
import io.kotest.common.ExperimentalKotest
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
private data class Blueprint(
val id: Int,
val oreRobotOreCosts: Int,
val clayRobotOreCosts: Int,
val obsidianRobotOreCosts: Int,
val obsidianRobotClayCosts: Int,
val geodeRobotOreCosts: Int,
val geodeRobotObsidianCosts: Int
)
private data class Stock(
var ore: Int = 0,
var clay: Int = 0,
var obsidian: Int = 0,
var geode: Int = 0
)
private enum class Producing { NONE, ORE_ROBOT, CLAY_ROBOT, OBSIDIAN_ROBOT, GEODE_ROBOT }
private data class Production(
val blueprint: Blueprint,
val robots: Stock = Stock(ore = 1),
val materials: Stock = Stock(),
var factory: Producing = Producing.NONE
) {
fun copy() = Production(blueprint, robots.copy(), materials.copy(), factory)
}
@OptIn(ExperimentalKotest::class)
class Day19 : StringSpec({
"puzzle part 01" {
val blueprints = getBlueprints().asSequence()
val geodes = blueprints.map { it.id to collectMaterials(it, 24).geode }.toList()
all {
geodes.sumOf { it.first * it.second } shouldBe 2301
geodes shouldBe idToMaxGeode
}
}
"puzzle part 02" {
val blueprints = getBlueprints().asSequence().take(3)
val geodes = blueprints
.map { collectMaterials(it, 32).geode }
.reduce { acc, it -> acc * it }
geodes shouldBe 10336
}
})
private fun collectMaterials(blueprint: Blueprint, minutes: Int): Stock {
val productions = mutableSetOf(Production(blueprint))
repeat(minutes) { _ ->
productions.removeNonPromising()
productions.forEach {
if (it.canProduceGeodeRobot()) it.produceGeodeRobot()
}
productions.addAll(
buildList {
productions.forEach {
if (it.canProduceObsidianRobot()) add(it.copy().apply { produceObsidianRobot() })
if (it.canProduceClayRobot()) add(it.copy().apply { produceClayRobot() })
if (it.canProduceOreRobot()) add(it.copy().apply { produceOreRobot() })
}
}
)
productions.forEach {
it.collectMaterials()
it.deliverRobot()
}
}
return productions.maxBy { it.materials.geode }.materials
}
private fun MutableSet<Production>.removeNonPromising() {
val maxPromisingStates = 1500 // Arbitrary number based on playing with the results
if (count() <= maxPromisingStates) return
val promising = sortedWith(
compareByDescending<Production> { it.materials.geode }
.thenByDescending { it.robots.geode }
.thenByDescending { it.robots.obsidian }
.thenByDescending { it.robots.clay }
.thenByDescending { it.robots.ore }
).take(maxPromisingStates)
removeIf { it !in promising }
}
private fun Production.canProduceOreRobot() = factory == Producing.NONE &&
materials.ore >= blueprint.oreRobotOreCosts
private fun Production.canProduceClayRobot() = factory == Producing.NONE &&
materials.ore >= blueprint.clayRobotOreCosts
private fun Production.canProduceObsidianRobot() = factory == Producing.NONE &&
materials.clay >= blueprint.obsidianRobotClayCosts && materials.ore >= blueprint.obsidianRobotOreCosts
private fun Production.canProduceGeodeRobot() = factory == Producing.NONE &&
materials.obsidian >= blueprint.geodeRobotObsidianCosts && materials.ore >= blueprint.geodeRobotOreCosts
private fun Production.produceOreRobot() {
factory = Producing.ORE_ROBOT
materials.ore -= blueprint.oreRobotOreCosts
}
private fun Production.produceClayRobot() {
factory = Producing.CLAY_ROBOT
materials.ore -= blueprint.clayRobotOreCosts
}
private fun Production.produceObsidianRobot() {
factory = Producing.OBSIDIAN_ROBOT
materials.clay -= blueprint.obsidianRobotClayCosts
materials.ore -= blueprint.obsidianRobotOreCosts
}
private fun Production.produceGeodeRobot() {
factory = Producing.GEODE_ROBOT
materials.obsidian -= blueprint.geodeRobotObsidianCosts
materials.ore -= blueprint.geodeRobotOreCosts
}
private fun Production.collectMaterials() {
materials.ore += robots.ore
materials.clay += robots.clay
materials.obsidian += robots.obsidian
materials.geode += robots.geode
}
private fun Production.deliverRobot() {
when (factory) {
Producing.NONE -> return
Producing.ORE_ROBOT -> robots.ore++
Producing.CLAY_ROBOT -> robots.clay++
Producing.OBSIDIAN_ROBOT -> robots.obsidian++
Producing.GEODE_ROBOT -> robots.geode++
}
factory = Producing.NONE
}
private fun getBlueprints(): List<Blueprint> {
val blueprints = getPuzzleInput("day19-input.txt").toList()
.map { s ->
"""(\d+)""".toRegex().findAll(s)
.map {
it.groupValues.first().toInt()
}
.toList()
.let {
Blueprint(it[0], it[1], it[2], it[3], it[4], it[5], it[6])
}
}
return blueprints
}
private val idToMaxGeode = listOf(
1 to 3,
2 to 0,
3 to 0,
4 to 2,
5 to 9,
6 to 2,
7 to 1,
8 to 0,
9 to 6,
10 to 1,
11 to 15,
12 to 0,
13 to 9,
14 to 11,
15 to 0,
16 to 0,
17 to 12,
18 to 0,
19 to 0,
20 to 3,
21 to 3,
22 to 1,
23 to 16,
24 to 0,
25 to 7,
26 to 9,
27 to 5,
28 to 0,
29 to 15,
30 to 1
)
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 5,639 | adventofcode | MIT License |
src/main/kotlin/com/askrepps/advent2022/day15/Day15.kt | askrepps | 726,566,200 | false | {"Kotlin": 99712} | /*
* MIT License
*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.askrepps.advent2022.day15
import com.askrepps.advent2022.util.getInputLines
import java.io.File
import kotlin.math.abs
data class GridCoordinates(val x: Int, val y: Int) {
fun manhattanDistanceTo(other: GridCoordinates) =
abs(x - other.x) + abs(y - other.y)
}
data class SensorReport(val sensor: GridCoordinates, val beacon: GridCoordinates) {
val closestBeaconDistance = sensor.manhattanDistanceTo(beacon)
}
fun String.toCoordinates(): GridCoordinates {
val (xPart, yPart) = split(", ")
return GridCoordinates(
xPart.substringAfter("=").toInt(),
yPart.substringAfter("=").toInt()
)
}
fun String.toSensorReport(): SensorReport {
val (sensorPart, beaconPart) = split(": ")
return SensorReport(
sensorPart.substringAfter("at ").toCoordinates(),
beaconPart.substringAfter("at ").toCoordinates()
)
}
fun countBeaconExclusionPointsInLine(sensorReports: List<SensorReport>, searchY: Int): Int {
val maxDistanceMagnitude = sensorReports.maxOf { it.closestBeaconDistance }
val leftmostSearchX = sensorReports.minOf { it.sensor.x } - maxDistanceMagnitude
val rightMostSearchX = sensorReports.maxOf { it.sensor.x } + maxDistanceMagnitude
val searchXRange = leftmostSearchX..rightMostSearchX
return searchXRange.count { searchX ->
val testPoint = GridCoordinates(searchX, searchY)
cannotContainNewBeacon(testPoint, sensorReports)
}
}
fun cannotContainNewBeacon(point: GridCoordinates, sensorReports: List<SensorReport>) =
sensorReports.any {
point != it.beacon && point.manhattanDistanceTo(it.sensor) <= it.closestBeaconDistance
}
fun getSensorPerimeterPoints(sensorReport: SensorReport): Set<GridCoordinates> {
// find points that are 1 distance farther out than the distance to the closest beacon
val perimeterPoints = mutableSetOf<GridCoordinates>()
val (sensorX, sensorY) = sensorReport.sensor
val minSearchX = sensorX - sensorReport.closestBeaconDistance - 1
val maxSearchX = sensorX + sensorReport.closestBeaconDistance + 1
for (x in minSearchX..maxSearchX) {
val offset = abs(x - sensorReport.sensor.x) - sensorReport.closestBeaconDistance - 1
perimeterPoints.add(GridCoordinates(x, sensorY + offset))
perimeterPoints.add(GridCoordinates(x, sensorY - offset))
}
return perimeterPoints
}
fun getPart1Answer(sensorReports: List<SensorReport>, searchY: Int) =
countBeaconExclusionPointsInLine(sensorReports, searchY)
fun getPart2Answer(sensorReports: List<SensorReport>, searchRange: IntRange): Long {
// if we can assume there is only one valid position, it must lie on one of the diamonds
// that form the perimeter just outside each sensor's distance to its closest beacon
val beacons = sensorReports.map { it.beacon }.toSet()
for (sensor in sensorReports) {
for (point in getSensorPerimeterPoints(sensor)) {
if (point.x in searchRange && point.y in searchRange
&& point !in beacons && !cannotContainNewBeacon(point, sensorReports)
) {
return point.x * 4000000L + point.y
}
}
}
error("Beacon position not found")
}
fun main() {
val sensorReports = File("src/main/resources/2022/day15.txt")
.getInputLines().map { it.toSensorReport() }
println("The answer to part 1 is ${getPart1Answer(sensorReports, searchY = 2000000)}")
println("The answer to part 2 is ${getPart2Answer(sensorReports, searchRange = 0..4000000)}")
}
| 0 | Kotlin | 0 | 0 | 5ce2228b0951db49a5cf2a6d974112f57e70030c | 4,691 | advent-of-code-kotlin | MIT License |
src/Day08.kt | kuangbin | 575,873,763 | false | {"Kotlin": 8252} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
val n = input.size
val m = input[0].length
val array = Array(n) { BooleanArray(m) }
for (i in 0 until n) {
for (j in 0 until m) {
array[i][j] = false
}
}
for (i in 0 until n) {
var maxValue = -1
for (j in 0 until m) {
val v = input[i][j] - '0'
if (v > maxValue) {
array[i][j] = true
maxValue = v
}
}
maxValue = -1
for (j in m-1 downTo 0) {
val v = input[i][j] - '0'
if (v > maxValue) {
array[i][j] = true
maxValue = v
}
}
}
for (j in 0 until m) {
var maxValue = -1
for (i in 0 until n) {
val v = input[i][j] - '0'
if (v > maxValue) {
array[i][j] = true
maxValue = v
}
}
maxValue = -1
for (i in n-1 downTo 0) {
val v = input[i][j] - '0'
if (v > maxValue) {
array[i][j] = true
maxValue = v
}
}
}
var ans = 0
for (i in 0 until n) {
for (j in 0 until m) {
if (array[i][j]) {
ans++
}
}
}
return ans
}
fun part2(input: List<String>): Int {
val n = input.size
val m = input[0].length
var ans = 0
for (i in 0 until n) {
for (j in 0 until m) {
var t1 = 0
for (x in i-1 downTo 0) {
t1++
if (input[x][j] >= input[i][j]) break
}
var t2 = 0
for (x in i+1 until n) {
t2++
if (input[x][j] >= input[i][j]) break
}
var t3 = 0
for (y in j-1 downTo 0) {
t3++
if (input[i][y] >= input[i][j]) break
}
var t4 = 0
for (y in j+1 until m) {
t4++
if (input[i][y] >= input[i][j]) break
}
ans = max(ans, t1*t2*t3*t4)
}
}
return ans
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | ea0d89065b4d3cb4f6f78f768882d5b5473624d1 | 2,229 | advent-of-code-2022 | Apache License 2.0 |
src/graph/DijstraShortestPath.kt | agapeteo | 157,038,583 | false | null | package graph
import java.util.*
import kotlin.collections.HashSet
data class EdgeTo<V>(val to: V, val weight: Double)
class WeightedGraph<V> {
val edges: MutableMap<V, HashSet<EdgeTo<V>>> = mutableMapOf()
fun addEdge(from: V, to: V, weight: Double) {
edges.computeIfAbsent(from) { HashSet() }.add(EdgeTo(to, weight))
}
fun addBothEdges(from: V, to: V, weight: Double) {
addEdge(from, to, weight)
addEdge(to, from, weight)
}
}
class ShortestPath<V>(private val graph: WeightedGraph<V>) {
private data class VertexRank<V>(val vertex: V, var curWeight: Double, var prev: V?, var visited: Boolean = false)
private val ranksComparator = kotlin.Comparator { stat1: VertexRank<V>, stat2: VertexRank<V> ->
when {
stat1.curWeight == stat2.curWeight -> 0
stat1.curWeight < stat2.curWeight -> -1
else -> 1
}
}
fun minPath(start: V, end: V): List<V> {
val ranks = mutableMapOf<V, VertexRank<V>>()
val minQueue = PriorityQueue(ranksComparator)
val startRank = VertexRank(start, 0.0, null)
ranks[start] = startRank
minQueue.add(startRank)
while (minQueue.isNotEmpty()) {
val curRank = minQueue.poll()
if (curRank.visited) continue
curRank.visited = true
val neighborEdges = graph.edges[curRank.vertex] ?: continue
for (neighborEdge in neighborEdges) {
var neighborRank = ranks[neighborEdge.to]
if (neighborRank != null) {
if (ranks[neighborRank.vertex]!!.visited) continue
if (curRank.curWeight + neighborEdge.weight < neighborRank.curWeight) {
neighborRank.curWeight = curRank.curWeight + neighborEdge.weight
neighborRank.prev = curRank.vertex
}
} else {
neighborRank = VertexRank(neighborEdge.to, curRank.curWeight + neighborEdge.weight, curRank.vertex)
ranks[neighborRank.vertex] = neighborRank
}
minQueue.add(neighborRank)
}
}
return extractPath(end, ranks)
}
private fun extractPath(end: V, ranks: Map<V, VertexRank<V>>): List<V> {
val result = mutableListOf(end)
var prev = ranks[end]?.prev
while (prev != null) {
result.add(prev)
prev = ranks[prev]?.prev
}
result.reverse()
return result
}
} | 0 | Kotlin | 0 | 1 | b5662c8fe416e277c593931caa1b29b7f017ef60 | 2,566 | kotlin-data-algo | MIT License |
src/chapter3/section5/ex1.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter3.section5
import chapter3.section3.RedBlackBST
import chapter3.section4.LinearProbingHashST
import edu.princeton.cs.algs4.In
/**
* 分别使用RedBlackBST和LinearProbingHashST来实现OrderedSET和SET(为键关联虚拟值并忽略它们)
*/
/**
* 基于RedBlackBST实现的有序集合
*/
class RedBlackOrderedSET<K : Comparable<K>> : OrderedSET<K> {
val st = RedBlackBST<K, Any>()
companion object {
private const val DEFAULT_VALUE = ""
}
override fun min(): K {
return st.min()
}
override fun max(): K {
return st.max()
}
override fun floor(key: K): K {
return st.floor(key)
}
override fun ceiling(key: K): K {
return st.ceiling(key)
}
override fun rank(key: K): Int {
return st.rank(key)
}
override fun select(k: Int): K {
return st.select(k)
}
override fun deleteMin() {
st.deleteMin()
}
override fun deleteMax() {
st.deleteMax()
}
override fun size(low: K, high: K): Int {
return st.size(low, high)
}
override fun add(key: K) {
st.put(key, DEFAULT_VALUE)
}
override fun delete(key: K) {
st.delete(key)
}
override fun contains(key: K): Boolean {
return st.contains(key)
}
override fun size(): Int {
return st.size()
}
override fun keys(low: K, high: K): Iterable<K> {
return st.keys(low, high)
}
override fun isEmpty(): Boolean {
return st.isEmpty()
}
override fun iterator(): Iterator<K> {
return st.keys().iterator()
}
}
/**
* 基于LinearProbingHashST实现的集合
*/
class LinearProbingHashSET<K : Any> : SET<K> {
val st = LinearProbingHashST<K, Any>()
companion object {
private const val DEFAULT_VALUE = ""
}
override fun add(key: K) {
st.put(key, DEFAULT_VALUE)
}
override fun delete(key: K) {
st.delete(key)
}
override fun contains(key: K): Boolean {
return st.contains(key)
}
override fun isEmpty(): Boolean {
return st.isEmpty()
}
override fun size(): Int {
return st.size()
}
override fun iterator(): Iterator<K> {
return st.keys().iterator()
}
}
fun main() {
testSET(LinearProbingHashSET())
testOrderedSET(RedBlackOrderedSET())
val set = LinearProbingHashSET<String>()
val orderedSET = RedBlackOrderedSET<String>()
val input = In("./data/tinyTale.txt")
while (!input.isEmpty) {
val key = input.readString()
set.add(key)
orderedSET.add(key)
}
println("set : ${set.joinToString()}")
println("orderedSET: ${orderedSET.joinToString()}")
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 2,769 | Algorithms-4th-Edition-in-Kotlin | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year18/Day17.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year18
import com.grappenmaker.aoc.*
import com.grappenmaker.aoc.Direction.*
fun PuzzleSet.day17() = puzzle(day = 17) {
// Increase the recursion limit for this one: -Xss10m
val lines = inputLines.map { l ->
val (a, b, c) = l.splitInts()
if (l.first() == 'x') Point(a, b)..Point(a, c) else Point(b, a)..Point(c, a)
}
val originalPoints = lines.flatMap(Line::allPoints)
val delta = Point(-originalPoints.minX(), 0)
val points = originalPoints.map { it + delta }
val grid = points.asBooleanGrid().expandEmpty(x = 1, y = 0)
val waterSpring = Point(500, 0) + delta
val generationPoint = waterSpring + DOWN
val rows = grid.rows
val settled = mutableSetOf<Point>()
val flowing = mutableSetOf<Point>()
fun Point.isCompletelyEmpty() = !grid[this] && this !in settled && this !in flowing
fun solve(curr: Point = generationPoint) {
flowing += curr
val down = curr + DOWN
if (down !in grid) return
val left = curr + LEFT
val right = curr + RIGHT
if (down.isCompletelyEmpty()) solve(down)
if (grid[down] || down in settled) {
if (left in grid && left.isCompletelyEmpty()) solve(left)
if (right in grid && right.isCompletelyEmpty()) solve(right)
}
val (gridLeft, gridRight) = rows[curr.y].splitAt(curr.x)
fun Iterable<Point>.findWall(): Point? {
iterator().drain { cur ->
when {
cur !in grid || cur.isCompletelyEmpty() -> return null
grid[cur] -> return cur
}
}
return null
}
val wallToLeft = gridLeft.asReversed().findWall() ?: return
val wallToRight = gridRight.findWall() ?: return
val offset = Point(1, 0)
val toSettle = (wallToLeft + offset..wallToRight - offset).allPoints().toSet()
flowing -= toSettle
settled += toSettle
}
solve()
val my = points.minY()
fun Set<Point>.result() = count { it.y >= my }.s()
partOne = (flowing + settled).result()
partTwo = settled.result()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,176 | advent-of-code | The Unlicense |
2015/16/kotlin/b.kt | shrivatsas | 583,681,989 | false | {"Kotlin": 17998, "Python": 9402, "Racket": 4669, "Clojure": 2953} | import java.io.File
fun main() {
val lines: List<String> = File("../16.input").useLines { it.toList() }
// Sue 410: trees: 1, akitas: 10, vizslas: 6
val pattern = Regex("""(\w+): (\d+)""")
val maps = lines.map { line ->
val matches = pattern.findAll(line)
val m: Map<String, Int> = matches.associate { match -> match.groupValues[1] to match.groupValues[2].toInt() }
m + mapOf("Sue" to line.split(":")[0].split(" ")[1].toInt())
}
val found: Map<String, Int> = mapOf("children" to 3, "cats" to 7, "samoyeds" to 2, "pomeranians" to 3, "akitas" to 0, "vizslas" to 0, "goldfish" to 5, "trees" to 3, "cars" to 2, "perfumes" to 1)
for (m in maps) {
if (m.keys.filter { k -> k != "Sue" }.all { k ->
when (k) {
"cats", "trees" -> m[k]!! > found[k]!!
"pomeranians", "goldfish" -> m[k]!! < found[k]!!
else -> m[k] == found[k]
}}) {
println("Sue ${m["Sue"]} has all the things")
}
}
} | 0 | Kotlin | 0 | 1 | 529a72ff55f1d90af97f8e83b6c93a05afccb44c | 954 | AoC | MIT License |
src/main/java/com/booknara/problem/search/binary/RangeSumOfBSTKt.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.search.binary
import java.util.*
/**
* 938. Range Sum of BST (Easy)
* https://leetcode.com/problems/range-sum-of-bst/
*/
class RangeSumOfBSTKt {
var res = 0
// T:O(n), S:O(h)
fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int {
helper(root, low, high)
return res
}
fun helper(node: TreeNode?, low: Int, high: Int) {
// base case
if (node == null) return
if (node.`val` in low..high)
res += node.`val`
if (low < node.`val`) {
helper(node.left, low, high)
}
if (node.`val` < high) {
helper(node.right, low, high)
}
}
// T:O(n), S:O(h)
fun rangeSumBST1(root: TreeNode?, low: Int, high: Int): Int {
// input check, the number of nodes >= 1
val queue = LinkedList<TreeNode>()
queue.offer(root)
var res = 0
while (!queue.isEmpty()) {
val size = queue.size
for (i in 0 until size) {
val node = queue.poll()
val num = node.`val`
if (num in low..high) {
res += num
}
if (num >= low && node.left != null) {
queue.offer(node.left)
}
if (num <= high && node.right != null) {
queue.offer(node.right)
}
}
}
return res
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
} | 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 1,374 | playground | MIT License |
src/Day04.kt | matheusfinatti | 572,935,471 | false | {"Kotlin": 12612} | fun main() {
val input = readInput("Day04").split("\n")
input
.map { assignment -> assignment.split(",") }
.map { assignment ->
assignment.map { it.split("-") }
}
.map { assignments ->
assignments
.map { it.map(String::toInt) }
.sortedBy { a -> a[0] }
}
.also { assignments ->
assignments.sumOf { (a1, a2) ->
val (start1, end1) = a1
val (start2, end2) = a2
if (
start1 >= start2 &&
end1 <= end2
|| start2 >= start1 &&
end2 <= end1
) {
1L
} else {
0L
}
}.also(::println)
}
.also { assignments ->
assignments.sumOf { (a1, a2) ->
val (_, end1) = a1
val (start2, _) = a2
if (start2 <= end1) {
1L
} else {
0L
}
}.also(::println)
}
} | 0 | Kotlin | 0 | 0 | a914994a19261d1d81c80e0ef8e196422e3cd508 | 1,149 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/g2901_3000/s2967_minimum_cost_to_make_array_equalindromic/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2967_minimum_cost_to_make_array_equalindromic
// #Medium #Array #Math #Sorting #Greedy #2024_01_19_Time_363_ms_(100.00%)_Space_56_MB_(86.49%)
import kotlin.math.abs
import kotlin.math.min
@Suppress("NAME_SHADOWING")
class Solution {
fun minimumCost(nums: IntArray): Long {
nums.sort()
val len = nums.size
val m = if (len % 2 != 0) len / 2 else len / 2 - 1
val previousPalindrome = getPreviousPalindrome(nums[m])
val nextPalindrome = getNextPalindrome(nums[m])
var ans1: Long = 0
var ans2: Long = 0
for (num in nums) {
ans1 += abs((previousPalindrome - num))
ans2 += abs((nextPalindrome - num))
}
return min(ans1, ans2)
}
private fun getPreviousPalindrome(num: Int): Int {
var previousPalindrome = num
while (!isPalindrome(previousPalindrome)) {
previousPalindrome--
}
return previousPalindrome
}
private fun getNextPalindrome(num: Int): Int {
var nextPalindrome = num
while (!isPalindrome(nextPalindrome)) {
nextPalindrome++
}
return nextPalindrome
}
private fun isPalindrome(num: Int): Boolean {
var num = num
val copyNum = num
var reverseNum = 0
while (num > 0) {
reverseNum = reverseNum * 10 + num % 10
num /= 10
}
return copyNum == reverseNum
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,473 | LeetCode-in-Kotlin | MIT License |
word-generator/src/main/kotlin/com/github/pjozsef/wordgenerator/rule/ScrambleRule.kt | pjozsef | 248,344,539 | false | null | package com.github.pjozsef.wordgenerator.rule
import com.github.pjozsef.wordgenerator.util.Scrambler
import java.util.Random
class ScrambleRule(
prefix: String = "!",
val scrambler: Scrambler = Scrambler()
) : Rule {
private val vowels = listOf('a', 'i', 'e', 'o', 'u', 'y')
private val ruleRegexString = "((?<rule>[\\w\\s|]+)(,(?<params>[\\s0-9\\-.,]+))?)"
private val _regex: Regex =
Regex("$prefix\\{$ruleRegexString}")
override val regex: Regex
get() = _regex
private val ruleRegex = Regex(ruleRegexString)
private val rangeRegex = Regex("(?<range>(?<min>[1-9][0-9]*)?-(?<max>[1-9][0-9]*)?)")
private val ratioRegex = Regex("[0-9]+\\.[0-9]+")
override fun evaluate(rule: String, mappings: Map<String, List<String>>, random: Random): String {
scrambler.random = random
val match = ruleRegex.matchEntire(rule) ?: error("Unparsable rule: $rule")
val ruleSection = match.groups["rule"]?.value ?: error("Cannot find rule!")
val (range, ratio) = parseParams(match.groups["params"]?.value ?: "")
return ruleSection.split("|").let {
val randomValue = it[random.nextInt(it.size)].replace(Regex("\\s"), "")
mappings[randomValue]?.let { mappingList ->
mappingList[random.nextInt(mappingList.size)]
} ?: randomValue
}.let {
if (ratio != null) {
val (vowels, consonants) = it.partition {
vowels.contains(it)
}.let {
scrambler.scramble(it.first).toList() to scrambler.scramble(it.second).toList()
}
combineWithRatio(vowels, consonants, ratio, random)
} else {
scrambler.scramble(it)
}
}.let {
if (range != null) {
val min = range.min ?: 1
val max = range.max ?: it.length
val randomLength = random.nextInt(max - min) + min
it.take(randomLength)
} else {
it
}
}
}
private fun combineWithRatio(vowels: List<Char>, consonants: List<Char>, ratio: Double, random: Random): String {
tailrec fun combine(acc: String, vowels: List<Char>, consonants: List<Char>): String = when {
vowels.isEmpty() -> acc + consonants.joinToString("")
consonants.isEmpty() -> acc + vowels.joinToString("")
else -> {
if (random.nextDouble() < ratio) {
combine(acc + vowels.first(), vowels.drop(1), consonants)
} else {
combine(acc + consonants.first(), vowels, consonants.drop(1))
}
}
}
return combine("", vowels, consonants)
}
private data class RangeParam(val min: Int?, val max: Int?)
private data class ScrambleParams(val range: RangeParam?, val ratio: Double?)
private fun parseParams(rawParams: String) =
rawParams.split(",")
.map {
it.replace(Regex("\\s"), "")
}.filter {
it.isNotBlank()
}.fold(ScrambleParams(null, null)) { acc, param ->
when {
rangeRegex.matches(param) -> {
rangeRegex.matchEntire(param)?.let {
acc.copy(range = RangeParam(it.min(), it.max()))
} ?: error("Unparsable param: $param")
}
ratioRegex.matches(param) -> {
ratioRegex.matchEntire(param)?.let {
acc.copy(ratio = it.value.toDouble())
} ?: error("Unparsable param: $param")
}
else -> error("Unparsable param: $param")
}
}
private fun MatchResult.min() = groups["min"]?.value?.toInt()
private fun MatchResult.max() = groups["max"]?.value?.toInt()
}
| 23 | Kotlin | 0 | 0 | 10a40fd61b18b5baf1723fc3b28c6205b7af30cb | 4,011 | word-generator | MIT License |
src/main/kotlin/smartcalc.kt | kevindcp | 424,878,655 | false | {"Kotlin": 8153} | package calculator
import java.math.BigInteger
fun defineOperator( operatorString: String ): String {
var isValid = operatorString.toIntOrNull()
when{
isValid != null -> return "-1"
}
when{
operatorString.length % 2 == 0 -> return "+"
operatorString == "=" -> return "-2"
else -> return "-"
}
}
fun defineLimits ( expression: List<String>, start: Int) : Int {
var need = 0
var end = start
for ( i in start..expression.size ) {
if (expression[i] == ")") {
need -= 1
}
if (expression[i] == "("){
need += 1
}
end = i
if (need == 0) return end
}
return -1
}
fun evaluate( expressionList: List<String> ) : String {
try {
var i = 0
var expression = expressionList.toMutableList()
var size = expression.size
var flag = 0
while (i < size ) {
if (expression[i] == "(") {
flag = 1
var subexpinicio = i
var subexpfin = defineLimits(expression, subexpinicio)
if ( subexpfin == -1 ){
throw IllegalArgumentException("Operator not valid")
} else {
var subexp = expression.subList(subexpinicio+1, subexpfin).toMutableList()
var eval = evaluate(subexp)
var z = subexpinicio
while (z < subexpfin) {
expression.removeAt(subexpinicio)
z += 1
size -=1
}
expression[subexpinicio] = eval
}
i = 0
} else if (expression[i] == ")" && flag == 0){
throw IllegalArgumentException("Operator not valid")
}else i++
}
i = 0
size = expression.size
while ( i < size - 2 ) {
var op1 = expression[i].toBigInteger()
var op2 = expression[i + 2].toBigInteger()
var operator = expression[i + 1]
when(operator) {
"*" -> {
expression[i+2] = (op1 * op2).toString()
expression.removeAt(i)
expression.removeAt(i)
size -= 2
i = 0
}
"/" -> {
expression[i+2] = (op1 / op2).toString()
expression.removeAt(i)
expression.removeAt(i)
size -= 2
i = 0
}
else -> i += 2
}
}
i = 0
while ( i < size - 2 ) {
var op1 = expression[i].toBigInteger()
var op2 = expression[i + 2].toBigInteger()
var operator = expression[i + 1]
if( operator.length > 1 ) {
operator = defineOperator(operator)
}
when(operator) {
"+" -> expression[i+2] = (op1 + op2).toString()
"-" -> expression[i+2] = (op1 - op2).toString()
else -> throw IllegalArgumentException("Operator not valid")
}
i += 2
}
return expression.last()
} catch (e : Exception) {
return "Invalid expression"
}
}
fun isLetters(string: String): Boolean {
return string.all { it in 'A'..'Z' || it in 'a'..'z' }
}
fun isNumbers(string: String): Boolean {
return string.all { it in '0'..'9' }
}
fun main() {
var variables = mutableMapOf<String, BigInteger>()
loop@ while(true) {
var input = readLine()!!.replace("\\=".toRegex(), "eq=eq").replace("\\(".toRegex(), "(par").replace("\\)".toRegex(), "par)").replace("\\++".toRegex(), "plus+plus").replace("(?<!-)-(--)*(?!-|\\d)".toRegex(), "minus-minus").replace("\\--+".toRegex(), "plus+plus").replace("\\*".toRegex(), "mul*mul").replace("\\/(?!\\d|\\w)".toRegex(), "div/div").replace("\\s".toRegex(), "")
var expression = input.split("plus|minus|eq|mul|div|par".toRegex()).toMutableList()
var eval: String = ""
when {
expression[0] == "/help" -> {
println("sdads")
continue
}
expression[0] == "/exit" -> break
expression[0].startsWith('/') -> {
println("Unknown Command")
continue
}
expression.size == 1 && expression[0] == "" -> continue
expression.size == 1 && isLetters(expression[0]) -> {
when {
variables.containsKey(expression[0]) -> {
println(variables[expression[0]])
continue
}
else -> {
println("Unknown variable")
continue
}
}
}
expression.size == 3 && expression[1] == "=" -> {
when {
isLetters(expression[0]) && !isLetters(expression[2]) -> {
try {
variables[expression[0]] = expression[2].toBigInteger()
continue
} catch (e: Exception){
println("Invalid expression")
continue
}
}
isLetters(expression[0]) && isLetters(expression[2]) -> {
when {
variables.containsKey(expression[2]) ->{
variables[expression[0]] = variables[expression[2]]!!
continue
}
else -> {
println("Invalid assignment")
continue
}
}
}
else -> {
println("Invalid identifier")
continue
}
}
}
expression.size == 3 -> {
println(evaluate(expression))
continue
}
expression.size > 3 -> {
for (i in expression.indices) {
if ( i > 1 && expression[i] == "="){
println("Invalid assignment")
continue@loop
}
}
when {
expression[1] == "=" -> when {
isLetters(expression[0]) -> {
variables[expression[0]] = evaluate(expression.subList(2, expression.size - 1)).toBigInteger()
continue
}
else -> continue
}
else->{
for (i in expression.indices) {
if (isLetters(expression[i])) {
when {
variables.containsKey(expression[i]) -> expression[i] = variables[expression[i]].toString()
else -> {
continue
}
}
}
}
println(evaluate(expression))
continue
}
}
}
else -> println(expression)
}
break
}
println("Bye")
}
| 0 | Kotlin | 0 | 0 | e2efb902e22b098d9a1d60df0973157c1847e914 | 7,718 | smart--calc | MIT License |
src/Day10.kt | JonasDBB | 573,382,821 | false | {"Kotlin": 17550} | private fun part1(input: List<String>) {
var c = 0
var xreg = 1
var ret = 0
for (line in input) {
if (line == "noop") {
++c
if ((c + 20) % 40 == 0) {
ret += c * xreg
}
continue
}
val inc = line.split(" ")[1].toInt()
++c
if ((c + 20) % 40 == 0) {
ret += c * xreg
}
++c
if ((c + 20) % 40 == 0) {
ret += c * xreg
}
xreg += inc
}
println(ret)
}
private fun part2(input: List<String>) {
val screen = MutableList(6) { CharArray(40) }
var c = 0
var xreg = 1
for (line in input) {
if (line == "noop") {
val chr = if (c % 40 == xreg || c % 40 == xreg - 1 || c % 40 == xreg + 1) '#' else '.'
screen[c / 40][c % 40] = chr
++c
} else {
val inc = line.split(" ")[1].toInt()
var chr = if (c % 40 == xreg || c % 40 == xreg - 1 || c % 40 == xreg + 1) '#' else '.'
screen[c / 40][c % 40] = chr
++c
chr = if (c % 40 == xreg || c % 40 == xreg - 1 || c % 40 == xreg + 1) '#' else '.'
screen[c / 40][c % 40] = chr
++c
xreg += inc
}
}
screen.forEach { line -> line.forEach { print("$it ") }; println() }
}
fun main() {
val input = readInput("10")
println("part 1")
part1(input)
println("part 2")
part2(input)
}
| 0 | Kotlin | 0 | 0 | 199303ae86f294bdcb2f50b73e0f33dca3a3ac0a | 1,483 | AoC2022 | Apache License 2.0 |
aoc-2016/src/main/kotlin/nl/jstege/adventofcode/aoc2016/days/Day07.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2016.days
import nl.jstege.adventofcode.aoccommon.days.Day
import java.util.*
/**
*
* @author <NAME>
*/
class Day07 : Day(title = "Internet Protocol Version 7") {
override fun first(input: Sequence<String>): Any = input.asSequence()
.count { ipv7 ->
ipv7.getIpv7Segments().run {
hypernet.none { it.hasAbbaSequence() }
&& notHypernet.any { it.hasAbbaSequence() }
}
}
override fun second(input: Sequence<String>): Any = input.asSequence()
.count { ipv7 ->
ipv7.getIpv7Segments().run {
val possibleBabs = notHypernet
.flatMap { it.calculateAbas() }
.map { it.calculateBab() }
hypernet.any { s -> possibleBabs.any { it in s } }
}
}
private fun String.getIpv7Segments(): Ipv7Segments {
val segments = Ipv7Segments()
val tokenizer = StringTokenizer(this, "[]", true)
var isHyperNet = false
var previous = ""
while (tokenizer.hasMoreTokens()) {
when (val token = tokenizer.nextToken()) {
"[", "]" -> {
if (previous.isNotEmpty()) {
if (isHyperNet) segments.hypernet.add(previous)
else segments.notHypernet.add(previous)
}
isHyperNet = token == "["
previous = ""
}
else -> previous = token
}
}
if (previous.isNotEmpty()) {
if (isHyperNet) segments.hypernet.add(previous)
else segments.notHypernet.add(previous)
}
return segments
}
private fun String.hasAbbaSequence(): Boolean = (0 until this.length - 3)
.any {
this[it] != this[it + 1] && this[it] == this[it + 3] && this[it + 1] == this[it + 2]
}
private fun String.calculateAbas(): Set<String> = (0 until this.length - 2)
.filter { this[it] == this[it + 2] && this[it] != this[it + 1] }
.map { this.substring(it, it + 2) }
.toSet()
private fun String.calculateBab(): String = "${this[1]}${this[0]}${this[1]}"
private data class Ipv7Segments(
val hypernet: MutableSet<String> = mutableSetOf(),
val notHypernet: MutableSet<String> = mutableSetOf()
)
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 2,438 | AdventOfCode | MIT License |
src/main/kotlin/com/danielmichalski/algorithms/data_structures/_09_hash_table/HashTable.kt | DanielMichalski | 288,453,885 | false | {"Kotlin": 101963, "Groovy": 19141} | package com.danielmichalski.algorithms.data_structures._09_hash_table
import kotlin.math.min
class HashTable {
private val length = 17
private val elements = arrayOfNulls<ArrayList<HashPair>>(length)
init {
for (i in elements.indices) {
elements[i] = ArrayList(0)
}
}
fun set(key: String, value: String): Int {
val index = hash(key)
val listUnderIndex = elements[index]
listUnderIndex!!.add(HashPair(key, value))
return index
}
fun get(key: String): String? {
val index = hash(key)
val list = elements[index]
if (list != null) {
val iter = list.iterator()
while (iter.hasNext()) {
val pair = iter.next()
if (key == pair.getKey()) {
return pair.getValue()
}
}
}
return null
}
fun keys(): List<String> {
val keys = ArrayList<String>(length)
for (element in elements) {
if (element != null) {
val iter = element.iterator()
while (iter.hasNext()) {
val pair = iter.next()
val key = pair.getKey()
if (!keys.contains(key)) {
keys.add(key)
}
}
}
}
return keys
}
fun values(): List<String> {
val values = ArrayList<String>(length)
for (element in elements) {
if (element != null) {
val iter = element.iterator()
while (iter.hasNext()) {
val pair = iter.next()
val value = pair.getValue()
if (!values.contains(value)) {
values.add(value)
}
}
}
}
return values
}
private fun hash(key: String): Int {
var total = 0
val prime = 31
for (i in 0 until min(key.length, 100)) {
val value = key.codePointAt(i) - 96
total = (total + prime + value) % length
}
return total
}
override fun toString(): String {
var output = "{\n"
for (element in elements) {
if (element!!.size > 0) {
val iter = element.iterator()
while (iter.hasNext()) {
val pair = iter.next()
output += "\t{ ${pair.getKey()}: ${pair.getValue()} }\t"
}
output += "\n"
}
}
output += "}\n"
return output
}
}
| 0 | Kotlin | 1 | 7 | c8eb4ddefbbe3fea69a172db1beb66df8fb66850 | 2,684 | algorithms-and-data-structures-in-kotlin | MIT License |
src/Day01.kt | semanticer | 577,822,514 | false | {"Kotlin": 9812} | fun main() {
fun part1(input: List<String>): Int {
val totals = caloriesByElf(input)
return totals.maxOrNull() ?: 0
}
fun part2(input: List<String>): Int {
val totals = caloriesByElf(input)
val sortedTotals = totals.sortedDescending()
return sortedTotals.take(3).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")
part1(input).println()
part2(input).println()
}
private fun caloriesByElf(input: List<String>): List<Int> {
val totals = mutableListOf<Int>()
var current = 0
for (line in input) {
if (line.isEmpty()) {
totals.add(current)
current = 0
} else {
current += line.trim().toInt()
}
}
totals.add(current)
return totals
} | 0 | Kotlin | 0 | 0 | 9013cb13f0489a5c77d4392f284191cceed75b92 | 964 | Kotlin-Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day04/Day04.kt | jackploeg | 736,755,380 | false | {"Kotlin": 318734} | package nl.jackploeg.aoc._2023.calendar.day04
import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory
import nl.jackploeg.aoc.utilities.readStringFile
import javax.inject.Inject
import kotlin.math.pow
class Day04 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(fileName: String): Int {
val cards: MutableList<ScratchCard> = mutableListOf()
readScratchCards(fileName, cards)
return cards.sumOf { it.getCardPoints() }
}
fun partTwo(fileName: String): Int {
val cards: MutableList<ScratchCard> = mutableListOf()
readScratchCards(fileName, cards)
val cardBuckets: Map<Int, ScratchCard> =
cards.associateBy { it.cardNumber }
cardBuckets.forEach {
val matches = it.value.getCardMatches()
if (matches==0) {
return@forEach
}
for (i in 1..matches) {
cardBuckets[it.key + i]?.incrementCopies(it.value.copies)
}
}
return cardBuckets.map { it.value.copies }.sum()
}
fun readScratchCards(fileName: String, cards: MutableList<ScratchCard>) =
readStringFile(fileName).forEach { cards.add(parseCardData(it)) }
fun parseCardData(line: String): ScratchCard {
val cardNo: Int = line.split(':')[0].split("\\D+".toRegex())[1].toInt()
val numbers: String = line.split(':')[1]
val winningNumbers = numbers.split('|')[0].trim().split("\\D+".toRegex()).map { it.toInt() }
val drawNumbers = numbers.split('|')[1].trim().split("\\D+".toRegex()).map { it.toInt() }
return ScratchCard(cardNo, winningNumbers.toSortedSet(), drawNumbers.toSortedSet())
}
data class ScratchCard(
val cardNumber: Int,
val winningNumbers: MutableSet<Int> = mutableSetOf(),
val drawNumbers: MutableSet<Int> = mutableSetOf()
) {
var copies = 1
fun getCardPoints(): Int {
val wins = drawNumbers.count { it in winningNumbers }
if (wins == 0) {
return 0
}
return 2.0.pow((wins - 1).toDouble()).toInt()
}
fun getCardMatches(): Int =
drawNumbers.count { it in winningNumbers }
fun incrementCopies(increment: Int) {
copies += increment
}
}
}
| 0 | Kotlin | 0 | 0 | f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76 | 2,165 | advent-of-code | MIT License |
src/main/java/challenges/educative_grokking_coding_interview/k_way_merge/_1/MergeSorted.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.k_way_merge._1
import challenges.util.PrintHyphens
/**
Given two sorted integer arrays, 1 nums1 and 2 nums2, and the number of data elements in each array, m and n ,
implement a function that merges the second array into the first one. You have to modify 1 nums1 in place.
https://www.educative.io/courses/grokking-coding-interview-patterns-java/m72yGKyz8Br
*/
internal object MergeSorted {
private fun printArrayWithMarkers(arr: IntArray, pValue: Int): String {
var out = "["
for (i in 0 until arr.size - 1) {
if (i == pValue) {
out += "«"
out += arr[i].toString() + "»" + ", "
} else {
out += arr[i].toString() + ", "
}
}
if (pValue == arr.size - 1) {
out += "«" + arr[arr.size - 1]
out += "»]"
} else {
out += arr[arr.size - 1]
out += "]"
}
return out
}
private fun printArrayWithMarkers(arr: IntArray, iValue: Int, jValue: Int): String {
var out = "["
for (i in 0 until arr.size - 1) {
if (i == iValue || i == jValue) {
out += "«"
out += arr[i].toString() + "»" + ", "
} else {
out += arr[i].toString() + ", "
}
}
if (iValue == arr.size - 1 || jValue == arr.size - 1) {
out += "«" + arr[arr.size - 1]
out += "»]"
} else {
out += arr[arr.size - 1]
out += "]"
}
return out
}
private fun mergeSorted(nums1: IntArray, m: Int, nums2: IntArray, n: Int): IntArray {
var p1 = m - 1 // set p1 to the last initialised element of nums1
val p2 = n - 1 // set p2 to the last element of nums2
println("\n\t\tInitialising p1 to the last data element of nums1:")
println("\t\t\t" + printArrayWithMarkers(nums1, p1))
println("\t\t\tp1: " + p1 + ", value: " + nums1[p1])
println("\n\t\t Initialising p2 to the last data element of nums2:")
println("\t\t\t" + printArrayWithMarkers(nums2, p2))
println("\t\t\tp1: " + p2 + ", value: " + nums2[p2])
// traverse backwards over the nums1 array
println("\n\tTraversing the nums1 array using pointer p:")
var x = 0
for (p in m + n - 1 downTo 0) {
println("\t\tLoop iteration: $x")
x += 1
println("\t\t\t" + printArrayWithMarkers(nums1, p1))
print("\t\t\tp1: $p1, value: ")
if (p1 < 0) println(nums1[p1 + 1]) else println(nums1[p1])
println("\t\t\t" + printArrayWithMarkers(nums2, p2))
print("\t\t\tp2: $p2, value: ")
if (p2 < 0) println(nums2[p2 + 1]) else println(nums2[p2])
// if p1 is not on the first element and the nums1 element is greater than nums2 element
if (p1 >= 0 && nums1[p1] > nums2[p2]) {
println("\t\t\tThe value at p1(" + nums1[p1] + ") > the value at p2(" + nums2[p2] + ")")
// set the element at index p = the element on index p1 in nums1
println("\t\t\t\t" + printArrayWithMarkers(nums1, p1, p))
println("\t\t\t\tp1: " + p1 + ", value: " + nums1[p1])
println("\t\t\t\tp: " + p + ", value: " + nums1[p])
nums1[p] = nums1[p1]
println("\t\t\t\tChanging the value at p to the value at p1:")
println("\t\t\t\t\t" + printArrayWithMarkers(nums1, p))
// move the p1 pointer one element back
println(
""" Decrementing p1: $p1 ⟶ ${p1 - 1}
"""
)
p1 -= 1
}
}
return nums1
}
@JvmStatic
fun main(args: Array<String>) {
val m = intArrayOf(9, 2, 3, 1, 8)
val n = intArrayOf(6, 1, 4, 2, 1)
val nums1 = arrayOf(
intArrayOf(23, 33, 35, 41, 44, 47, 56, 91, 105, 0, 0, 0, 0, 0, 0),
intArrayOf(1, 2, 0),
intArrayOf(1, 1, 1, 0, 0, 0, 0),
intArrayOf(6, 0, 0),
intArrayOf(12, 34, 45, 56, 67, 78, 89, 99, 0)
)
val nums2 = arrayOf(
intArrayOf(32, 49, 50, 51, 61, 99),
intArrayOf(7),
intArrayOf(1, 2, 3, 4),
intArrayOf(-45, -99),
intArrayOf(100)
)
var k = 1
for (i in m.indices) {
print("$k.\tnums1: [")
for (j in 0 until nums1[i].size - 1) {
print(nums1[i][j].toString() + ", ")
}
println(nums1[i][nums1[i].size - 1].toString() + "], m: " + m[i])
print("\tnums2: [")
for (j in 0 until nums2[i].size - 1) {
print(nums2[i][j].toString() + ", ")
}
println(nums2[i][nums2[i].size - 1].toString() + "], n: " + n[i])
mergeSorted(nums1[i], m[i], nums2[i], n[i])
println("\tMerged list: None")
println(PrintHyphens.repeat("-", 100))
k += 1
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 5,191 | CodingChallenges | Apache License 2.0 |
src/Day03.kt | jpereyrol | 573,074,843 | false | {"Kotlin": 9016} | fun main() {
fun part1(input: List<String>): Int {
val chunkedInput = input.map { it.chunked(it.length / 2) }
val intersects = chunkedInput.map {
it.first().toCharArray() intersect it.last().toSet()
}
return intersects.sumOf { it.first().toPriority() }
}
fun part2(input: List<String>): Int {
val chunkedInput = input.chunked(3)
val intersects = chunkedInput.map { (first, second, third) ->
first.toSet() intersect second.toSet() intersect third.toSet()
}
return intersects.sumOf { it.first().toPriority() }
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
fun Char.toPriority(): Int {
return if (this.isUpperCase()) {
this.code - 'A'.code + 27
} else {
this.code - 'a'.code + 1
}
} | 0 | Kotlin | 0 | 0 | e17165afe973392a0cbbac227eb31d215bc8e07c | 865 | advent-of-code | Apache License 2.0 |
examples/nearestNeighbor/src/main/kotlin/NearestNeighbor.kt | p7nov | 235,310,936 | true | {"Kotlin": 380202, "C": 124672, "C++": 2372, "Python": 1766} | import org.jetbrains.numkt.*
import org.jetbrains.numkt.core.KtNDArray
import org.jetbrains.numkt.core.ravel
import org.jetbrains.numkt.math.*
import org.jetbrains.numkt.random.Random
fun generateRandomPoints(size: Int = 10, min: Int = 0, max: Int = 1): KtNDArray<Double> =
(max - min) * Random.randomSample(size, 2) + min
class NearestNeighbor(private val distance: Int = 0) {
private lateinit var xTrain: KtNDArray<Double>
private lateinit var yTrain: KtNDArray<Int>
fun train(x: KtNDArray<Double>, y: KtNDArray<Int>) {
xTrain = x
yTrain = y
}
fun predict(x: KtNDArray<Double>): ArrayList<Int> {
val predictions = ArrayList<Int>()
val sh = x.shape
for (i in 0 until sh[0]) {
if (distance == 0) {
val distances = sum(absolute(xTrain - x[i..(i + 1)].ravel()), axis = 1)
val minIndex = argMin(distances)
predictions.add(yTrain[minIndex])
} else if (distance == 1) {
val distances = sum(square(xTrain - x[i..(i + 1)].ravel()), axis = 1)
val minIndex = argMin(distances)
predictions.add(yTrain[minIndex])
}
}
return predictions
}
}
class Analysis(x: Array<KtNDArray<Double>>, distance: Int) {
lateinit var xTest: KtNDArray<Double>
private set
lateinit var yTest: ArrayList<Int>
private set
private val nofClasses: Int = x.size
private lateinit var range: Pair<Int, Int>
private val classified: ArrayList<KtNDArray<Double>> = ArrayList()
private val nn: NearestNeighbor
init {
val listY = ArrayList<KtNDArray<Long>>()
for ((i, el) in x.indices.zip(x)) {
listY.add(i * ones(el.shape[0]))
}
val xt = concatenate(*x, axis = 0)
nn = NearestNeighbor(distance)
nn.train(xt, array<Int>(listY).ravel())
}
fun prepareTestSamples(min: Int = 0, max: Int = 2, step: Double = 0.01) {
range = Pair(min, max)
// grid
val grid = arrayOf(empty<Double>(201, 201), empty(201, 201))
var s = 0.0
for (j in 0..200) {
for (k in 0..200) {
grid[0][j, k] = s
}
s += step
}
for (j in 0..200) {
s = 0.0
for (k in 0..200) {
grid[1][j, k] = s
s += step
}
}
xTest = vstack(grid[0].ravel(), grid[1].ravel()).t
}
fun analyse() {
yTest = nn.predict(xTest)
for (label in 0 until nofClasses) {
val classI = ArrayList<KtNDArray<Double>>()
for (i in 0 until yTest.size) {
if (yTest[i] == label) {
classI.add(xTest[i..(i + 1)].ravel())
}
}
classified.add(array(classI))
}
}
}
fun main() {
val x1 = generateRandomPoints(50, 0, 1)
val x2 = generateRandomPoints(50, 1, 2)
var tempX = generateRandomPoints(50, 0, 1)
var listX = arrayListOf<List<Double>>()
for (i in 0..49) {
listX.add(arrayListOf(tempX[i, 0], tempX[i, 1] + 1))
}
val x3 = array<Double>(listX)
tempX = generateRandomPoints(50, 1, 2)
listX = arrayListOf()
for (i in 0..49) {
listX.add(arrayListOf(tempX[i, 0], tempX[i, 1] - 1))
}
val x4 = array<Double>(listX)
val c4 = Analysis(arrayOf(x1, x2, x3, x4), distance = 1)
c4.prepareTestSamples()
c4.analyse()
// accuracy
var accuracy = 0.0
for (i in 0 until c4.yTest.size) {
val trueLabel: Int = if (c4.xTest[i..(i + 1)].ravel()[0] < 1 && c4.xTest[i..(i + 1)].ravel()[1] < 1) {
0
} else if (c4.xTest[i..(i + 1)].ravel()[0] > 1 && c4.xTest[i..(i + 1)].ravel()[1] > 1) {
1
} else if (c4.xTest[i..(i + 1)].ravel()[0] < 1 && c4.xTest[i..(i + 1)].ravel()[1] > 1) {
2
} else {
3
}
if (trueLabel == c4.yTest[i]) {
accuracy += 1
}
}
accuracy /= c4.xTest.shape[0]
println(accuracy)
} | 0 | null | 0 | 0 | 30e2ad464f805dc310e2a54dcb5bc2ccca8f1496 | 4,131 | kotlin-numpy | Apache License 2.0 |
code-gen/src/main/kotlin/gen/CodeGen.kt | TimothyEarley | 202,394,163 | false | null | package gen
import java.io.File
import java.util.*
import kotlin.math.abs
fun main(args: Array<String>) {
require(args.size == 1) { "Please pass a file as the first argument" }
val source = File(args[0]).readText()
println(gen(source))
}
fun gen(input: String): String {
val ast = readAST(input.lineSequence().filterNot(String::isBlank))
return (ast.compile() + "halt").print()
}
fun readAST(lines: Sequence<String>): AST {
fun Sequence<String>.recurse(): Pair<AST, Sequence<String>> {
val split = first().split("\\s+".toRegex(), 2)
val (type, value) = if (split.size == 2) split else split + ""
val tail = drop(1)
return when (type) {
";" -> AST.EMPTY to tail
in listOf(
"Sequence",
"Prts",
"Prti",
"Prtc",
"Assign",
"While",
"Less",
"LessEqual",
"NotEqual",
"Add",
"Negate",
"Greater",
"Divide",
"Multiply",
"Mod",
"If", //TODO check
"Subtract"
) -> {
val (first, firstLines) = tail.recurse()
val (second, secondLines) = firstLines.recurse()
AST.Binary(type, first, second) to secondLines
}
in listOf(
"String",
"Identifier",
"Integer"
) -> AST.Terminal(type, value) to tail
else -> error("Unknown type $type")
}
}
return lines.recurse().also { (_, lines) ->
require(lines.toList().isEmpty()) { "Not everything was parsed: ${lines.toList()}" }
}.first
}
sealed class AST {
object EMPTY : AST()
data class Binary(val name: String, val left: AST, val right: AST): AST()
data class Terminal(val name: String, val value: String): AST()
}
data class Instruction(val address: Int, var name: String)
data class Assembly(
val variables: Map<String, Int>,
val constantStrings: List<String>,
val code: List<Instruction>
) {
val pc: Int get() = code.size
fun print(): String =
"Datasize: ${variables.size} Strings: ${constantStrings.size}\n" +
(if (constantStrings.isNotEmpty()) constantStrings.joinToString(separator = "\n", postfix = "\n") else "") +
code.joinToString(transform = { "%4d %-4s".format(it.address, it.name).trimEnd() }, separator = "\n")
fun addConstantString(string: String): Assembly =
if (constantStrings.contains(string)) this
else this.copy(constantStrings = constantStrings + string)
fun addVariable(string: String): Assembly =
if (variables.contains(string)) this
else this.copy(variables = variables + (string to variables.size))
operator fun plus(name: String): Assembly = this.copy(
code = code + Instruction(code.size, name)
)
}
fun AST.compile(state: Assembly = Assembly(emptyMap(), emptyList(), emptyList())): Assembly = when(this) {
AST.EMPTY -> state
is AST.Binary -> when (name) {
"Sequence" -> left.compile(state).let { right.compile(it) }
//TODO merge all the cases of compiler right, compile left, do instruction
"Prts" -> left.compile(state) + "prts"
"Prti" -> left.compile(state) + "prti"
"Prtc" -> left.compile(state) + "prtc"
"Assign" -> (left as AST.Terminal).value.let { id ->
right.compile(state).addVariable(id).let {
it + "store [${it.variables[id]}]"
}
}
"While" -> {
val start = state.pc
lateinit var jzPlaceholder: Instruction
// test
(left.compile(state) +
// jz to end
"jz placeholder"
).let {
jzPlaceholder = it.code.last()
// body
right.compile(it)
}.let {
// jmp back
jzPlaceholder.name = "jz ${jumpDescriptor(jzPlaceholder.address, it.pc + 1)}"
it + "jmp ${jumpDescriptor(it.pc, start)}"
}
}
"If" -> {
lateinit var jzPlaceholder: Instruction
(left.compile(state) + "jz placeholder").let {
jzPlaceholder = it.code.last()
val (_, ifBody, elseBody) = right as AST.Binary
ifBody.compile(it).let {
jzPlaceholder.name = "jz ${jumpDescriptor(jzPlaceholder.address, it.pc)}"
it //TODO else
}
}
}
"Less" -> left.compile(state).let { right.compile(it) + "lt" }
"LessEqual" -> left.compile(state).let { right.compile(it) + "le" }
"Equal" -> left.compile(state).let { right.compile(it) + "eq" }
"NotEqual" -> left.compile(state).let { right.compile(it) + "ne" }
"Greater" -> left.compile(state).let { right.compile(it) + "gt" }
"Add" -> left.compile(state).let { right.compile(it) + "add" }
"Subtract" -> left.compile(state).let { right.compile(it) + "sub" }
"Divide" -> left.compile(state).let { right.compile(it) + "div" }
"Multiply" -> left.compile(state).let { right.compile(it) + "mul" }
"Mod" -> left.compile(state).let { right.compile(it) + "mod" }
"Negate" -> left.compile(state) + "neg"
else -> TODO(name)
}
is AST.Terminal -> when(name) {
"String" -> state.addConstantString(value).let {
it + "push ${it.constantStrings.indexOf(value)}"
}
"Integer" -> state + "push $value"
"Identifier" -> state + "fetch [${state.variables[value]}]"
else -> TODO(this.toString())
}
}
private fun jumpDescriptor(from: Int, to: Int) = if (from > to) {
"(${to - from + 1}) $to"
} else {
"(${to - from - 1}) $to"
} | 0 | Kotlin | 0 | 0 | bb10aca0d2d3ca918bb272657aee5a26ce431560 | 4,988 | rosetta-code-compiler | MIT License |
Problems/Algorithms/847. Shortest Path Visiting All Nodes/ShortestPath.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun shortestPathLength(graph: Array<IntArray>): Int {
val n = graph.size
if (n == 1) return 0
val endingMask = (1 shl n) - 1
val visited = Array(n) { BooleanArray(endingMask+1) { false } }
val queue = ArrayDeque<IntArray>()
for (i in 0..n-1) {
queue.add(intArrayOf(i, (1 shl i)))
visited[i][(1 shl i)] = true
}
var ans = 0
while (!queue.isEmpty()) {
val size = queue.size
for (i in 0..size-1) {
val curr = queue.removeFirst()
val node = curr[0]
val mask = curr[1]
if (mask == endingMask) return ans
for (neighbor in graph[node]) {
val nextMask = mask or (1 shl neighbor)
if (!visited[neighbor][nextMask]) {
visited[neighbor][nextMask] = true
queue.add(intArrayOf(neighbor, nextMask))
}
}
}
ans++
}
return -1
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,206 | leet-code | MIT License |
src/advent/of/code/17thPuzzle.kt | 1nco | 725,911,911 | false | {"Kotlin": 112713, "Shell": 103} | package advent.of.code
import advent.of.code.types.Graph
import utils.Util
import java.util.*
object `17thPuzzle` {
private const val DAY = "17";
private var input: MutableList<String> = arrayListOf();
private var result = 0L;
private var resultSecond = 0L;
fun solve() {
val startingTime = Date();
input.addAll(Reader.readInput(DAY));
first();
second();
println("first: $result");
println("second: $resultSecond");
println(startingTime);
println(Date());
}
private fun first() {
val map = Util.initMapWithNumbers(input);
val weights: MutableMap<Pair<String, String>, Int> = mutableMapOf();
for (i in 0..<map.size) {
for (j in 0..<map[0].size) {
weights.putAll(getWeightsOfVertex("$i;$j", map))
}
}
val start = "0;0"
val end = "${map.size - 1};${map[0].size - 1}"
val shortestPathTree = dijkstra(Graph(weights), start, arrayListOf())
val shortestPathBetweenStartAndEnd = shortestPath(shortestPathTree, start, end);
result = shortestPathBetweenStartAndEnd.map { vertex -> map[vertex.split(";")[0].toInt()][vertex.split(";")[1].toInt()] }.sum().toLong();
}
private fun getWeightsOfVertex(vertex: String, map: List<List<Int>>): Map<Pair<String, String>, Int> {
val weights: MutableMap<Pair<String, String>, Int> = mutableMapOf();
val directions: List<Position> = arrayListOf(
Position(-1, 0),
Position(1, 0),
Position(0, -1),
Position(0, 1)
)
val vx = vertex.split(";")[0].toInt()
val vy = vertex.split(";")[1].toInt()
directions.forEach{direction ->
val neighborX = vx + direction.x;
val neighborY = vy + direction.y;
if (neighborX >= 0 && neighborX < map.size && neighborY < map[0].size && neighborY >= 0) {
weights[Pair(vertex, "$neighborX;$neighborY")] = map[neighborX][neighborY]
}
}
return weights
}
private fun second() {
}
data class Position(var x: Int, var y: Int)
} | 0 | Kotlin | 0 | 0 | 0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3 | 2,205 | advent-of-code | Apache License 2.0 |
src/Day03.kt | nZk-Frankie | 572,894,533 | false | {"Kotlin": 13625} | val FILE = readInput("Day03")
fun main()
{
Part02()
}
fun Part01(){
var score = 9
var TotalScore = 0
for (i in FILE)
{
var len = i.length - 1
var firstHalf = i.slice(0..len/2)
var secondHalf = i.slice((len/2)+1..len)
for(x in 0 until firstHalf.length step 1)
{
if(secondHalf.contains(firstHalf.get(x)))
{
println("Letter: "+ firstHalf.get(x) + " at POS: " + x +" and Line: "+ i)
score = calculateScore(firstHalf.get(x))
TotalScore += score
println("Score This Round:= "+score)
println("Score Total := "+TotalScore)
break
}
}
}
}
fun calculateScore(char:Char):Int{
var score = 0
if(char.toInt()>96)
{
score = 1 + char.toInt() - 'a'.toInt()
}
else
{
score = 27 + char.toInt() - 'A'.toInt()
}
return score
}
fun Part02(){
var score = 0
var priorityScore = 0
for (i in 0 until FILE.size step 3)
{
var fString = FILE.get(i)
var sString = FILE.get(i+1)
var tString = FILE.get(i+2)
for(char in fString)
{
if(sString.contains(char) && tString.contains(char))
{
score = calculateScore(char)
priorityScore += score
println("Badge Found: "+ char)
println("Score This Round: "+ score)
println("Total Priority Score: "+priorityScore)
println("=======================================")
break
}
}
}
}
| 0 | Kotlin | 0 | 0 | b8aac8aa1d7c236651c36da687939c716626f15b | 1,729 | advent-of-code-kotlin | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2019/Dec12.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2019
import org.elwaxoro.advent.Coord3D
import org.elwaxoro.advent.PuzzleDayTester
import org.elwaxoro.advent.lcm
import java.math.BigInteger
import kotlin.math.abs
import kotlin.math.sign
/**
* Day 12: The N-Body Problem
*/
class Dec12 : PuzzleDayTester(12, 2019) {
/**
* Ok pretty easy. move the moons 1000 times and do some math. ez-pz
*/
override fun part1(): Any = (1..1000).fold(loader()) { moons, _ ->
moons.step()
}.sumOf { it.first.absSum() * it.second.absSum() }// == 9139
/**
* CRAAAAP this will never finish on its own.
* Instead, lets split each axis and see when all the moons converge on their starting x position & x velocity (or y, or z)
* Once the period is known for each separate axis, find the least common multiple of all 3 axis: this is the iteration count needed to return to start
* Full disclosure: I needed some hints on this one :rip:
*/
override fun part2(): Any = loader().let { initialMoons ->
var seekX = -1L
var seekY = -1L
var seekZ = -1L
var idx = 0L
var moons = initialMoons
while (seekX < 1 || seekY < 1 || seekZ < 1) {
idx++
moons = moons.step()
if (seekX < 1 && initialMoons.zip(moons).all { (a, b) -> a.first.x == b.first.x && a.second.x == b.second.x }) {
seekX = idx
}
if (seekY < 1 && initialMoons.zip(moons).all { (a, b) -> a.first.y == b.first.y && a.second.y == b.second.y }) {
seekY = idx
}
if (seekZ < 1 && initialMoons.zip(moons).all { (a, b) -> a.first.z == b.first.z && a.second.z == b.second.z }) {
seekZ = idx
}
}
listOf(seekX, seekY, seekZ).map { BigInteger("$it") }.lcm().toLong()
}// == 420788524631496
private fun List<Pair<Coord3D, Coord3D>>.step(): List<Pair<Coord3D, Coord3D>> =
mapIndexed { _, moon ->
val newVel = this.minus(moon).fold(moon.second) { acc, (otherPos, _) ->
val dx = (otherPos.x - moon.first.x).sign
val dy = (otherPos.y - moon.first.y).sign
val dz = (otherPos.z - moon.first.z).sign
acc.add(dx, dy, dz)
}
val newPos = moon.first.add(newVel)
newPos to newVel
}
private fun Coord3D.absSum() = abs(x) + abs(y) + abs(z)
private fun loader() = load().map {
// LAZY
Coord3D.parse(it.replace("<x=", "").replace(" y=", "").replace(" z=", "").replace(">", "")) to Coord3D()
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,621 | advent-of-code | MIT License |
src/day01/Day01.kt | Regiva | 573,089,637 | false | {"Kotlin": 29453} | package day01
import readText
fun main() {
fun readElves(fileName: String): Sequence<Sequence<Int>> {
return readText(fileName)
.splitToSequence("\n\n")
.map { it.lineSequence().map(String::toInt) }
}
// Time — O(n), Memory — O(1)?
fun part1(input: Sequence<Sequence<Int>>) = input.maxOf { it.sum() }
// Time — O(n*log(n)), Memory — O(n)?
fun part2(input: Sequence<Sequence<Int>>): Int {
return input.sortedByDescending { it.sum() }
.take(3)
.sumOf { it.sum() }
}
val testInput = readElves("day01/Day01_test")
check(part1(testInput) == 24000)
val input = readElves("day01/Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2d9de95ee18916327f28a3565e68999c061ba810 | 753 | advent-of-code-2022 | Apache License 2.0 |
classroom/src/main/kotlin/com/radix2/algorithms/week2/Sorting.kt | rupeshsasne | 190,130,318 | false | {"Java": 66279, "Kotlin": 50290} | package com.radix2.algorithms.week2
fun IntArray.selectionSort() {
for (i in 0 until size) {
var j = i
var minIndex = j
while (j < size) {
if (this[minIndex] > this[j]) {
minIndex = j
}
j++
}
val temp = this[i]
this[i] = this[minIndex]
this[minIndex] = temp
}
}
fun IntArray.insertionSort() {
for (i in 0 until this.size) {
var j = i
while (j > 0) {
if (this[j] < this[j - 1]) {
val temp = this[j - 1]
this[j - 1] = this[j]
this[j] = temp
} else {
break
}
j--
}
}
}
enum class Color(val id: Int) {
BLUE(0), WHITE(1), RED(2);
}
data class Pebble(val color: Color)
fun dutchNationalFlag(array: Array<Pebble>) {
var left = 0
var mid = 0
var right = array.size - 1
fun swap(i: Int, j: Int) {
val temp = array[i]
array[i] = array[j]
array[j] = temp
}
while (mid <= right) {
when {
array[mid].color == Color.BLUE -> swap(left++, mid++)
array[mid].color === Color.RED -> swap(mid, right--)
array[mid].color == Color.WHITE -> mid++
}
}
}
fun main(args: Array<String>) {
val array = arrayOf(Pebble(Color.WHITE), Pebble(Color.RED), Pebble(Color.BLUE), Pebble(Color.RED), Pebble(Color.WHITE), Pebble(Color.BLUE))
dutchNationalFlag(array)
val str = array.joinToString { pebble ->
pebble.color.toString()
}
println(str)
} | 0 | Java | 0 | 1 | 341634c0da22e578d36f6b5c5f87443ba6e6b7bc | 1,620 | coursera-algorithms-part1 | Apache License 2.0 |
src/Day01.kt | makohn | 571,699,522 | false | {"Kotlin": 35992} | fun main() {
fun part1(input: List<String>): Int {
val calories = mutableListOf<Int>()
var count = 0
for (s in input) {
if (s.isEmpty()) {
calories.add(count)
count = 0
} else {
count += s.toInt()
}
}
return calories.max()
}
fun part2(input: List<String>): Int {
val calories = mutableListOf<Int>()
var count = 0
for (s in input) {
if (s.isEmpty()) {
calories.add(count)
count = 0
} else {
count += s.toInt()
}
}
calories.add(count)
var total = 0
total += calories.max()
calories.remove(calories.max())
total += calories.max()
calories.remove(calories.max())
total += calories.max()
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2734d9ea429b0099b32c8a4ce3343599b522b321 | 1,201 | aoc-2022 | Apache License 2.0 |
day7/src/main/kotlin/day7/CrabAlignment.kt | snv | 434,384,799 | false | {"Kotlin": 99328} | package day7
import kotlin.math.absoluteValue
fun main() {
// val input = rawInput.parse()
println("""
Part 1: ${CrabSwarm(rawInput().parse()).idealConstantFuelCost}
Part 2: ${CrabSwarm(rawInput().parse()).idealIncreasingConstantFuelCost}
""".trimIndent())
}
class CrabSwarm(private val initalPositions: List<Int>){
private val sortedPositions = initalPositions.sorted()
val medianPosition = sortedPositions.elementAt(initalPositions.count().div(2))
val idealConstantFuelCost = constantFuelCost(medianPosition)
private val smallesPosition = sortedPositions.first()
private val largestPosition = sortedPositions.last()
private val fuelCostsPlot = (smallesPosition..largestPosition)
.associateBy { increasingFuelCost(it) }
.toSortedMap()
val weighedPosition: Int = fuelCostsPlot[fuelCostsPlot.firstKey()]!!
val idealIncreasingConstantFuelCost: Int = increasingFuelCost(weighedPosition)
fun constantFuelCost(targetPosition: Int): Int = initalPositions.sumOf { (targetPosition - it).absoluteValue }
fun increasingFuelCost(targetPosition: Int): Int = initalPositions.sumOf { smallGauss((targetPosition - it).absoluteValue) }
private fun smallGauss(n: Int) = n * ( n + 1) / 2
} | 0 | Kotlin | 0 | 0 | 0a2d94f278defa13b52f37a938a156666314cd13 | 1,265 | adventOfCode21 | The Unlicense |
leetcode2/src/leetcode/BinarySearch.kt | hewking | 68,515,222 | false | null | package leetcode
/**
* 704. 二分查找
* https://leetcode-cn.com/problems/binary-search/
* Created by test
* Date 2019/5/27 22:32
* Description
* 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
提示:
你可以假设 nums 中的所有元素是不重复的。
n 将在 [1, 10000]之间。
nums 的每个元素都将在 [-9999, 9999]之间。
*/
object BinarySearch {
class Solution {
fun search(nums: IntArray, target: Int): Int {
var low = 0
var high = nums.size -1
var m = 0
while (low <= high) {
m = (low + high).div(2)
if (nums[m] == target) {
return m
}else if (nums[m] < target) {
low = m + 1
} else if (nums[m] > target) {
high = m - 1
}
}
return -1
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,278 | leetcode | MIT License |
src/main/kotlin/g1701_1800/s1765_map_of_highest_peak/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1701_1800.s1765_map_of_highest_peak
// #Medium #Array #Breadth_First_Search #Matrix
// #2023_06_18_Time_1087_ms_(100.00%)_Space_141.9_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
private val dir = intArrayOf(0, 1, 0, -1, 0)
fun highestPeak(isWater: Array<IntArray>): Array<IntArray> {
var h = 1
var q: Queue<IntArray> = LinkedList()
for (i in isWater.indices) {
for (j in isWater[0].indices) {
isWater[i][j] = if (isWater[i][j] == 1) 0 else -1
if (isWater[i][j] == 0) {
q.add(intArrayOf(i, j))
}
}
}
while (q.isNotEmpty()) {
val q1: Queue<IntArray> = LinkedList()
for (cur in q) {
val x = cur[0]
val y = cur[1]
for (i in 0..3) {
val nx = x + dir[i]
val ny = y + dir[i + 1]
if (nx >= 0 && nx < isWater.size && ny >= 0 && ny < isWater[0].size && isWater[nx][ny] == -1) {
isWater[nx][ny] = h
q1.add(intArrayOf(nx, ny))
}
}
}
h++
q = q1
}
return isWater
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,315 | LeetCode-in-Kotlin | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year16/Day09.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year16
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.onceSplit
fun PuzzleSet.day09() = puzzle {
fun String.createParts(): List<ExplodePart> = buildList {
var left = this@createParts
while (left.isNotEmpty()) {
if ("(" !in left) {
add(LengthPart(left.length))
break
}
val (before, after) = left.onceSplit("(", "")
if (before.isNotEmpty()) add(LengthPart(before.length))
val (marker, rest) = after.onceSplit(")", "")
left = rest
if (after.isEmpty()) break
if (marker.isNotEmpty()) {
val (x, y) = marker.split("x").map(String::toInt)
add(MarkerPart(x, y, left.take(x).createParts()))
left = left.drop(x)
}
}
}
val parts = input.createParts()
partOne = parts.sumOf {
when (it) {
is LengthPart -> it.length
is MarkerPart -> it.amount * it.times
}
}.s()
fun List<ExplodePart>.partTwo(): Long = sumOf {
when (it) {
is LengthPart -> it.length.toLong()
is MarkerPart -> it.times.toLong() * it.parts.partTwo()
}
}
partTwo = parts.partTwo().s()
}
sealed interface ExplodePart
data class LengthPart(val length: Int) : ExplodePart
data class MarkerPart(val amount: Int, val times: Int, val parts: List<ExplodePart>) : ExplodePart | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,500 | advent-of-code | The Unlicense |
src/main/kotlin/days/Day1.kt | MaciejLipinski | 317,582,924 | true | {"Kotlin": 60261} | package days
class Day1 : Day(1) {
override fun partOne(): Any {
return inputList
.map { it.toInt() }
.mapNotNull { findMatchingFor((inputList.map { i -> i.toInt() } - it), it) }
.first()
.itMultipliedByMatching()
}
override fun partTwo(): Any {
val numbers = inputList.map { it.toInt() }
return numbers
.flatMap { (numbers - it).map { inner -> Pair(inner, it) } }
.asSequence()
.distinct()
.filter { it.first + it.second < 2020 }
.mapNotNull { findMatchingFor(numbers, it.toList().sum()) }
.distinct()
.reduce { acc, i -> acc * i }
}
private fun findMatchingFor(numbers: List<Int>, number: Int): Int? =
numbers.find { it + number == 2020 }
private fun Int.itMultipliedByMatching(): Int = this * (2020 - this)
}
| 0 | Kotlin | 0 | 0 | 1c3881e602e2f8b11999fa12b82204bc5c7c5b51 | 951 | aoc-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day17/Day17.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day17
import execute
import readAllText
import wtf
val shapes = listOf(
"""
....
....
....
####
""".trimIndent(),
"""
....
.#..
###.
.#..
""".trimIndent(),
"""
....
..#.
..#.
###.
""".trimIndent(),
"""
#...
#...
#...
#...
""".trimIndent(),
"""
....
....
##..
##..
""".trimIndent()
).map { Shape(it) }
fun part1(input: String) = solve(input, 2022L)
fun part2(input: String) = solve(input, 1000000000000L)
class Shape(input: String) {
private val data = IntArray(4) { input.lines()[it].toCharArray().toInt() }
operator fun get(shapeY: Int) = data[shapeY]
}
private const val FULL = 511
private const val WALLS = 257
class Chamber {
private val data = IntArray(80) { if (it == 0) FULL else WALLS }
// var offset = 0L
fun isLineEmpty(i: Long) = this[i] and FULL == WALLS
fun cleanUpAbove(i: Long) = (1..8).forEach { dy -> this[i + dy] = WALLS }
private operator fun set(i: Long, value: Int) {
data[(i % data.size).toInt()] = value
}
operator fun get(i: Long) = data[(i % data.size).toInt()]
fun rest(shape: Shape, x: Int, y: Long) {
val chamberY = y + 3
(0..3).forEach { dY ->
val sl = (shape[dY] shl 5) shr x
val cl = this[chamberY - dY]
this[chamberY - dY] = cl or sl
}
}
fun canGo(shape: Shape, x: Int, y: Long): Boolean {
val chamberY = y + 3
return (0..3).all { dY ->
val sl = (shape[dY] shl 5) shr x
val cl = this[chamberY - dY]
sl and cl == 0
}
}
}
private fun CharArray.toInt() = fold(0) { acc, c ->
(acc shl 1) + if (c != '.') 1 else 0
}
private fun solve(input: String, times: Long) = input.trim().let { winds ->
var windIndex = 0
val chamber = Chamber()
var done = 0L
var height = 0L
var snapshotShapeIdx = 0
var snapshotWindIdx = 0
val snapshotChamber = IntArray(40)
var snapshotHeight = 0L
val snapshotAt = 1000L
var period = 0L
var delta = 0L
var repetitions = 0L
while (done < times) {
val shapeIdx = (done % shapes.size).toInt()
val shape = shapes[shapeIdx]
if (done == snapshotAt) {
snapshotHeight = height
snapshotShapeIdx = shapeIdx
snapshotWindIdx = windIndex
snapshotChamber.indices.forEach { snapshotChamber[it] = chamber[height - it] }
}
if (done > snapshotAt && snapshotHeight > 0 && period == 0L) {
if (snapshotWindIdx == windIndex && snapshotShapeIdx == shapeIdx && snapshotChamber.indices.all { snapshotChamber[it] == chamber[height - it] }) {
delta = height - snapshotHeight
period = done - snapshotAt
repetitions = (times / period) - (done / period) - 1
done += repetitions * period
}
}
var x = 3
var y = height + 4
var falling = true
while (falling) {
val dir = winds[windIndex % winds.length]
windIndex = (windIndex + 1) % winds.length
if (dir == '>') {
if (chamber.canGo(shape, x + 1, y)) x += 1
} else if (dir == '<') {
if (chamber.canGo(shape, x - 1, y)) x -= 1
} else wtf("$dir")
if (chamber.canGo(shape, x, y - 1)) y -= 1 else falling = false
}
chamber.rest(shape, x, y)
height = (0..5).map { it + height }.first { chamber.isLineEmpty(it + 1) }
chamber.cleanUpAbove(height)
done++
}
height + repetitions * delta
}
fun main() {
val input = readAllText("local/day17_input.txt")
val test = ">>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>"
execute(::part1, test, 3068)
execute(::part1, input, 3227)
execute(::part2, test, 1514285714288)
execute(::part2, input, 1597714285698)
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 4,060 | advent-of-code-2022 | MIT License |
src/main/kotlin/homeworks/fifth/second/GaussQuadratureFormula.kt | Niksen111 | 689,743,548 | false | {"Kotlin": 112514} | package homeworks.fifth.second
import homeworks.first.Homework1
import homeworks.first.utils.vo.HomeworkData
import homeworks.utils.vo.Seq
import kotlin.math.pow
class GaussQuadratureFormula(
val seq: Seq,
val N: Int
) {
val polynomials = MutableList(N + 1) {
{ _: Double -> 1.0 }
}
val roots = MutableList(N) {
0.0
}
val coef = MutableList(N) {
0.0
}
init {
for (i in 0 ..N) {
when (i) {
0 -> {
polynomials[i] = { _: Double -> 1.0 }
}
1 -> {
polynomials[i] = { x: Double -> x }
}
else -> {
polynomials[i] = { x: Double ->
val cf1 = ((2.0 * i.toDouble() - 1.0) / i.toDouble())
val cf2 = - ((i.toDouble() - 1.0) / i.toDouble())
val res = cf1 * polynomials[i - 1](x) * x + cf2 * polynomials[i - 2](x)
res
}
}
}
}
val rootsData = HomeworkData(
func = polynomials[N],
seq = Seq(-1.0, 1.0),
epsilon = 10.0.pow(-12),
firstDerivative = { 1.0 },
secondDerivative = { 1.0 }
)
val rootsDetection = Homework1(rootsData)
rootsDetection.separateSolutions(200).mapIndexed { ind, rootSeq ->
roots[ind] = rootsDetection.findSolutionByMethod("Secant", rootSeq).result
}
for (i in 0 until N) {
val calculatedPolynomial = polynomials[N - 1](roots[i])
coef[i] = 2.0 * (1.0 - roots[i] * roots[i]) / (N.toDouble() * N.toDouble() * calculatedPolynomial * calculatedPolynomial)
}
}
fun evaluateParameters() {
val (a, b) = seq
for (i in 0 until N) {
roots[i] = (seq.size / 2.0) * roots[i] + (b + a) / 2.0
coef[i] *= seq.size / 2.0
}
}
fun calculate(func: (Double) -> Double): Double {
evaluateParameters()
var result = 0.0
for (i in 0 until N) {
result += coef[i] * func(roots[i])
}
return result
}
} | 0 | Kotlin | 0 | 0 | 15e8493468da8fa909f36f9e0b72e7d6ddd5c5cb | 2,230 | Calculation-Methods | Apache License 2.0 |
src/Day08.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | fun main() {
fun part1(input: List<String>): Int {
val m = input[0].length
val n = input.size
val a: Array<BooleanArray> = Array(n) { BooleanArray(m) }
fun checkMax(input: List<String>, i: Int, j: Int, max: Char): Char {
val c = input[i][j]
if (c > max) {
a[i][j] = true
}
return maxOf(c, max)
}
for (j in 1 until m - 1) {
var max = input[0][j]
for (i in 1 until n - 1) {
max = checkMax(input, i, j, max)
}
}
for (j in 1 until m - 1) {
var max = input[n - 1][j]
for (i in n - 2 downTo 1) {
max = checkMax(input, i, j, max)
}
}
for (i in 1 until n - 1) {
var max = input[i][0]
for (j in 1 until m - 1) {
max = checkMax(input, i, j, max)
}
}
for (i in 1 until n - 1) {
var max = input[i][m - 1]
for (j in m - 2 downTo 1) {
max = checkMax(input, i, j, max)
}
}
var res = n * 2 + m * 2 - 4
for (row in a) {
res += row.count { it }
}
return res
}
fun part2(input: List<String>): Int {
val m = input[0].length
val n = input.size
var max = 0
for (i in 0 until n) {
for (j in 0 until m) {
var up = 0
val c = input[i][j]
for (ii in i - 1 downTo 0) {
up++
if (c <= input[ii][j]) {
break
}
}
var down = 0
for (ii in i + 1 until n) {
down++
if (c <= input[ii][j]) {
break
}
}
var left = 0
for (jj in j - 1 downTo 0) {
left++
if (c <= input[i][jj]) {
break
}
}
var right = 0
for (jj in j + 1 until m) {
right++
if (c <= input[i][jj]) {
break
}
}
max = maxOf(max, up * down * left * right)
}
}
return max
}
part1(readInput("input")).println()
part2(readInput("input")).println()
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 2,565 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day1.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.AsListOfStrings
fun main() {
aoc(AsListOfStrings) {
puzzle { 2023 day 1 }
part1 { input ->
input.sumOf { line ->
val numbers = line.filter { it.isDigit() }
"${numbers.first()}${numbers.last()}".toInt()
}
}
val digits = 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,
)
part2 { input ->
input.sumOf { line ->
val numbers = line.windowed(size = 5, partialWindows = true).mapNotNull {
if (it.first().isDigit()) it.first().digitToInt()
else digits[digits.keys.firstOrNull { digit -> it.startsWith(digit) }]
}
"${numbers.first()}${numbers.last()}".toInt()
}
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 1,132 | aoc-2023 | The Unlicense |
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day04.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2021
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
class Aoc2021Day04 {
companion object {
private const val NUMBER_SEPARATOR = ","
private val ONE_OR_MORE_SPACE = Regex(pattern = "\\s+")
}
data class Marker(val number: Int, var played: Boolean = false)
class Board(
private val columns: Int,
private val rows: Int,
private var markers: Array<Marker>,
private var won: Boolean = false,
var winningNumber: Int = 0,
var score: Int = 0
) {
init {
score = markers.sumOf { it.number }
}
fun completed(): Boolean {
if (won) {
return true
}
for (y in 0 until rows) {
var rowPlayed = true
for (x in 0 until columns) {
rowPlayed = rowPlayed && markers[y * rows + x].played
}
if (rowPlayed) {
return true
}
}
for (x in 0 until columns) {
var columnPlayed = true
for (y in 0 until rows) {
columnPlayed = columnPlayed && markers[y * rows + x].played
}
if (columnPlayed) {
return true
}
}
return false
}
fun play(number: Int) {
val marker = markers.find { it.number == number }
if (marker != null && !marker.played) {
marker.played = true
if (!won) {
score -= number
}
}
if (!won && completed()) {
won = true
winningNumber = number
}
}
}
class Game(
var numbers: IntArray = intArrayOf(),
private var boards: MutableList<Board> = mutableListOf(),
var lastCompleted: Board? = null
) {
fun addBoard(board: Board) {
boards.add(board)
}
fun play(number: Int) {
boards.forEach { board ->
board.play(number)
if (board.completed() && board.winningNumber == number) {
lastCompleted = board
}
}
}
}
private fun String.toIntArray(): IntArray {
return this.split(NUMBER_SEPARATOR).map { it.toInt() }.toIntArray()
}
private fun parse(lines: List<String>): Game {
val game = Game()
var boardColumns = 0
var boardRows = 0
var currentBoard: MutableList<Int> = mutableListOf()
lines.forEachIndexed { index, line ->
when {
index == 0 -> {
game.numbers = lines[0].toIntArray()
}
line.isBlank() -> {
if (currentBoard.isNotEmpty()) {
// convert and add to game
game.addBoard(
Board(
boardColumns,
boardRows,
currentBoard.map { Marker(it) }.toTypedArray()
)
)
}
currentBoard = mutableListOf()
boardRows = 0
boardColumns = 0
}
else -> {
val row = line.trim().split(ONE_OR_MORE_SPACE).map { it.trim().toInt() }.toList()
if (boardColumns == 0) {
boardColumns = row.size
}
currentBoard.addAll(row)
boardRows++
}
}
}
if (currentBoard.isNotEmpty()) {
// convert and add to game
game.addBoard(
Board(
boardColumns,
boardRows,
currentBoard.map { Marker(it) }.toTypedArray()
)
)
}
return game
}
fun part1(input: List<String>): Int {
val game = parse(input.toList())
game.numbers.forEach { number ->
game.play(number)
val lastCompleted = game.lastCompleted
if (lastCompleted != null) {
return lastCompleted.score * lastCompleted.winningNumber
}
}
return -1
}
fun part2(input: List<String>): Int {
val game = parse(input.toList())
game.numbers.forEach { number ->
game.play(number)
}
val lastCompleted = game.lastCompleted
if (lastCompleted != null) {
return lastCompleted.score * lastCompleted.winningNumber
}
return -1
}
}
fun main() {
val solver = Aoc2021Day04()
val prefix = "aoc2021/aoc2021day04"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(4512, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(1924, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
}
| 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 5,341 | adventofcode | MIT License |
src/main/kotlin/com/jacobhyphenated/advent2022/day10/Day10.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day10
import com.jacobhyphenated.advent2022.Day
/**
* Day 10: Cathode-Ray Tube
*
* The input is a list of code instructions that are either:
* noop
* addx y
* There is 1 register and a cpu clock. The register starts at 1
* Noop takes 1 cpu cycle. Addx takes 2 cpu cycles
* At the *end* of the cpu cycles needed for the instruction, the register is updated with the value in addx
*/
class Day10: Day<List<String>> {
override fun getInput(): List<String> {
return readInputFile("day10").lines()
}
/**
* Signal strength is the value in the register multiplied by the clock time.
* Add the signal strengths during the 20th, 60th, 100th, 140th, 180th, and 220th cycles.
*/
override fun part1(input: List<String>): Int {
val cpuMap = generateCpuRegisterMap(input)
return (20 .. 220 step 40).sumOf { cpuMap.getValue(it) * it }
}
/**
* The pixels are written to the screen based on the cpu time.
* A single line is 40 pixels for every 40 cycles. There are 6 lines (240 cpu cycles)
*
* The register value is a pixel that occupies 3 spaces (register +- 1)
* If the cpu cycle (mod 40 per line) is within the register pixel range, the pixel is turned on ("#")
* Otherwise the pixel is off (".")
*
* Print the result on the screen (should be 8 capital letters)
*/
override fun part2(input: List<String>): String {
val cpuMap = generateCpuRegisterMap(input)
return (0 until 240).windowed(40, step = 40).joinToString("\n", prefix = "\n") { lineRange ->
lineRange.joinToString("") { cpuTime ->
val position = cpuTime % 40
val register = cpuMap.getValue(cpuTime + 1) //1 index vs 0 index position
if (position in register - 1..register + 1) {
"#"
} else {
"."
}
}
}
}
/**
* generate a map that shows the register value at every cpu clock cycle
*/
private fun generateCpuRegisterMap(input: List<String>): Map<Int,Int> {
var register = 1
var clock = 1
val cpuMap = mutableMapOf(clock to register)
input.forEach { instruction ->
if (instruction == "noop") {
clock++
} else { // addx
val (_, value) = instruction.split(" ")
cpuMap[clock + 1] = register
register += value.toInt()
clock += 2
}
cpuMap[clock] = register
}
return cpuMap
}
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 2,661 | advent2022 | The Unlicense |
src/Day20.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} | import kotlin.math.abs
class Day20 {
private fun decrypt(input: List<Long>, decryptKey: Int = 1, mixTimes: Int = 1): Long {
val original = input.mapIndexed { index, i -> Pair(index, i *decryptKey)}
val moved = original.toMutableList()
for(i in 0 until mixTimes) {
original.forEach { p ->
val idx = moved.indexOf(p)
moved.removeAt(idx)
moved.add((idx + p.second).mod(moved.size), p)
}
}
return moved.map { it.second }.let {
val idx0 = it.indexOf(0)
it[(1000 + idx0) % moved.size] + it[(2000 + idx0) % moved.size] + it[(3000 + idx0) % moved.size]
}
}
fun part1(input: List<Long>): Long {
return decrypt(input, 1)
}
fun part2(input: List<Long>): Long {
return decrypt(input, 811589153, 10)
}
}
fun main() {
val testInput = readInput("Day20_test").map { it.toLong() }
check(Day20().part1(testInput) == 3L)
check(Day20().part2(testInput) == 1623178306L)
measureTimeMillisPrint {
val input = readInput("Day20").map {it.toLong()}
println(Day20().part1(input))
println(Day20().part2(input))
}
} | 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 1,220 | aoc-22-kotlin | Apache License 2.0 |
src/day3/KotlinMain.kt | nick-bennett | 225,112,065 | false | {"Java": 58302, "Kotlin": 22625} | /*
* Copyright 2019 <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 day3
import java.io.File
import kotlin.math.abs
object KotlinMain {
private const val INPUT_FILE = "input.txt"
private const val DELIMITER = "\\s*,\\s*"
private const val CELL_FORMAT = "%1\$s(row=%2\$d, col=%3\$d)"
private const val LEG_FORMAT = "%s %d"
private const val FORMAT_1 =
"Part 1: Minimum Manhattan distance from origin to intersection is %,d.%n"
private const val FORMAT_2 =
"Part 2: Minimum combined travel distance from origin to intersection is %,d.%n"
private val delimiterRegex = Regex(DELIMITER)
@JvmStatic
fun main(args: Array<String>) {
javaClass.getResource(INPUT_FILE)?.toURI()?.let { uri ->
with(parse(File(uri))) {
print(FORMAT_1.format(process(this) { cell -> cell.manhattan }))
print(FORMAT_2.format(process(this) { cell -> cell.travel }))
}
}
}
private fun parse(file: File): List<Wire> {
return file.useLines { sequence ->
sequence
.map { Wire.parse(it) }
.toList()
}
}
private fun process(wires: List<Wire>, metric: (Cell) -> Int): Int {
val traces: MutableMap<Cell, Cell> = HashMap()
var best: Cell? = null
var bestMeasure = Int.MAX_VALUE
for (wire in wires) {
var row = 0
var column = 0
var travel = 0
for (leg in wire.legs) {
val direction = leg.direction
val rowOffset = direction.rowOffset
val columnOffset = direction.columnOffset
repeat(leg.length) {
row += rowOffset
column += columnOffset
val cell = Cell(wire, row, column, ++travel)
val previous = traces[cell]
if (previous == null) {
traces[cell] = cell
} else if (previous.wire != wire) {
if (metric(cell) < metric(previous)) {
traces[cell] = cell // Not required; extends approach to 3+ wires.
}
val augmented = Cell(wire, row, column, travel + previous.travel)
val testMeasure = metric(augmented)
if (best == null || testMeasure < bestMeasure) {
best = augmented
bestMeasure = testMeasure
}
}
}
}
}
return bestMeasure
}
private enum class Direction(
val rowOffset: Int,
val columnOffset: Int
) {
UP(-1, 0),
RIGHT(0, 1),
DOWN(1, 0),
LEFT(0, -1);
companion object {
fun fromCode(code: Char): Direction? {
return when (code) {
'U' -> UP
'R' -> RIGHT
'D' -> DOWN
'L' -> LEFT
else -> null
}
}
}
}
private class Leg private constructor(val direction: Direction, val length: Int) {
private val str: String = String.format(LEG_FORMAT, direction, length)
override fun toString(): String {
return str
}
companion object {
fun parse(input: String): Leg {
val direction = Direction.fromCode(input[0])
val length = input.substring(1).toInt()
return Leg(direction!!, length)
}
}
}
private class Wire private constructor(val legs: List<Leg>) {
companion object {
fun parse(input: String?): Wire {
return Wire(
delimiterRegex.split(input ?: "").asSequence()
.map { Leg.parse(it) }
.toList()
)
}
}
}
private class Cell(
val wire: Wire,
val row: Int,
val column: Int,
val travel: Int
) {
val manhattan: Int = abs(row) + abs(column)
private val hash: Int = 31 * row.hashCode() + column.hashCode()
private val str: String = CELL_FORMAT.format(javaClass.simpleName, row, column)
override fun hashCode(): Int {
return hash
}
override fun equals(other: Any?): Boolean {
return (other === this || (other is Cell && other.row == row && other.column == column))
}
override fun toString(): String {
return str
}
}
} | 0 | Java | 0 | 1 | 40004a851e09734b3aae730d3350a386f2418ec4 | 5,279 | advent-of-code-2019 | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/Day16.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 16: Packet Decoder
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.readFileAsString
fun main() {
println(" ** Day 16: Packet Decoder ** \n")
val packetTransmission = readFileAsString("/Day16BITSTransmission.txt")
val packetVersionsSum = sumAllVersionNumbersInBitsPackets(packetTransmission)
println("Sum of all packet versions is $packetVersionsSum")
val resultFromBitsPacket = calculateResultFromAllBitsPackets(packetTransmission).first()
println("The final calculated result from the BITS packets is $resultFromBitsPacket")
}
fun sumAllVersionNumbersInBitsPackets(packetTransmissionAsHex: String) =
sumAllVersionNumbersInBitsPackets(decodePackets(packetTransmissionAsHex))
private fun sumAllVersionNumbersInBitsPackets(packetTransmission: List<Packet>): Int =
packetTransmission.sumOf {
when (it) {
is OperatorPacket -> sumAllVersionNumbersInBitsPackets(it.subPackets) + it.packetVersion
is LiteralPacket -> it.packetVersion
else -> 0
}
}
fun calculateResultFromAllBitsPackets(packetTransmissionAsHex: String) = calculateResultFromAllBitsPackets(decodePackets(packetTransmissionAsHex))
private fun calculateResultFromAllBitsPackets(packetTransmission: List<Packet>) =
packetTransmission.filterIsInstance<OperatorPacket>().map(::calculateResultFromBitsPacket)
private fun calculateResultFromBitsPacket(packet: OperatorPacket): Long {
val subPacketValues = packet.subPackets.mapNotNull {
when (it) {
is OperatorPacket -> calculateResultFromBitsPacket(it)
is LiteralPacket -> it.literal
else -> null
}
}
return when (packet.operatorPacketType) {
OperatorPacketType.SUM -> subPacketValues.sum()
OperatorPacketType.PRODUCT -> subPacketValues.fold(1) { accumulator, value -> accumulator * value }
OperatorPacketType.MINIMUM -> subPacketValues.minOrNull() ?: 0
OperatorPacketType.MAXIMUM -> subPacketValues.maxOrNull() ?: 0
OperatorPacketType.GREATER_THAN -> if (subPacketValues[0] > subPacketValues[1]) 1 else 0
OperatorPacketType.LESS_THAN -> if (subPacketValues[0] < subPacketValues[1]) 1 else 0
OperatorPacketType.EQUAL_TO -> if (subPacketValues[0] == subPacketValues[1]) 1 else 0
}
}
fun decodePackets(packetTransmissionAsHex: String) = decodePackets(binaryBufferFromHex(packetTransmissionAsHex))
private fun decodePackets(packetTransmission: BinaryBuffer): List<Packet> {
val packets = mutableListOf<Packet>()
while (!packetTransmission.isEmpty()) {
packets.add(decodePacket(packetTransmission))
}
return packets
}
private fun decodePacket(packetTransmission: BinaryBuffer): Packet {
val packetVersion = packetTransmission.takeInt(3)
val packetType = packetTransmission.takeInt(3)
return when (packetType) {
4 -> decodeLiteralPacket(packetVersion, packetTransmission)
else -> decodeOperatorPacket(packetVersion, packetType, packetTransmission)
}
}
private fun decodeLiteralPacket(packetVersion: Int, packetTransmission: BinaryBuffer): LiteralPacket {
val halfBytes = mutableListOf<String>()
do {
val continueBit = packetTransmission.takeBoolean()
halfBytes.add(packetTransmission.takeBits(4))
} while (continueBit)
val literal = halfBytes.joinToString("").toLong(2)
return LiteralPacket(packetVersion, literal)
}
private fun decodeOperatorPacket(packetVersion: Int, packetType: Int, packetTransmission: BinaryBuffer): OperatorPacket {
val lengthTypeId = packetTransmission.takeBits(1)
val subPackets = when (lengthTypeId) {
"0" -> decodeOperatorSubPacketsUsingLengthOfPackets(packetTransmission)
else -> decodeOperatorSubPacketsUsingNumberOfPackets(packetTransmission)
}
return OperatorPacket(packetVersion, OperatorPacketType.fromInt(packetType), subPackets)
}
private fun decodeOperatorSubPacketsUsingLengthOfPackets(packetTransmission: BinaryBuffer): List<Packet> {
val lengthOfSubPackets = packetTransmission.takeInt(15)
val subPacketBuffer = BinaryBuffer(packetTransmission.takeBits(lengthOfSubPackets))
return decodePackets(subPacketBuffer)
}
private fun decodeOperatorSubPacketsUsingNumberOfPackets(packetTransmission: BinaryBuffer): List<Packet> {
val numberOfSubPackets = packetTransmission.takeInt(11)
return (0 until numberOfSubPackets).map { decodePacket(packetTransmission) }
}
open class Packet(open val packetVersion: Int)
data class LiteralPacket(override val packetVersion: Int, val literal: Long) : Packet(packetVersion)
data class OperatorPacket(
override val packetVersion: Int,
val operatorPacketType: OperatorPacketType,
val subPackets: List<Packet>) : Packet(packetVersion)
enum class OperatorPacketType(val operatorType: Int) {
SUM(0),
PRODUCT(1),
MINIMUM(2),
MAXIMUM(3),
GREATER_THAN(5),
LESS_THAN(6),
EQUAL_TO(7);
companion object {
fun fromInt(value: Int) = values().first { it.operatorType == value }
}
}
private class BinaryBuffer(private val binaryString: String) {
private var bufferPosition = 0
fun takeBits(bits: Int) =
binaryString
.substring(bufferPosition, bufferPosition + bits)
.also { bufferPosition += bits }
fun takeInt(bits: Int) =
binaryString
.substring(bufferPosition, bufferPosition + bits)
.toInt(2)
.also { bufferPosition += bits }
fun takeBoolean() = binaryString[bufferPosition++] == '1'
fun isEmpty() = !binaryString.substring(bufferPosition).contains('1')
}
private fun binaryBufferFromHex(hexString: String) = BinaryBuffer(parseHex(hexString))
private fun parseHex(packetTransmissionAsHex: String) =
packetTransmissionAsHex
.toCharArray()
.joinToString("") { it.digitToInt(16).toString(2).padStart(4, '0') }
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 5,955 | AdventOfCode2021 | MIT License |
mobile/src/main/java/ch/epfl/sdp/mobile/application/chess/parser/StringCombinators.kt | epfl-SDP | 462,385,783 | false | {"Kotlin": 1271815, "Shell": 359} | package ch.epfl.sdp.mobile.application.chess.parser
import ch.epfl.sdp.mobile.application.chess.parser.Combinators.filter
import ch.epfl.sdp.mobile.application.chess.parser.Combinators.map
typealias Token = String
/** An object which contains some convenience parser combinators for [String]. */
object StringCombinators {
/** Parses the first [Char] of a [String], if it's not empty. */
fun char(): Parser<String, Char> = Parser {
if (it.isNotEmpty()) {
sequenceOf(Parser.Result(it.drop(1), it.first()))
} else emptySequence()
}
/**
* Parses the first [Char] of a [String], if it's not empty and has the provided value.
*
* @param value the value that is searched.
*/
fun char(value: Char): Parser<String, Char> = char().filter { it == value }
/** Parses the first digit of a [String], if it exists. */
fun digit(): Parser<String, Int> = char().filter { it in '0'..'9' }.map { it - '0' }
/**
* Parses the first [Token] of a [String].
*
* @param delimiter the delimiter between each token.
*/
fun token(delimiter: Char = ' '): Parser<String, Token> =
Parser<String, String> {
if (it.isNotEmpty()) {
val splitString = it.trim { char -> char == delimiter }.split(delimiter, limit = 2)
val result = splitString.first()
val remaining = splitString.drop(1).firstOrNull() ?: ""
sequenceOf(Parser.Result(remaining, result))
} else {
emptySequence()
}
}
.filter { it.isNotEmpty() }
/**
* Parses the first [Token] of a [String], if it's not empty and has the provided value.
*
* @param value the value that is searched.
* @param delimiter the delimiter between each token.
*/
fun token(value: Token, delimiter: Char = ' '): Parser<String, Token> =
token(delimiter).filter { it == value }
/**
* Parse the first [Token] of a [String], and try to find the corresponding [DictKey] homophone.
*
* @param DictKey Key type of dictionary.
* @param dictionary where to look the search the homophone.
* @param delimiter the delimiter between each token.
*/
fun <DictKey> convertToken(
dictionary: Map<DictKey, List<String>>,
delimiter: Char = ' '
): Parser<String, DictKey?> =
token(delimiter).map { token ->
for (entry in dictionary) {
if (entry.value.any { it == token }) {
return@map entry.key
}
}
return@map null
}
/**
* Filters the results from this [Parser] which have an empty remaining input to parse,
* effectively making sure the remaining string is empty.
*
* @param O the type of the output of this [Parser].
*/
fun <O> Parser<String, O>.checkFinished(): Parser<String, O> = Parser {
parse(it).filter { r -> r.remaining.isEmpty() }
}
}
| 15 | Kotlin | 2 | 13 | 71f6e2a5978087205b35f82e89ed4005902d697e | 2,845 | android | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem2136/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2136
/**
* LeetCode page: [2136. Earliest Possible Day of Full Bloom](https://leetcode.com/problems/earliest-possible-day-of-full-bloom/);
*/
class Solution {
/* Complexity:
* Time O(NLogN) and Space O(N) where N is the size of plantTime and growTime;
*/
fun earliestFullBloom(plantTime: IntArray, growTime: IntArray): Int {
val sortedSeeds = getSeedsSortedByDescendingGrowTime(plantTime, growTime)
var plantDoneTime = 0
var latestBloomTime = 0
for (seed in sortedSeeds) {
plantDoneTime += seed.plantTime
val newSeedBloomTime = plantDoneTime + seed.growTime
latestBloomTime = maxOf(latestBloomTime, newSeedBloomTime)
}
return latestBloomTime
}
private fun getSeedsSortedByDescendingGrowTime(plantTime: IntArray, growTime: IntArray): List<Seed> {
val seeds = MutableList(plantTime.size) { index -> Seed(plantTime[index], growTime[index]) }
seeds.sortByDescending { it.growTime }
return seeds
}
private class Seed(val plantTime: Int, val growTime: Int)
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,140 | hj-leetcode-kotlin | Apache License 2.0 |
src/chapter1/section1/binarySearch.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter1.section1
//课本中的二分查找原版
fun binarySearch(key: Int, array: IntArray): Int {
var low = 0
var high = array.size - 1
while (low <= high) {
val mid = (low + high) / 2
when {
key < array[mid] -> high = mid - 1
key > array[mid] -> low = mid + 1
else -> return mid
}
}
return -1
}
fun <T : Comparable<T>> binarySearch(key: T, array: Array<T>): Int {
var low = 0
var high = array.size - 1
while (low <= high) {
val mid = (low + high) / 2
val compareResult = key.compareTo(array[mid])
when {
compareResult < 0 -> high = mid - 1
compareResult > 0 -> low = mid + 1
else -> return mid
}
}
return -1
}
/**
* 自定义比较规则进行二分查找,要求数组排序时也使用相同的比较规则
* 通常用不可比较对象中的某个可比较属性比较大小
* 例如对于不同学生,用学号作为比较方式,学生可以不实现Comparable接口,学号可以比较就行,属于委托
*/
fun <T, R : Comparable<R>> binarySearchBy(key: T, array: Array<T>, selector: (T) -> R?): Int {
return binarySearchWith(key, array, compareBy(selector))
}
/**
* 自定义比较规则进行二分查找,要求数组排序时也使用相同的比较规则
* 直接定义如何比较两个对象
*/
fun <T> binarySearchWith(key: T, array: Array<T>, comparator: Comparator<in T>): Int {
var low = 0
var high = array.size - 1
while (low <= high) {
val mid = (low + high) / 2
val compareResult = comparator.compare(key, array[mid])
when {
compareResult < 0 -> high = mid - 1
compareResult > 0 -> low = mid + 1
else -> return mid
}
}
return -1
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,843 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinTimeToVisitAllPoints.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.abs
/**
* Minimum Time Visiting All Points
* @see <a href="https://leetcode.com/problems/minimum-time-visiting-all-points">Source</a>
*/
fun interface MinTimeToVisitAllPoints {
operator fun invoke(points: Array<IntArray>): Int
}
class MinTimeToVisitAllPointsMoveDiagonally : MinTimeToVisitAllPoints {
override fun invoke(points: Array<IntArray>): Int {
var ans = 0
for (i in 1 until points.size) {
val prev = points[i - 1]
val cur = points[i]
ans += abs(cur[0] - prev[0]).coerceAtLeast(abs(cur[1] - prev[1]))
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,272 | kotlab | Apache License 2.0 |
algorithm/src/main/kotlin/com/seanshubin/condorcet/algorithm/CondorcetAlgorithm.kt | SeanShubin | 190,099,313 | false | null | package com.seanshubin.condorcet.algorithm
import com.seanshubin.condorcet.matrix.Matrix
import com.seanshubin.condorcet.matrix.Size
import com.seanshubin.condorcet.matrix.plus
import kotlin.math.max
import kotlin.math.min
object CondorcetAlgorithm {
fun tally(request: TallyElectionRequest): TallyElectionResponse {
val election = request.election
val candidates = request.candidates.sorted()
val eligibleVoters = request.eligibleVoters
val ballots = request.ballots.sortedWith(Ballot.sortByConfirmation)
val (voted, didNotVote) = voted(eligibleVoters, ballots)
val preferenceMatrix = computePreferenceMatrix(candidates, ballots)
val strongestPathMatrix = computeStrongestPaths(preferenceMatrix)
val winners = computeWinners(strongestPathMatrix)
val rankings = computePlacings(candidates, winners)
return TallyElectionResponse(
election,
candidates,
voted,
didNotVote,
rankings,
ballots,
preferenceMatrix.rows,
strongestPathMatrix.rows)
}
private fun voted(eligibleVoters: Set<String>, ballots: List<Ballot>): VotedAndDidNotVote {
fun ballotVoter(ballot: Ballot): String = ballot.voterName
val voted = ballots.map(::ballotVoter)
fun notVoted(voter: String): Boolean = !voted.contains(voter)
val didNotVote = eligibleVoters.filter(::notVoted)
return VotedAndDidNotVote(voted.sorted(), didNotVote.sorted())
}
private fun computePreferenceMatrix(candidates: List<String>, ballots: List<Ballot>): Matrix<Int> {
val lose = Int.MAX_VALUE
val size = Size(candidates.size, candidates.size)
val emptyMatrix = Matrix(size, 0)
fun addBallot(accumulator: Matrix<Int>, ballot: Ballot): Matrix<Int> {
fun computeValue(row: Int, col: Int): Int {
val winner = candidates[row]
val loser = candidates[col]
return if (ballot.rankings[winner] ?: lose < ballot.rankings[loser] ?: lose) 1 else 0
}
return accumulator + Matrix(size, ::computeValue)
}
return ballots.fold(emptyMatrix, ::addBallot)
}
private fun computeStrongestPaths(matrix: Matrix<Int>): Matrix<Int> {
val strongestPaths = matrix.mutableCopy()
val size = matrix.size.row
for (i in 0 until size) {
for (j in 0 until size) {
if (i != j) {
for (k in 0 until size) {
if (i != k && j != k) {
strongestPaths[j][k] =
max(strongestPaths[j][k], min(strongestPaths[j][i], strongestPaths[i][k]))
}
}
}
}
}
return Matrix(strongestPaths)
}
private fun computeWinners(strongestPaths: Matrix<Int>): List<List<Int>> {
val soFar = emptyList<List<Int>>()
val remain = (0 until strongestPaths.size.squareSize()).toList()
return computeWinners(strongestPaths, soFar, remain)
}
private fun computeWinners(strongestPaths: Matrix<Int>, soFar: List<List<Int>>, remain: List<Int>): List<List<Int>> {
if (remain.isEmpty()) return soFar
val winners = mutableListOf<Int>()
val newRemain = remain.toMutableList()
fun undefeated(target: Int): Boolean {
for (i in 0 until remain.size) {
val votesWon = strongestPaths[target, remain[i]]
val votesLost = strongestPaths[remain[i], target]
if (votesWon < votesLost) return false
}
return true
}
for (i in 0 until remain.size) {
if (undefeated(remain[i])) {
winners.add(remain[i])
newRemain.remove(remain[i])
}
}
return computeWinners(strongestPaths, soFar + listOf(winners), newRemain)
}
private fun computePlacings(candidates: List<String>, indicesPlaceList: List<List<Int>>): List<Placing> {
val placings = mutableListOf<Placing>()
var place = 1
for (indicesAtPlace in indicesPlaceList) {
val candidatesAtPlace = indicesAtPlace.map { candidates[it] }
placings.add(Placing(place, candidatesAtPlace))
place += indicesAtPlace.size
}
return placings
}
}
| 2 | Kotlin | 0 | 0 | 61219ae238b47792a5d347625f4963a1b2841d2d | 4,510 | condorcet5 | The Unlicense |
src/main/adventofcode/Day05Solver.kt | eduardofandrade | 317,942,586 | false | null | package adventofcode
import java.io.InputStream
import java.util.stream.Collectors
class Day05Solver(stream: InputStream) : Solver {
private val processedInput: List<Seat>
init {
processedInput = processInput(stream)
}
private fun processInput(stream: InputStream): List<Seat> {
return stream.bufferedReader().readLines().stream()
.map { code -> Seat(code) }
.collect(Collectors.toList())
}
override fun getPartOneSolution(): Long {
return processedInput.stream()
.map { seat -> seat.getSeatID() }
.max { o1, o2 -> o1.compareTo(o2) }
.orElse(0)
}
override fun getPartTwoSolution(): Long {
val listOfSeatIDs = processedInput.stream()
.map { seat -> seat.getSeatID() }
.sorted()
.collect(Collectors.toList())
for (i in 1 until listOfSeatIDs.size) {
if (listOfSeatIDs[i] - listOfSeatIDs[i - 1] == 2L) {
return listOfSeatIDs[i] - 1
}
}
return 0
}
private class Seat(val code: String) {
fun getSeatID(): Long {
return getRow().toLong() * 8 + getColumn().toLong()
}
private fun getRow(): Int {
var lower = 0
var upper = 127
for (i in 0..6) {
when {
code[i] == 'F' -> upper -= ((upper - lower + 1) / 2)
code[i] == 'B' -> lower += ((upper - lower + 1) / 2)
}
}
return upper// or lower, they are the same
}
private fun getColumn(): Int {
var lower = 0
var upper = 7
for (i in 7..9) {
when {
code[i] == 'L' -> upper -= ((upper - lower + 1) / 2)
code[i] == 'R' -> lower += ((upper - lower + 1) / 2)
}
}
return upper // or lower, they are the same
}
}
}
| 0 | Kotlin | 0 | 0 | 147553654412ae1da4b803328e9fc13700280c17 | 2,047 | adventofcode2020 | MIT License |
src/main/kotlin/Day02.kt | attilaTorok | 573,174,988 | false | {"Kotlin": 26454} | /**
* The shape what the opponent chooses.
*
* The value represents how much does the shape worth. The method score, calculates the points for the second part of
* the exercise.
*
* In part two, the second column says how the round needs to end: X means you need to lose, Y means you need to end the
* round in a draw, and Z means you need to win.
*/
enum class OpponentShape(val value: Int) {
A(1) {
override fun score(playerShape: PlayerShape): Int {
return when (playerShape.name) {
PlayerShape.X.name -> 3
PlayerShape.Y.name -> 4
PlayerShape.Z.name -> 8
else -> {
throw RuntimeException("Wrong value")
}
}
}
},
B(2) {
override fun score(playerShape: PlayerShape): Int {
return when (playerShape.name) {
PlayerShape.X.name -> 1
PlayerShape.Y.name -> 5
PlayerShape.Z.name -> 9
else -> {
throw RuntimeException("Wrong value")
}
}
}
},
C(3) {
override fun score(playerShape: PlayerShape): Int {
return when (playerShape.name) {
PlayerShape.X.name -> 2
PlayerShape.Y.name -> 6
PlayerShape.Z.name -> 7
else -> {
throw RuntimeException("Wrong value")
}
}
}
};
abstract fun score(playerShape: PlayerShape): Int
}
/**
* The shape what the player chooses.
*
* The value represents how much does the shape worth. The method score, calculates the points for the first part of
* the exercise.
*
* The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second
* column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. Your
* total score is the sum of your scores for each round. The score for a single round is the score for the shape you
* selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost,
* 3 if the round was a draw, and 6 if you won).
*/
enum class PlayerShape(val value: Int) {
X(1) {
override fun score(opponentShape: OpponentShape): Int {
return when (opponentShape.name) {
OpponentShape.A.name -> 4
OpponentShape.B.name -> 1
OpponentShape.C.name -> 7
else -> {
throw RuntimeException("Wrong value")
}
}
}
},
Y(2) {
override fun score(opponentShape: OpponentShape): Int {
return when (opponentShape.name) {
OpponentShape.A.name -> 8
OpponentShape.B.name -> 5
OpponentShape.C.name -> 2
else -> {
throw RuntimeException("Wrong value")
}
}
}
},
Z(3) {
override fun score(opponentShape: OpponentShape): Int {
return when (opponentShape.name) {
OpponentShape.A.name -> 3
OpponentShape.B.name -> 9
OpponentShape.C.name -> 6
else -> {
throw RuntimeException("Wrong value")
}
}
}
};
abstract fun score(opponentShape: OpponentShape): Int
}
fun main() {
fun calculateScore(fileName: String): Int {
var score = 0
readInputWithStream(fileName).useLines {
val iterator = it.iterator()
while (iterator.hasNext()) {
val split = iterator.next().split(" ")
score += PlayerShape.valueOf(split[1]).score(OpponentShape.valueOf(split[0]))
}
}
return score
}
fun calculateScorePart2(fileName: String): Int {
var score = 0
readInputWithStream(fileName).useLines {
val iterator = it.iterator()
while (iterator.hasNext()) {
val split = iterator.next().split(" ")
score += OpponentShape.valueOf(split[0]).score(PlayerShape.valueOf(split[1]))
}
}
return score
}
println("Test")
println("The score should be 15! Score: ${calculateScore("Day02_test")}")
println("The score should be 12! Score: ${calculateScorePart2("Day02_test")}")
println()
println("Exercise")
println("The score should be 13052! Score: ${calculateScore("Day02")}")
println("The score should be 13693! Score: ${calculateScorePart2("Day02")}")
} | 0 | Kotlin | 0 | 0 | 1799cf8c470d7f47f2fdd4b61a874adcc0de1e73 | 4,717 | AOC2022 | Apache License 2.0 |
src/main/java/challenges/cracking_coding_interview/sorting_and_searching/sparse_search/QuestionB.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.sorting_and_searching.sparse_search
object QuestionB {
fun searchI(strings: Array<String>, str: String?, first: Int, last: Int): Int {
var first = first
var last = last
while (first <= last) {
/* Move mid to the middle */
var mid = (last + first) / 2
/* If mid is empty, find closest non-empty string */if (strings[mid].isEmpty()) {
var left = mid - 1
var right = mid + 1
while (true) {
if (left < first && right > last) {
return -1
} else if (right <= last && !strings[right].isEmpty()) {
mid = right
break
} else if (left >= first && !strings[left].isEmpty()) {
mid = left
break
}
right++
left--
}
}
val res = strings[mid].compareTo(str!!)
if (res == 0) { // Found it!
return mid
} else if (res < 0) { // Search right
first = mid + 1
} else { // Search left
last = mid - 1
}
}
return -1
}
private fun searchR(strings: Array<String>, str: String, first: Int, last: Int): Int {
if (first > last) {
return -1
}
/* Move mid to the middle */
var mid = (last + first) / 2
/* If mid is empty, find closest non-empty string. */if (strings[mid].isEmpty()) {
var left = mid - 1
var right = mid + 1
while (true) {
if (left < first && right > last) {
return -1
} else if (right <= last && !strings[right].isEmpty()) {
mid = right
break
} else if (left >= first && !strings[left].isEmpty()) {
mid = left
break
}
right++
left--
}
}
/* Check for string, and recurse if necessary */return if (str == strings[mid]) { // Found it!
mid
} else if (strings[mid].compareTo(str) < 0) { // Search right
searchR(
strings,
str,
mid + 1,
last
)
} else { // Search left
searchR(
strings,
str,
first,
mid - 1
)
}
}
fun search(strings: Array<String>?, str: String?): Int {
return if (strings == null || str == null || str.isEmpty()) {
-1
} else searchR(
strings,
str,
0,
strings.size - 1
)
}
@JvmStatic
fun main(args: Array<String>) {
val stringList = arrayOf("apple", "", "", "banana", "", "", "", "carrot", "duck", "", "", "eel", "", "flower")
println(search(stringList, "ac"))
//for (String s : stringList) {
// String cloned = new String(s);
// println("<" + cloned + "> " + " appears at location " + search(stringList, cloned));
//}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 3,464 | CodingChallenges | Apache License 2.0 |
src/main/kotlin/pl/jpodeszwik/aoc2023/Day03.kt | jpodeszwik | 729,812,099 | false | {"Kotlin": 55101} | package pl.jpodeszwik.aoc2023
import java.lang.Long.parseLong
fun isAdjacentToNonDigit(lines: List<String>, line: Int, begin: Int, end: Int): Boolean {
val isSymbol: (Char) -> Boolean = { c -> c != '.' }
for (i in begin - 1..end + 1) {
if (line - 1 >= 0) {
if (i >= 0 && i <= lines[line].length - 1) {
if (isSymbol(lines[line - 1][i])) {
return true
}
}
}
if (line < lines.size - 1) {
if (i >= 0 && i <= lines[line].length - 1) {
if (isSymbol(lines[line + 1][i])) {
return true
}
}
}
}
if (begin > 0 && isSymbol(lines[line][begin - 1])) {
return true
}
if (end < lines[line].length - 1 && isSymbol(lines[line][end + 1])) {
return true
}
return false
}
private fun part1(lines: List<String>) {
var sum = 0L
var digitBegin = -1
for (i in lines.indices) {
if (digitBegin != -1) {
val number = parseLong(lines[i - 1].substring(digitBegin, lines[0].length))
if (isAdjacentToNonDigit(lines, i - 1, digitBegin, lines[0].length - 1)) {
sum += number
}
digitBegin = -1
}
for (j in lines[0].indices) {
if (lines[i][j].isDigit()) {
if (digitBegin == -1) {
digitBegin = j
}
} else {
if (digitBegin != -1) {
val number = parseLong(lines[i].substring(digitBegin, j))
if (isAdjacentToNonDigit(lines, i, digitBegin, j - 1)) {
sum += number
}
digitBegin = -1
}
}
}
}
if (digitBegin != -1) {
val number = parseLong(lines[lines.size - 1].substring(digitBegin, lines[lines.size - 1].length))
if (isAdjacentToNonDigit(lines, lines.size - 1, digitBegin, lines[0].length - 1)) {
sum += number
}
}
println(sum)
}
fun findAdjacentNumbers(lines: List<String>, row: Int, col: Int): List<Long> {
assert(lines[row][col] == '*')
val numbers = ArrayList<Long>()
if (col > 0 && lines[row][col - 1].isDigit()) {
numbers.add(parseNumber(lines, row, col - 1))
}
if (col < lines[row].length - 1 && lines[row][col + 1].isDigit()) {
numbers.add(parseNumber(lines, row, col + 1))
}
if (row > 0) {
numbers.addAll(findAdjacentRowNumbers(lines, row - 1, col))
}
if (row < lines.size - 1) {
numbers.addAll(findAdjacentRowNumbers(lines, row + 1, col))
}
return numbers
}
fun findAdjacentRowNumbers(lines: List<String>, row: Int, col: Int): List<Long> {
val line = lines[row]
if (line[col].isDigit()) {
return listOf(parseNumber(lines, row, col))
}
val numbers = ArrayList<Long>()
if (col > 0 && line[col - 1].isDigit()) {
numbers.add(parseNumber(lines, row, col - 1))
}
if (col < line.length - 1 && line[col + 1].isDigit()) {
numbers.add(parseNumber(lines, row, col + 1))
}
return numbers
}
fun parseNumber(lines: List<String>, row: Int, col: Int): Long {
val line = lines[row]
assert(line[col].isDigit())
var first = col
var last = col
while (first > 0 && line[first - 1].isDigit()) {
first--
}
while (last < line.length - 1 && line[last + 1].isDigit()) {
last++
}
return parseLong(line.substring(first, last + 1))
}
private fun part2(lines: List<String>) {
var sum = 0L
for (i in lines.indices) {
for (j in lines[0].indices) {
if (lines[i][j] == '*') {
val numbers = findAdjacentNumbers(lines, i, j)
if (numbers.size == 2) {
sum += numbers[0] * numbers[1]
}
}
}
}
println(sum)
}
fun main() {
val lines = loadFile("/aoc2023/input3")
part1(lines)
part2(lines)
}
| 0 | Kotlin | 0 | 0 | 2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63 | 4,079 | advent-of-code | MIT License |
src/test/java/quam/ComplexMatrixShould.kt | johnhearn | 149,781,062 | false | null | package quam
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class ComplexMatrixShould {
private val a = 1.0 + 2.0 * i
private val b = 3.0 + 4.0 * i
private val c = 5.0 + 6.0 * i
private val d = 7.0 + 8.0 * i
@Test
fun `build from integers`() {
val lhs = ComplexMatrix(2, 1, 1, 0, 0)
val expected = ComplexMatrix(2, 1.0, 1.0, 0.0, 0.0)
assertEquals(expected, lhs)
}
/**
* (a b) => (a c*)
* (c d) (b* d)
*/
@Test
fun `compute transpose`() {
val lhs = ComplexMatrix(2, a, b, c, d)
val expected = ComplexMatrix(2, a, c, b, d)
assertEquals(expected, lhs.transpose())
}
/**
* alpha*(a b)
* (c d)
*/
@Test
fun `compute product with scalar`() {
val rhs = ComplexMatrix(2, a, b, c, d)
val alpha = 1.5
val expected = ComplexMatrix(2, alpha * a, alpha * b, alpha * c, alpha * d)
assertEquals(expected, alpha * rhs)
}
/**
* (a b)(a)=(aa+bb)
* (c d)(b) (ca+db)
*/
@Test
fun `compute product with vector`() {
val matrix = ComplexMatrix(2, a, b, c, d)
val vector = ComplexVector(a, b)
val expected = ComplexVector(a * a + b * b, c * a + d * b)
assertEquals(expected, matrix * vector)
}
/**
* (a b)(a b)=(aa+bc ab+bd)
* (c d)(c d) (ca+dc cb+dd)
*/
@Test
fun `compute product with matrix`() {
val matrix1 = ComplexMatrix(2, a, b, c, d)
val matrix2 = ComplexMatrix(2, a, b, c, d)
val expected = ComplexMatrix(2, a * a + b * c, a * b + b * d, c * a + d * c, c * b + d * d)
assertEquals(expected, matrix1 * matrix2)
}
/**
* (a b)x(a c) = (aa ac ba bc)
* (c d) (b d) (ab ad bb bd)
* (ca cc da dc)
* (cb cd db dd)
*/
@Test
fun `compute tensor product`() {
val lhs = ComplexMatrix(2, a, b, c, d)
val rhs = ComplexMatrix(2, a, c, b, d)
val expected = ComplexMatrix(4,
a * a, a * c, b * a, b * c,
a * b, a * d, b * b, b * d,
c * a, c * c, d * a, d * c,
c * b, c * d, d * b, d * d)
val actual = lhs tensor rhs
assertEquals(expected, actual)
}
/**
* (a b)+(d c) = (a b 0 0)
* (c d) (b a) (c d 0 0)
* (0 0 d c)
* (0 0 b a)
*/
@Test
fun `compute direct sum`() {
val lhs = ComplexMatrix(2, a, b, c, d)
val rhs = ComplexMatrix(2, d, c, b, a)
val expected = ComplexMatrix(4,
a, b, ZERO, ZERO,
c, d, ZERO, ZERO,
ZERO, ZERO, d, c,
ZERO, ZERO, b, a)
val actual = lhs directSum rhs
assertEquals(expected, actual)
}
@Test
fun `have useful toString`() {
val a = 1.0 + Math.PI * i
val b = 3.0 + 4.0 * i
val c = 5.0 + 0.0 * i
val d = 7.0 + 8.0 * i
val matrix = ComplexMatrix(2, a, b, c, d)
assertEquals(
"1 + i3.142 | 3 + i4\n" +
"5 | 7 + i8", matrix.toString())
}
}
| 1 | Kotlin | 0 | 1 | 4215d86e7afad97b803ce850745920b63f75a0f9 | 3,225 | quko | MIT License |
Kotlin/Solucionando problemas em Kotlin/PrimoRapido.kt | Pleiterson | 328,727,089 | false | null | // Primo Rápido
/*
Mariazinha sabe que um Número Primo é aquele que pode ser dividido somente por
1 (um) e por ele mesmo. Por exemplo, o número 7 é primo, pois pode ser dividido
apenas pelo número 1 e pelo número 7 sem que haja resto. Então ela pediu para
você fazer um programa que aceite diversos valores e diga se cada um destes
valores é primo ou não. Acontece que a paciência não é uma das virtudes de
Mariazinha, portanto ela quer que a execução de todos os casos de teste que ela
selecionar (instâncias) aconteçam no tempo máximo de um segundo, pois ela odeia
esperar.
- Entrada
A primeira linha da entrada contém um inteiro N (1 ≤ N ≤ 200), correspondente
ao número de casos de teste. Seguem N linhas, cada uma contendo um valor
inteiro X (1 < X < 231) que pode ser ou não, um número primo.
- Saída
Para cada caso de teste imprima a mensagem “Prime” (Primo) ou “Not Prime” (Não
Primo), de acordo com o exemplo abaixo.
*/
import kotlin.math.sqrt
fun main(args: Array<String>) {
val n = readLine()!!.toInt()
for (i in 0 until n) {
val x = readLine()!!.toDouble()
val prime = isPrime(x)
print(prime)
}
}
fun print(prime: Boolean) {
if (prime) {
print("Prime\n")
} else print("Not Prime\n")
}
fun isPrime(num: Double): Boolean {
if (num < 2) return false
if (num % 2 == 0.0) return num == 2.0
val root = sqrt(num).toInt()
var i = 3
while (i <= root) {
if (num % i == 0.0) return false
i += 2
}
return true
} | 3 | Java | 73 | 274 | 003eda61f88702e68670262d6c656f47a3f318b6 | 1,563 | desafios-bootcamps-dio | MIT License |
app/src/main/kotlin/com/resurtm/aoc2023/day18/Part1.kt | resurtm | 726,078,755 | false | {"Kotlin": 119665} | package com.resurtm.aoc2023.day18
import kotlin.math.abs
fun solvePart1(moves: List<Move>): Int {
val minMax = findMinMax(moves)
val size = Pos(
abs(minMax.min.row) + abs(minMax.max.row) + 1,
abs(minMax.min.col) + abs(minMax.max.col) + 1
)
val delta = Pos(-minMax.min.row, -minMax.min.col)
val grid = Grid(buildGrid(size), delta)
fillGridBorders(moves, grid)
// printGrid(grid)
// println("Debug: ${countFilled(grid)}")
fillGridInside(grid)
// println("Debug: ${countFilled(grid)}")
return countFilled(grid)
}
private fun fillGridInside(g: Grid) {
val queue = ArrayDeque<Pos>()
queue.add(findStartPos(g))
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
val next = findNextPos(curr, g)
queue.addAll(next)
g.set(curr, '#')
next.forEach {
g.set(it, '#')
}
}
}
private fun findNextPos(pos: Pos, g: Grid): List<Pos> {
val result = mutableListOf<Pos>()
if (g.get(pos.row - 1, pos.col) != '#')
result.add(pos.copy(row = pos.row - 1))
if (g.get(pos.row + 1, pos.col) != '#')
result.add(pos.copy(row = pos.row + 1))
if (g.get(pos.row, pos.col - 1) != '#')
result.add(pos.copy(col = pos.col - 1))
if (g.get(pos.row, pos.col + 1) != '#')
result.add(pos.copy(col = pos.col + 1))
return result
}
private fun findStartPos(g: Grid): Pos {
var startPos = Pos()
startPosLoop@ for (row in g.minPos().row..g.maxPos().row) {
for (col in g.minPos().col..g.maxPos().col) {
if (g.get(row, col) == '#' && g.get(row + 1, col) == '#' && g.get(row, col + 1) == '#') {
startPos = Pos(row + 1, col + 1)
break@startPosLoop
}
}
}
return startPos
}
private fun countFilled(grid: Grid): Int {
var count = 0
for (row in grid.grid.indices) {
for (col in grid.grid[row].indices) {
if (grid.grid[row][col] == '#') count++
}
}
return count
}
private fun fillGridBorders(moves: List<Move>, grid: Grid) {
var curr = Pos()
for (move in moves) {
val nextPos = getNextPos(curr, move)
if (nextPos.row == curr.row) {
if (nextPos.col > curr.col) {
for (col in curr.col..nextPos.col) grid.set(curr.row, col, '#')
} else if (nextPos.col < curr.col) {
for (col in nextPos.col..curr.col) grid.set(curr.row, col, '#')
} else throw Exception("Invalid state, zero step moves are not supported")
} else if (nextPos.col == curr.col) {
if (nextPos.row > curr.row) {
for (row in curr.row..nextPos.row) grid.set(row, curr.col, '#')
} else if (nextPos.row < curr.row) {
for (row in nextPos.row..curr.row) grid.set(row, curr.col, '#')
} else throw Exception("Invalid state, zero step moves are not supported")
} else throw Exception("Invalid state, diagonal moves are not supported")
curr = nextPos
}
}
private fun buildGrid(size: Pos): GridData {
val grid: GridData = mutableListOf()
repeat(size.row.toInt()) {
val items = mutableListOf<Char>()
repeat(size.col.toInt()) { items.add('.') }
grid.add(items)
}
return grid
}
private fun findMinMax(moves: List<Move>): MinMax {
var curr = Pos()
var min = Pos()
var max = Pos()
for (move in moves) {
curr = getNextPos(curr, move)
if (curr.col < min.col) min = min.copy(col = curr.col)
if (curr.row < min.row) min = min.copy(row = curr.row)
if (curr.col > max.col) max = max.copy(col = curr.col)
if (curr.row > max.row) max = max.copy(row = curr.row)
}
return MinMax(min, max)
}
| 0 | Kotlin | 0 | 0 | fb8da6c246b0e2ffadb046401502f945a82cfed9 | 3,811 | advent-of-code-2023 | MIT License |
src/main/kotlin/com/jaspervanmerle/aoc2020/day/Day11.kt | jmerle | 317,518,472 | false | null | package com.jaspervanmerle.aoc2020.day
class Day11 : Day("2321", "2102") {
private val initialLayout = getInput()
.lines()
.map { it.toCharArray() }
.toTypedArray()
private val width = initialLayout[0].size
private val height = initialLayout.size
private val adjacentDirections = arrayOf(-1 to -1, 0 to -1, 1 to -1, -1 to 0, 1 to 0, -1 to 1, 0 to 1, 1 to 1)
override fun solvePartOne(): Any {
return countOccupiedSeatsAfterMutations(4) { layout, x, y ->
adjacentDirections.count {
val newX = x + it.first
val newY = y + it.second
newX in 0 until width && newY in 0 until height && layout[newY][newX] == '#'
}
}
}
override fun solvePartTwo(): Any {
return countOccupiedSeatsAfterMutations(5) { layout, x, y ->
adjacentDirections.count {
var newX = x + it.first
var newY = y + it.second
while (newX in 0 until width && newY in 0 until height) {
when (layout[newY][newX]) {
'#' -> return@count true
'L' -> return@count false
}
newX += it.first
newY += it.second
}
return@count false
}
}
}
private fun countOccupiedSeatsAfterMutations(
occupiedToEmptyThreshold: Int,
neighborCounter: (layout: Array<CharArray>, x: Int, y: Int) -> Int
): Int {
var currentLayout = duplicateLayout(initialLayout)
while (true) {
val newLayout = duplicateLayout(currentLayout)
var layoutChanged = false
for (y in 0 until height) {
for (x in 0 until width) {
if (currentLayout[y][x] == '.') {
continue
}
val occupiedNeighbors = neighborCounter(currentLayout, x, y)
if (currentLayout[y][x] == 'L') {
if (occupiedNeighbors == 0) {
newLayout[y][x] = '#'
layoutChanged = true
}
} else {
if (occupiedNeighbors >= occupiedToEmptyThreshold) {
newLayout[y][x] = 'L'
layoutChanged = true
}
}
}
}
if (!layoutChanged) {
break
}
currentLayout = newLayout
}
return currentLayout.sumBy { it.count { char -> char == '#' } }
}
private fun duplicateLayout(layout: Array<CharArray>): Array<CharArray> {
return layout.map { it.clone() }.toTypedArray()
}
}
| 0 | Kotlin | 0 | 0 | 81765a46df89533842162f3bfc90f25511b4913e | 2,880 | advent-of-code-2020 | MIT License |
kotlin/0304-range-sum-query-2d-immutable.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | class NumMatrix(matrix: Array<IntArray>) {
val row = matrix.size
val col = matrix[0].size
val prefixSum = Array(row + 1){ IntArray(col + 1) }
init {
for(i in 0 until row) {
var prefix = 0
for(j in 0 until col) {
println("i: $i j: $j")
prefix += matrix[i][j]
prefixSum[i + 1][j + 1] = prefix + prefixSum[i][j + 1]
}
}
}
fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int {
val r1 = row1 + 1
val r2 = row2 + 1
val c1 = col1 + 1
val c2 = col2 + 1
val botRight = prefixSum[r2][c2]
val aboveOf = prefixSum[r1 - 1][c2]
val leftOf = prefixSum[r2][c1 - 1]
val topLeft = prefixSum[r1 - 1][c1 - 1]
return botRight - aboveOf - leftOf + topLeft
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* var obj = NumMatrix(matrix)
* var param_1 = obj.sumRegion(row1,col1,row2,col2)
*/
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,018 | leetcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/StoneGame3.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 kotlin.math.max
/**
* 1406. Stone Game III
* @see <a href="https://leetcode.com/problems/stone-game-iii/">Source</a>
*/
fun interface StoneGame3 {
operator fun invoke(stoneValue: IntArray): String
}
private const val ALICE = "Alice"
private const val BOB = "Bob"
private const val TIE = "Tie"
private const val NOT_COMPUTED = 1000000000
/**
* Approach 1: Bottom-Up Dynamic Programming
*/
class StoneGame3BottomUp : StoneGame3 {
override operator fun invoke(stoneValue: IntArray): String {
val n: Int = stoneValue.size
val dp = IntArray(n + 1)
for (i in n - 1 downTo 0) {
dp[i] = stoneValue[i] - dp[i + 1]
if (i + 2 <= n) {
dp[i] = max(dp[i], stoneValue[i] + stoneValue[i + 1] - dp[i + 2])
}
if (i + 3 <= n) {
dp[i] = max(dp[i], stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[i + 3])
}
}
if (dp[0] > 0) {
return ALICE
}
return if (dp[0] < 0) {
BOB
} else {
TIE
}
}
}
/**
* Approach 2: Top-Down Dynamic Programming (Memoization)
*/
class StoneGame3TopDown : StoneGame3 {
override operator fun invoke(stoneValue: IntArray): String {
val dif = f(stoneValue, stoneValue.size, 0)
if (dif > 0) {
return ALICE
}
return if (dif < 0) {
BOB
} else {
TIE
}
}
private fun f(stoneValue: IntArray, n: Int, i: Int): Int {
if (i == n) {
return 0
}
var result = stoneValue[i] - f(stoneValue, n, i + 1)
if (i + 2 <= n) {
result = max(
result,
stoneValue[i] + stoneValue[i + 1] - f(stoneValue, n, i + 2),
)
}
if (i + 3 <= n) {
result = max(
result,
stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - f(stoneValue, n, i + 3),
)
}
return result
}
}
class StoneGame3Optimized : StoneGame3 {
private lateinit var dp: IntArray
override operator fun invoke(stoneValue: IntArray): String {
val n: Int = stoneValue.size
dp = IntArray(n + 1)
for (i in 0 until n) {
dp[i] = NOT_COMPUTED
}
val dif = f(stoneValue, stoneValue.size, 0)
if (dif > 0) {
return ALICE
}
return if (dif < 0) {
BOB
} else {
TIE
}
}
private fun f(stoneValue: IntArray, n: Int, i: Int): Int {
if (i == n) {
return 0
}
if (dp[i] != NOT_COMPUTED) {
return dp[i]
}
dp[i] = stoneValue[i] - f(stoneValue, n, i + 1)
if (i + 2 <= n) {
dp[i] = max(
dp[i],
stoneValue[i] + stoneValue[i + 1] - f(stoneValue, n, i + 2),
)
}
if (i + 3 <= n) {
dp[i] = max(
dp[i],
stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - f(stoneValue, n, i + 3),
)
}
return dp[i]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,841 | kotlab | Apache License 2.0 |
src/main/java/com/squareup/tools/maven/resolution/MavenVersion.kt | square | 250,649,454 | false | null | /*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.tools.maven.resolution
import kotlin.math.min
const val LESS_THAN = -1
const val GREATER_THAN = 1
const val EQUAL = 0
/**
* Encapsulates the logic of maven version comparisons, notably enshrining the logic described
* [in this article](https://blog.soebes.de/blog/2017/02/04/apache-maven-how-version-comparison-works).
*/
class MavenVersion private constructor(
private val raw: String,
private val elements: List<String>,
val snapshot: Boolean = false
) : Comparable<MavenVersion> {
override fun toString() = raw
override fun equals(other: Any?) = other is MavenVersion && compareTo(other) == EQUAL
override fun hashCode() = 31 + raw.hashCode()
override fun compareTo(other: MavenVersion): Int {
if (raw == other.raw) return EQUAL // simple obvious case.
// loop through the next-to-last of the shortest.
val minLength = min(elements.size, other.elements.size)
for (i in 0..minLength - 2) {
elements[i].numberOrStringComparison(other.elements[i]).let {
cmp -> if (cmp != EQUAL) return cmp
}
}
// so far, all but the last element (of the shortest version) are equal.
// 1.3.5.2 vs. 1.3.6-RC1 or 1.3.5 vs. 1.3.05, should all make it here.
val a = VersionElement.from(
elements[minLength - 1],
elements.size == minLength)
val b = VersionElement.from(
other.elements[minLength - 1],
other.elements.size == minLength)
// test the last element
a.compareTo(b).let { comparison -> if (comparison != EQUAL) return comparison }
// so far, the equivalent elements all match. Now check to see if one has more elements
// (1.3.5 > 1.3)
return when {
elements.size > other.elements.size -> return GREATER_THAN // 1.3.5 > 1.3
elements.size < other.elements.size -> return LESS_THAN // 1.3 < 1.3.5
else -> EQUAL
}
}
companion object {
@JvmStatic fun from(raw: String) = with(raw.split(".")) {
MavenVersion(raw, this, this.last().endsWith("-SNAPSHOT"))
}
}
}
internal data class VersionElement(
val core: String,
val qualifier: String? = null,
val snapshot: Boolean = false
) : Comparable<VersionElement> {
override fun compareTo(other: VersionElement): Int {
var compare = core.numberOrStringComparison(other.core)
if (compare != 0) return compare
compare = when {
qualifier == null && other.qualifier != null -> GREATER_THAN // qualified version is lesser
qualifier != null && other.qualifier == null -> LESS_THAN // unqualified version is greater
else -> {
qualifier?.numberOrStringComparison(other.qualifier!!) ?: EQUAL
}
}
if (compare != 0) return compare
// qualifiers are equal or don't exist - versions are equal at this point. Checking snapshot
return when {
this.snapshot && !other.snapshot -> LESS_THAN // snapshot less than release
!this.snapshot && other.snapshot -> GREATER_THAN // release greater than snapshot
else -> EQUAL
}
}
companion object {
fun from(raw: String, terminal: Boolean): VersionElement {
require(!raw.contains(".")) { "Version elements may not contains '.' characters." }
return if (terminal) {
val noSnapshot = raw.removeSuffix("-SNAPSHOT")
val parts = noSnapshot.split("-", limit = 2)
VersionElement(
core = parts[0],
qualifier = if (parts.size == 2) parts[1] else null,
snapshot = raw.endsWith("-SNAPSHOT")
)
} else VersionElement(raw)
}
}
}
internal fun String.numberComparison(other: String): Int? {
val a = this.toIntOrNull()
val b = other.toIntOrNull()
return if (a != null && b != null) a.compareTo(b)
else null
}
internal fun String.numberOrStringComparison(other: String) =
numberComparison(other) ?: this.compareTo(other)
| 4 | Kotlin | 9 | 69 | 6f43ea77ea80602f663b54fce63c7a1bc1a5946f | 4,446 | maven-archeologist | Apache License 2.0 |
01-basics-of-oop/Final/main.kt | kodecocodes | 734,547,562 | false | {"Kotlin": 58443} | import java.util.UUID;
val lagos = Pair(6.465422, 3.406448)
val london = Pair(51.509865, -0.118092)
// Procedural programming function
// DONE: Add more inputs
fun computeTravelTime(from: Pair<Double, Double>,
to: Pair<Double, Double>,
averageSpeed: Double,
actualDistance: Double): Double {
// compute point-to-point distance
// assume some average driving speed?
return actualDistance/averageSpeed
}
// Object-oriented programming classes
open class TravelMode(private val mode: String, val averageSpeed: Double) {
val id = UUID.randomUUID().toString()
open fun actualDistance(from: Pair<Double, Double>, to: Pair<Double, Double>): Double {
// use relevant map info for each specific travel mode
throw IllegalArgumentException("Implement this method for ${mode}.")
}
fun computeTravelTime(from: Pair<Double, Double>, to: Pair<Double, Double>): Double {
return actualDistance(from, to)/averageSpeed
}
}
// DONE: Add Walking subclass
class Walking(mode: String, averageSpeed: Double): TravelMode(mode, averageSpeed) {
override fun actualDistance(from: Pair<Double, Double>, to: Pair<Double, Double>): Double {
// use map info about walking paths, low-traffic roads, hills
return 57.0
}
}
// DONE: Add Driving subclass
class Driving(mode: String, averageSpeed: Double): TravelMode(mode, averageSpeed) {
override fun actualDistance(from: Pair<Double, Double>, to: Pair<Double, Double>): Double {
// use map info about roads, tollways
return 57.0
}
// DONE: Over load computeTravelTime
fun computeTravelTime(from: Pair<Double, Double>,
to: Pair<Double, Double>,
traffic: Double,
parking: Double): Double {
return actualDistance(from, to)/averageSpeed * traffic + parking
}
}
fun main() {
//computeTravelTime()
// DONE: Instantiate TravelMode
val sammy = TravelMode(mode = "walking", averageSpeed = 4.5)
println(sammy.mode)
// sammy.actualDistance(Pair(12.4563, 32.2434), Pair(23.4424, 14.34413))
// DONE: Instantiate Walking
val tim = Walking(mode = "walking", averageSpeed = 6.0)
println(tim)
println(tim.actualDistance(from = Pair(12.4563, 32.2434), to = Pair(23.4424, 14.34413)))
println(tim.computeTravelTime(from = Pair(12.4563, 32.2434), to = Pair(23.4424, 14.34413)))
// DONE: Instantiate Driving
val car = Driving(mode = "driving", averageSpeed = 50.0)
println(car)
val hours = car.computeTravelTime(from = lagos, to = london)
println("Hours "+ hours)
val realHours = car.computeTravelTime(
from = lagos,
to = london,
traffic = 1.2,
parking = 0.5
)
println("Actual Hours: " + realHours)
}
| 0 | Kotlin | 0 | 0 | a0c5f2b61b3e5937d21a6f322ff8b19df3d89ada | 2,764 | m3-kioop-materials | Apache License 2.0 |
src/Day08.kt | olezhabobrov | 572,687,414 | false | {"Kotlin": 27363} | // Literally the most horrible code I've ever written
fun main() {
fun part1(input: List<String>): Int {
var counter = 0
val X = input[0].length
val Y = input.size
val field = Array(input.size, {index -> input[index].map { it.digitToInt() } })
field.forEachIndexed { y, xLine ->
xLine.forEachIndexed loop@{ x, height ->
if (x == 0 || x == X - 1 || y == 0 || y == Y - 1) {
counter++
return@loop
}
var dirs = 0
for (xid in 0 until x) {
if (field[y][xid] >= height) {
dirs++
break
}
}
for (xid in x + 1 until X) {
if (field[y][xid] >= height) {
dirs++
break
}
}
for (yid in 0 until y) {
if (field[yid][x] >= height) {
dirs++
break
}
}
for (yid in y + 1 until Y) {
if (field[yid][x] >= height) {
dirs++
break
}
}
if (dirs < 4)
counter++
}
}
return counter
}
fun part2(input: List<String>): Int {
var result = 0
val X = input[0].length
val Y = input.size
val field = Array(input.size, {index -> input[index].map { it.digitToInt() } })
field.forEachIndexed { y, xLine ->
xLine.forEachIndexed loop@{ x, height ->
if (x == 0 || x == X - 1 || y == 0 || y == Y - 1) {
return@loop
}
var current = 1
for (xid in x - 1 downTo -1) {
if (xid == -1) {
current *= x
break
}
if (field[y][xid] >= height) {
current *= (x - xid)
break
}
}
for (xid in x + 1 .. X) {
if (xid == X) {
current *= (X - x - 1)
break
}
if (field[y][xid] >= height) {
current *= (xid - x)
break
}
}
for (yid in y - 1 downTo -1) {
if (yid == -1) {
current *= y
break
}
if (field[yid][x] >= height) {
current *= (y - yid)
break
}
}
for (yid in y + 1 .. Y) {
if (yid == Y) {
current *= (Y - y - 1)
break
}
if (field[yid][x] >= height) {
current *= (yid - y)
break
}
}
result = maxOf(result, current)
}
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 31f2419230c42f72137c6cd2c9a627492313d8fb | 3,647 | AdventOfCode | Apache License 2.0 |
src/day20.kt | miiila | 725,271,087 | false | {"Kotlin": 77215} | import java.io.File
import kotlin.system.exitProcess
private const val DAY = 20
fun main() {
if (!File("./day${DAY}_input").exists()) {
downloadInput(DAY)
println("Input downloaded")
exitProcess(0)
}
val transformer = { x: String -> x }
val input = loadInput(DAY, false, transformer)
// println(input)
println(solvePart1(parseCables(input)))
solvePart2(parseCables(input))
}
// Part 1
private fun solvePart1(circuit: Circuit): Int {
var circuit = circuit
var pulses = mutableMapOf(0 to 0, 1 to 0)
for (i in (1..1000)) {
val (nc, np) = runPulse(circuit)
circuit = nc
pulses[0] = pulses[0]!! + np[0]!!
pulses[1] = pulses[1]!! + np[1]!!
}
return pulses[0]!! * pulses[1]!!
}
// Part 2
private fun solvePart2(circuit: Circuit) {
var circuit = circuit
var res = 0L
printGraph(circuit)
while (true) {
res++
val (nc, _) = runPulse(circuit, res)
circuit = nc
}
}
fun printGraph(circuit: Circuit) {
var mermaid = "flowchart TD\n"
val q = mutableListOf("broadcaster")
val done = mutableSetOf<String>()
while (q.isNotEmpty()) {
val k = q.removeFirst()
for (vv in circuit.routing[k]!!) {
if (vv in circuit.ffStates) {
mermaid += " $k --> $vv(($vv))\n"
} else if (vv in circuit.conjStates) {
mermaid += " $k --> $vv\n"
} else {
mermaid += " $k --> $vv\n"
}
if (vv in circuit.routing && vv !in done && vv !in q) {
q.add(vv)
}
}
done.add(k)
}
print(mermaid)
}
fun runPulse(circuit: Circuit, count: Long = 0): Pair<Circuit, Map<Int, Int>> {
val pulses = mutableMapOf(0 to 0, 1 to 0)
val q = mutableListOf(Triple("button", "broadcaster", 0))
while (q.isNotEmpty()) {
val (s, t, p) = q.removeFirst()
if (count > 0) {
if (s == "sl" && t == "bq" && p == 0) {
println("bq: $count")
}
if (s == "jz" && t == "vz" && p == 0) {
println("vz: $count")
}
if (s == "rr" && t == "lt" && p == 0) {
println("lt: $count")
}
if (s == "pq" && t == "qh" && p == 0) {
println("qh: $count")
}
}
pulses[p] = pulses[p]!! + 1
if (t in circuit.ffStates.keys) {
if (p == 1) {
continue
}
circuit.ffStates[t] = (circuit.ffStates[t]!! + 1) % 2
q.addAll(circuit.routing[t]!!.map { Triple(t, it, circuit.ffStates[t]!!) })
continue
}
if (t in circuit.conjStates.keys) {
circuit.conjStates[t]!![s] = p
val p = if (circuit.conjStates[t]!!.values.all { it == 1 }) 0 else 1
q.addAll(circuit.routing[t]!!.map { Triple(t, it, p) })
continue
}
if (t in circuit.routing.keys) {
q.addAll(circuit.routing[t]!!.map { Triple(t, it, p) })
}
}
return Pair(circuit, pulses)
}
data class Circuit(
val routing: Map<String, List<String>>,
val ffStates: MutableMap<String, Int>,
val conjStates: MutableMap<String, MutableMap<String, Int>>
)
fun parseCables(input: List<String>): Circuit {
val routing = mutableMapOf<String, List<String>>()
val ffStates = mutableMapOf<String, Int>()
val conjStates = mutableMapOf<String, MutableMap<String, Int>>()
for (line in input) {
val (source, targets) = line.split(" -> ").let { Pair(it[0], it[1]) }
when {
source.startsWith('%') -> ffStates[source.drop(1)] = 0
source.startsWith('&') -> conjStates[source.drop(1)] = mutableMapOf()
}
routing[if (source.startsWith('b')) source else source.drop(1)] = targets.split(", ")
}
for (conj in conjStates.keys) {
for ((s, t) in routing) {
if (conj in t) {
conjStates[conj]!![s] = 0
}
}
}
return Circuit(routing, ffStates, conjStates)
} | 0 | Kotlin | 0 | 1 | 1cd45c2ce0822e60982c2c71cb4d8c75e37364a1 | 4,161 | aoc2023 | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[61]旋转链表.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
//
//
//
// 示例 1:
//
//
//输入:head = [1,2,3,4,5], k = 2
//输出:[4,5,1,2,3]
//
//
// 示例 2:
//
//
//输入:head = [0,1,2], k = 4
//输出:[2,0,1]
//
//
//
//
// 提示:
//
//
// 链表中节点的数目在范围 [0, 500] 内
// -100 <= Node.val <= 100
// 0 <= k <= 2 * 109
//
// Related Topics 链表 双指针
// 👍 589 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun rotateRight(head: ListNode?, k: Int): ListNode? {
if(head == null || head.next == null || k == 0) return head
var curr = head
var len = 1
//遍历找到尾结点
while (curr!!.next !=null){
curr = curr.next
len++
}
//此时 curr 指向链表最后一个节点
//K刚好旋转等于长度余数为零
if(k%len == 0) return head
//有余数
curr.next = head
// 3. 找到倒数第 k 个节点的前驱节点
curr = head
for (index in 0 until len - (k % len) - 1) {
curr = curr!!.next
}
// 4. 断开 preK
val preK = curr
val kP = preK!!.next
preK.next = null
return kP
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,584 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/dev/kosmx/aoc23/cubes/Cubes.kt | KosmX | 726,056,762 | false | {"Kotlin": 32011} | package dev.kosmx.aoc23.cubes
import java.io.File
import kotlin.math.max
fun main() {
val games = File("cubes.txt").readLines().map { Game.of(it) }
println(games)
games.sumOf { game ->
val r = game.rounds.fold(Round()) { acc, round ->
Round(max(acc.red, round.red), max(acc.green, round.green), max(acc.blue, round.blue))
}
r.red * r.green * r.blue
}
.let { println(it) }
}
data class Round(val red: Int = 0, val green: Int = 0, val blue: Int = 0)
data class Game(
val gameId: Int,
val rounds: List<Round>,
) {
companion object {
private val linePattern = Regex("^Game (?<gameid>\\d+): (?<rounds>.+)\$")
private val redPattern = Regex("((?<num>\\d+) red)")
private val greenPattern = Regex("((?<num>\\d+) green)")
private val bluePattern = Regex("((?<num>\\d+) blue)")
fun of(line: String): Game {
val match = linePattern.find(line)!!
val gameId = match.groups["gameid"]!!.value.toInt()
val rounds = match.groups["rounds"]!!.value.split(";").map {
Round(
red = redPattern.find(it)?.groups?.get("num")?.value?.toInt() ?: 0,
green = greenPattern.find(it)?.groups?.get("num")?.value?.toInt() ?: 0,
blue = bluePattern.find(it)?.groups?.get("num")?.value?.toInt() ?: 0,
)
}
return Game(gameId, rounds)
}
}
}
| 0 | Kotlin | 0 | 0 | ad01ab8e9b8782d15928a7475bbbc5f69b2416c2 | 1,484 | advent-of-code23 | MIT License |
year2021/day08/part2/src/main/kotlin/com/curtislb/adventofcode/year2021/day08/part2/Year2021Day08Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
Through a little deduction, you should now be able to determine the remaining digits. Consider again
the first example above:
```
acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab |
cdfeb fcadb cdfeb cdbaf
```
After some careful analysis, the mapping between signal wires and segments only make sense in the
following configuration:
```
dddd
e a
e a
ffff
g b
g b
cccc
```
So, the unique signal patterns would correspond to the following digits:
- `acedgfb`: 8
- `cdfbe`: 5
- `gcdfa`: 2
- `fbcad`: 3
- `dab`: 7
- `cefabd`: 9
- `cdfgeb`: 6
- `eafb`: 4
- `cagedb`: 0
- `ab`: 1
Then, the four digits of the output value can be decoded:
- `cdfeb`: 5
- `fcadb`: 3
- `cdfeb`: 5
- `cdbaf`: 3
Therefore, the output value for this entry is 5353.
Following this same process for each entry in the second, larger example above, the output value of
each entry can be determined:
- `fdgacbe cefdb cefbgd gcbe`: 8394
- `fcgedb cgb dgebacf gc`: 9781
- `cg cg fdcagb cbg`: 1197
- `efabcd cedba gadfec cb`: 9361
- `gecf egdcabf bgf bfgea`: 4873
- `gebdcfa ecba ca fadegcb`: 8418
- `cefg dcbef fcge gbcadfe`: 4548
- `ed bcgafe cdgba cbgef`: 1625
- `gbdfcae bgc cg cgb`: 8717
- `fgae cfgab fg bagce`: 4315
Adding all of the output values in this larger example produces 61229.
For each entry, determine all of the wire/segment connections and decode the four-digit output
values. What do you get if you add up all of the output values?
*/
package com.curtislb.adventofcode.year2021.day08.part2
import com.curtislb.adventofcode.year2021.day08.display.SevenSegmentDisplay
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2021, day 8, part 2.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
var total = 0
inputPath.toFile().forEachLine { line ->
total += SevenSegmentDisplay(line).decodeOutput()
}
return total
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,058 | AdventOfCode | MIT License |
src/day06/Day06.kt | zoricbruno | 573,440,038 | false | {"Kotlin": 13739} | package day06
import readInput
fun findStartMarkerIndex(input: String, length: Int): Int {
val unique = HashSet<Char>()
var left = 0
var right = 0
while (right < input.length){
while (unique.contains(input[right])){
unique.remove(input[left])
left++
}
unique.add(input[right])
right++
if(unique.size == length)
return right
}
throw IllegalArgumentException("No such luck.")
}
fun part1(input: String): Int {
return findStartMarkerIndex(input, 4)
}
fun part2(input: String): Int {
return findStartMarkerIndex(input, 14)
}
fun main() {
val day = "Day06"
val test = "${day}_test"
val testInput = readInput(day, test).first()
val input = readInput(day, day).first()
val testFirst = part1(testInput)
println(testFirst)
check(testFirst == 7)
println(part1(input))
val testSecond = part2(testInput)
println(testSecond)
check(testSecond == 19)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16afa06aff0b6e988cbea8081885236e4b7e0555 | 1,025 | kotlin_aoc_2022 | Apache License 2.0 |
src/Day10.kt | flexable777 | 571,712,576 | false | {"Kotlin": 38005} | fun main() {
fun part1(input: List<String>): Int {
var x = 1
var totalSignalStrength = 0
var cycle = 1
input.forEach { instruction ->
if (instruction == "noop") {
// println("start of cycle $cycle, x = $x")
// println("no operation")
//check during
if (cycle in listOf(20, 60, 100, 140, 180, 220)) {
val signalStrength = cycle * x
// println("signalStrength during cycle $cycle: $signalStrength")
totalSignalStrength += signalStrength
}
// println("end of cycle $cycle, x = $x")
cycle++
} else {
// println("start of cycle $cycle, x = $x")
//check during
if (cycle in listOf(20, 60, 100, 140, 180, 220)) {
val signalStrength = cycle * x
// println("signalStrength during cycle $cycle: $signalStrength")
totalSignalStrength += signalStrength
}
//add instruction
val (action, amount) = instruction.split(" ")
// println("action: $action, amount: $amount")
val toAddInNextCycle = amount.toInt()
// println("end of cycle $cycle, x = $x")
cycle++
// println()
// println("start of cycle $cycle, x = $x")
//during
if (cycle in listOf(20, 60, 100, 140, 180, 220)) {
val signalStrength = cycle * x
// println("signalStrength during cycle $cycle: $signalStrength")
totalSignalStrength += signalStrength
}
//after
//perform previous cycles instructions
x += toAddInNextCycle
// println("end of cycle $cycle, x = $x")
cycle++
}
}
return totalSignalStrength
}
fun part2(input: List<String>): String {
val result = mutableListOf<Char>()
var x = 1
var cycle = 0
input.forEach { instruction ->
if (instruction == "noop") {
//check during
result += if (x == cycle || (x - 1) == cycle || (x + 1) == cycle) {
'#'
} else {
' '
}
cycle++
} else {
//check during
result += if (x == cycle || (x - 1) == cycle || (x + 1) == cycle) {
'#'
} else {
' '
}
//add instruction
val (action, amount) = instruction.split(" ")
val toAddInNextCycle = amount.toInt()
cycle++
//check during
result += if (x == cycle || (x - 1) == cycle || (x + 1) == cycle) {
'#'
} else {
' '
}
//after
//perform previous cycles instructions
x += toAddInNextCycle
cycle++
}
if (cycle == 40) {
cycle = 0
}
}
return result.chunked(40).map { line ->
line.joinToString("") { it.toString() }
}.joinToString("") { it + "\n" }
}
val testInput = readInputAsLines("Day10_test")
check(part1(testInput) == 13140)
// part2(testInput)
val input = readInputAsLines("Day10")
println("Part 1: " + part1(input))
println("Part 2:\n" + part2(input))
} | 0 | Kotlin | 0 | 0 | d9a739eb203c535a3d83bc5da1b6a6a90a0c7bd6 | 3,723 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/challenges/cracking_coding_interview/sorting_and_searching/introduction/MergeSort.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.sorting_and_searching.introduction
import challenges.util.AssortedMethods.printIntArray
import challenges.util.AssortedMethods.randomArray
object MergeSort {
private fun mergesort(array: IntArray) {
val helper = IntArray(array.size)
mergesort(array, helper, 0, array.size - 1)
}
private fun mergesort(
array: IntArray,
helper: IntArray,
low: Int, high: Int
) {
if (low >= high) return
val middle = low + (high - low) / 2
mergesort(array, helper, low, middle) // Sort left half
mergesort(array, helper, middle + 1, high) // Sort right half
merge(array, helper, low, middle, high) // Merge them
}
private fun merge(
array: IntArray,
helper: IntArray,
low: Int, middle: Int,
high: Int
) {
/* Copy both halves into a helper array */
for (i in low..high) {
helper[i] = array[i]
}
var helperLeft = low
var helperRight = middle + 1
var current = low
/* Iterate through helper array. Compare the left and right
* half, copying back the smaller element from the two halves
* into the original array.
* */
while (helperLeft <= middle && helperRight <= high) {
if (helper[helperLeft] <= helper[helperRight]) {
array[current] = helper[helperLeft]
helperLeft++
} else { // If right element is smaller than left element
array[current] = helper[helperRight]
helperRight++
}
current++
}
/* Copy the rest of the left side of the array into the
* target array
* */
val remaining = middle - helperLeft
for (i in 0..remaining) {
array[current + i] = helper[helperLeft + i]
}
}
@JvmStatic
fun main(args: Array<String>) {
val size = 8
val array = randomArray(size, 0, size - 1)
val validate = IntArray(size)
printIntArray(array)
for (i in 0 until size) {
validate[array[i]]++
}
mergesort(array)
for (i in 0 until size) {
validate[array[i]]--
}
printIntArray(array)
for (i in 0 until size) {
if (validate[i] != 0 || i < size - 1 && array[i] > array[i + 1]) {
println("ERROR")
}
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,528 | CodingChallenges | Apache License 2.0 |
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day09.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwenty
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.max
import fr.outadoc.aoc.scaffold.min
import fr.outadoc.aoc.scaffold.readDayInput
class Day09 : Day<Long> {
companion object {
const val PREAMBLE_LENGTH = 25
}
private val input = readDayInput()
.lineSequence()
.map { it.toLong() }
private fun checkSum(chunk: List<Long>): Boolean {
val n = chunk.first()
val rest = chunk.drop(1)
return rest.any { a ->
(rest - a).any { b ->
a + b == n
}
}
}
private tailrec fun findContiguousSum(chunk: List<Long>, n: Long): List<Long> {
var sum = 0L
var i = 0
while (sum < n && i < chunk.size) {
sum += chunk[i]
i++
}
return when (sum) {
// We've found a contiguous sum equal to n
n -> chunk.take(i)
else -> findContiguousSum(chunk.drop(1), n)
}
}
override fun step1(): Long {
return input
.toList()
// Reverse so that `windowed` takes the previous 25 instead of the next
.reversed()
// For every member, consider it and the previous 25 members
.windowed(size = PREAMBLE_LENGTH + 1, step = 1)
// Re-reverse so that we start at the beginning
.reversed()
.first { chunk -> !checkSum(chunk) }.first()
}
override fun step2(): Long {
val n = 22477624L
val interval = input
.filter { it < n }
.toList()
.reversed()
return findContiguousSum(interval, n).let { res ->
res.min() + res.max()
}
}
override val expectedStep1: Long = 22477624
override val expectedStep2: Long = 2980044
} | 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 1,866 | adventofcode | Apache License 2.0 |
archive/631/solve.kt | daniellionel01 | 435,306,139 | false | null | /*
=== #631 Constrained Permutations - Project Euler ===
Let $(p_1 p_2 \ldots p_k)$ denote the permutation of the set ${1, ..., k}$ that maps $p_i\mapsto i$. Define the length of the permutation to be $k$; note that the empty permutation $()$ has length zero.
Define an occurrence of a permutation $p=(p_1 p_2 \ldots p_k)$ in a permutation $P=(P_1 P_2 \ldots P_n)$ to be a sequence $1\leq t_1 < t_2 < \cdots < t_k \leq n$ such that $p_i < p_j$ if and only if $P_{t_i} < P_{t_j}$ for all $i,j \in \{1, ..., k\}$.
For example, $(1243)$ occurs twice in the permutation $(314625)$: once as the 1st, 3rd, 4th and 6th elements $(3\,\,46\,\,5)$, and once as the 2nd, 3rd, 4th and 6th elements $(\,\,146\,\,5)$.
Let $f(n, m)$ be the number of permutations $P$ of length at most $n$ such that there is no occurrence of the permutation $1243$ in $P$ and there are at most $m$ occurrences of the permutation $21$ in $P$.
For example, $f(2,0) = 3$, with the permutations $()$, $(1)$, $(1,2)$ but not $(2,1)$.
You are also given that $f(4, 5) = 32$ and $f(10, 25) = 294\,400$.
Find $f(10^{18}, 40)$ modulo $1\,000\,000\,007$.
Difficulty rating: 65%
*/
fun solve(x: Int): Int {
return x*2;
}
fun main() {
val a = solve(10);
println("solution: $a");
} | 0 | Kotlin | 0 | 1 | 1ad6a549a0a420ac04906cfa86d99d8c612056f6 | 1,246 | euler | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.