path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day2.kt | clechasseur | 568,233,589 | false | {"Kotlin": 242914} | package io.github.clechasseur.adventofcode.y2015
import io.github.clechasseur.adventofcode.y2015.data.Day2Data
object Day2 {
private val input = Day2Data.input
fun part1(): Int = input.lines().map { it.toPresent() }.sumOf { it.requiredPaper }
fun part2(): Int = input.lines().map { it.toPresent() }.sumOf { it.requiredRibbon }
private data class Present(val l: Int, val w: Int, val h: Int) {
val sides: List<Int>
get() = listOf(l * w, l * h, w * h)
val smallestSide: Int
get() = sides.min()
val requiredPaper: Int
get() = sides.sum() * 2 + smallestSide
val perimeters: List<Int>
get() = listOf(l * 2 + w * 2, l * 2 + h * 2, w * 2 + h * 2)
val smallestPerimeter: Int
get() = perimeters.min()
val volume: Int
get() = l * w * h
val requiredRibbon: Int
get() = smallestPerimeter + volume
}
private fun String.toPresent(): Present {
val (l, w, h) = split('x')
return Present(l.toInt(), w.toInt(), h.toInt())
}
}
| 0 | Kotlin | 0 | 0 | e5a83093156cd7cd4afa41c93967a5181fd6ab80 | 1,103 | adventofcode2015 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SymmetricTree.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 dev.shtanko.algorithms.extensions.isEven
import java.util.Stack
/**
* 101. Symmetric Tree
* @see <a href="https://leetcode.com/problems/symmetric-tree/">Source</a>
*/
fun interface SymmetricTree {
operator fun invoke(root: TreeNode?): Boolean
}
class SymmetricTreeRecursive : SymmetricTree {
override fun invoke(root: TreeNode?) = root.isSymmetricTree()
private fun TreeNode?.isSymmetricTree(): Boolean {
if (this == null) return true
return (left to right).isSymmetric()
}
private fun Pair<TreeNode?, TreeNode?>.isSymmetric(): Boolean {
if (first == null || second == null) {
return first == second
}
if (first?.value != second?.value) {
return false
}
return (first?.left to second?.right).isSymmetric() && (first?.right to second?.left).isSymmetric()
}
}
class SymmetricTreeIterative : SymmetricTree {
override fun invoke(root: TreeNode?): Boolean {
if (root == null) return true
val stack = Stack<TreeNode>()
var left: TreeNode
var right: TreeNode
if (root.left != null) {
if (root.right == null) {
return false
}
stack.push(root.left)
stack.push(root.right)
} else if (root.right != null) {
return false
}
while (stack.isNotEmpty()) {
if (stack.size.isEven.not()) {
return false
}
right = stack.pop()
left = stack.pop()
if (right.value != left.value) {
return false
}
if (left.left != null) {
if (right.right == null) {
return false
}
stack.push(left.left)
stack.push(right.right)
} else if (right.right != null) {
return false
}
if (left.right != null) {
if (right.left == null) {
return false
}
stack.push(left.right)
stack.push(right.left)
} else if (right.left != null) {
return false
}
}
return true
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,917 | kotlab | Apache License 2.0 |
src/kotlin2023/Day02.kt | egnbjork | 571,981,366 | false | {"Kotlin": 18156} | package kotlin2023
import readInput
import java.lang.IllegalStateException
fun main() {
val lines = readInput("kotlin2023/Day02_test")
println(minimumSet(lines))
}
fun minimumSet(input: List<String>): Int {
return input.sumOf {
val parsedLine = it.substring(it.indexOf(": ") + 1)
val gameSet = parsedLine.trim().split("; ")
minimumCubes(gameSet)
}
}
fun minimumCubes(set: List<String>): Int {
var maxBlue = 0
var maxRed = 0
var maxGreen = 0
for (gameCubes in set) {
val parsedGameCubes = gameCubes.split(", ")
for (cubes in parsedGameCubes) {
val cube = cubes.trim().split(" ")
val color = cube[1]
val count = cube[0].toInt()
when (color) {
"blue" -> if (count > maxBlue) maxBlue = count
"red" -> if (count > maxRed) maxRed = count
"green" -> if (count > maxGreen) maxGreen = count
else -> throw IllegalStateException("$color is not a proper color")
}
}
}
return maxBlue * maxRed * maxGreen
} | 0 | Kotlin | 0 | 0 | 1294afde171a64b1a2dfad2d30ff495d52f227f5 | 1,111 | advent-of-code-kotlin | Apache License 2.0 |
src/Day10.kt | dmstocking | 575,012,721 | false | {"Kotlin": 40350} | class Cpu {
private var tick = 0
private var x = 1
fun line() = StringBuilder("........................................")
var screen = listOf(line())
var data = listOf<Int>()
fun noop() = tick()
fun addx(i: Int) {
tick()
tick { x += i }
}
fun tick(action: () -> Unit = {}) {
val position = tick.mod(40)
val sprite = (x-1)..(x+1)
screen.last()[position] = if(position in sprite) '#' else '.'
tick += 1
if (tick.plus(20).mod(40) == 0) {
screen = screen + line()
data = data + (tick * x)
}
action()
}
}
fun main() {
fun part1(input: List<String>): Int {
val cpu = Cpu()
input.forEach {
val add = it.drop(5).toIntOrNull()
if (add == null) {
cpu.noop()
} else {
cpu.addx(add)
}
}
return cpu.data.reduce(Int::plus)
}
fun part2(input: List<String>): String {
val cpu = Cpu()
input.forEach {
val add = it.drop(5).toIntOrNull()
if (add == null) {
cpu.noop()
} else {
cpu.addx(add)
}
}
return cpu.screen.joinToString(separator = "\n") { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
println(part1(testInput))
check(part1(testInput) == 13140)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e49d9247340037e4e70f55b0c201b3a39edd0a0f | 1,594 | advent-of-code-kotlin-2022 | Apache License 2.0 |
kotlin/day01/sonarSweep.kt | aesdeef | 433,698,136 | false | {"Python": 118972, "Elm": 30537, "JavaScript": 6228, "Kotlin": 2090, "HTML": 244} | package day01
import java.io.File
fun main() {
val depths = parseInput()
val part1 = countIncreases(depths)
val slidingWindows = getSlidingWindows(depths)
val part2 = countIncreases(slidingWindows)
println(part1)
println(part2)
}
fun parseInput(): List<Int> {
return File("../../input/01.txt")
.readLines()
.map { it.toInt() }
}
fun countIncreases(measurements: List<Int>): Int {
return (measurements.dropLast(1) zip measurements.drop(1))
.count { it.first < it.second }
}
fun getSlidingWindows(depths: List<Int>): List<Int> {
return zipSum(
zipSum(
depths.dropLast(2),
depths.dropLast(1).drop(1)
),
depths.drop(2)
)
}
fun zipSum(first: List<Int>, second: List<Int>): List<Int> {
return (first zip second).map{ it.first + it.second }
}
| 0 | Python | 0 | 2 | 4561bcf12ac03d360f5b28c48ef80134f97613b9 | 859 | advent-of-code-2021 | MIT License |
src/Day15.kt | joshpierce | 573,265,121 | false | {"Kotlin": 46425} | import java.io.File
import kotlin.collections.fill
import java.math.BigInteger
// So... this returned a couple possible solutions for part 2, the first one that came out ended up being correct
// and it's 01:28a so I'm going to bed. Hopefully I'll find time tomorrow to come back to this to clean it up.
fun main() {
var validMin: Int = 0
var validMax: Int = 4000000
var rowCheck: Int = 2000000
var directions: List<String> = File("Day15.txt").readLines()
var sbpairs: MutableList<Pair<Pair<Int, Int>, Pair<Int, Int>>> = directions.map {
val parts = it.replace("Sensor at x=", "")
.replace(", y=", ",")
.replace(": closest beacon is at x=", ",")
.split(",")
Pair(Pair(parts[0].toInt(), parts[1].toInt()), Pair(parts[2].toInt(), parts[3].toInt()))
}.toMutableList()
// get all x and y values with the same euclidian distance to the beacon in a specified row
var points: MutableSet<Pair<Int, Int>> = mutableSetOf()
sbpairs.forEach {
var possPoints = getPoints(it.first, it.second, rowCheck)
var beacons = sbpairs.map { it.second }
possPoints.forEach {
if (!beacons.contains(it)) {
points.add(it)
}
}
}
println("Part 1 Answer: ${points.size}")
println()
var possPoints: MutableList<Pair<Int, Int>> = mutableListOf()
sbpairs.forEach {
//println("Getting Diamond For ${it.first.toString()} to ${it.second.toString()}")
possPoints.addAll(getDiamondOutsides(it.first, it.second))
}
// Don't run this for the large grid or you're going to have a bad time
// var innerPoints: MutableList<Pair<Int, Int>> = mutableListOf()
// sbpairs.forEach {
// innerPoints.addAll(getPoints(it.first, it.second, -1))
// }
// for (i in validMin..validMax) {
// for (j in validMin..validMax) {
// if (sbpairs.map { it.second }.contains(Pair(j, i))) {
// print("🟣")
// }
// else if (sbpairs.map { it.first }.contains(Pair(j, i))) {
// print("🟢")
// }
// else if (innerPoints.contains(Pair(j, i))) {
// print("⚫️")
// } else {
// print("🤪")
// }
// }
// println()
// }
// Sort the possible points by x and then y so that we can find duplicates
possPoints.sortWith(compareBy({ it.first }, { it.second }))
// Run through the list sequentially and tally up the duplicates
var dups: MutableList<Pair<Pair<Int, Int>, Int>> = mutableListOf()
var i: Int = 0
while (i <= possPoints.size - 1) {
if (possPoints[i].first >= validMin && possPoints[i].first <= validMax && possPoints[i].second >= validMin && possPoints[i].second <= validMax && i < possPoints.size - 1) {
if (possPoints[i] == possPoints[i+1]) {
var count = 1
while (possPoints[i] == possPoints[i+count]) {
count++
}
dups.add(Pair(possPoints[i], count))
i += (count - 1)
} else {
i++
}
} else {
i++
}
}
// Sort the duplicates by the number of duplicates to test the most likely locations first
dups.sortByDescending({ it.second })
// Get a map of our sensors and beacons and distances for testing
var beacons: List<SBPair> = sbpairs.map { SBPair(it.first, it.second, getDistance(it.first, it.second)) }
var distressLocation: Pair<Int, Int> = Pair(0, 0)
run dups@ {
dups.forEach { dup ->
//println("Testing For Distress Location @ ${dup.first.toString()} | ${dup.second} duplicates")
var isValid = true
beacons.forEach beacon@ { beacon ->
if (getDistance(dup.first, beacon.start) <= beacon.distance) {
isValid = false
return@beacon
}
}
if (isValid) {
//println("Found our distress location: ${dup.first.toString()}")
distressLocation = dup.first
return@dups
}
}
}
println("Part 2 Answer: | ${(BigInteger(distressLocation.first.toInt().toString()).multiply(BigInteger("4000000"))).plus(BigInteger(distressLocation.second.toInt().toString()))}")
}
class SBPair(start: Pair<Int, Int>, end: Pair<Int, Int>, distance: Int) {
var start: Pair<Int, Int> = start
var end: Pair<Int, Int> = end
var distance: Int = distance
}
enum class DiamondDirection {
DOWNLEFT, DOWNRIGHT, UPRIGHT, UPLEFT
}
fun getPointsAround(start: Pair<Int,Int>): MutableList<Pair<Int, Int>> {
val points: MutableList<Pair<Int, Int>> = mutableListOf()
points.add(Pair(start.first - 1, start.second))
points.add(Pair(start.first + 1, start.second))
points.add(Pair(start.first, start.second - 1))
points.add(Pair(start.first, start.second + 1))
return points
}
fun getDistance(start: Pair<Int, Int>, end: Pair<Int, Int>): Int {
val xDiff = start.first - end.first
val yDiff = start.second - end.second
return Math.abs(xDiff) + Math.abs(yDiff)
}
fun getDiamondOutsides(start: Pair<Int, Int>, end: Pair<Int, Int>): MutableList<Pair<Int, Int>> {
val points: MutableList<Pair<Int, Int>> = mutableListOf()
// Adding 1 to the distance to get the points just outside the diamond
val distance = getDistance(start, end) + 1
var iterator = Pair(0,distance)
do {
if (iterator.second != 0) points.add(Pair(start.first + iterator.first, start.second + iterator.second))
if (iterator.second != 0) points.add(Pair(start.first + iterator.first, start.second - iterator.second))
if (iterator.first != 0) points.add(Pair(start.first - iterator.first, start.second + iterator.second))
if (iterator.first != 0) points.add(Pair(start.first - iterator.first, start.second - iterator.second))
iterator = Pair(iterator.first + 1, iterator.second - 1)
} while (iterator.second != 0)
return points
}
fun getPoints(start: Pair<Int, Int>, end: Pair<Int, Int>, row: Int): List<Pair<Int, Int>> {
val points: MutableList<Pair<Int, Int>> = mutableListOf()
val distance = getDistance(start, end)
if (row != -1) {
for (i in (start.first-distance)..(start.first+distance)) {
var testXDiff = start.first - i
var testYDiff = start.second - row
if (Math.abs(testXDiff) + Math.abs(testYDiff) <= distance) {
points.add(Pair(i, row))
}
}
} else {
for (i in (start.first-distance)..(start.first+distance)) {
for (j in (start.second-distance)..(start.second+distance)) {
var testXDiff = start.first - i
var testYDiff = start.second - j
if (Math.abs(testXDiff) + Math.abs(testYDiff) <= distance) {
points.add(Pair(i, j))
}
}
}
}
return points
} | 0 | Kotlin | 0 | 1 | fd5414c3ab919913ed0cd961348c8644db0330f4 | 7,244 | advent-of-code-22 | Apache License 2.0 |
kotlin/524.Longest Word in Dictionary through Deleting(通过删除字母匹配到字典里最长单词).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
</p>
<p><b>Example 1:</b><br>
<pre>
<b>Input:</b>
s = "abpcplea", d = ["ale","apple","monkey","plea"]
<b>Output:</b>
"apple"
</pre>
</p>
</p>
<p><b>Example 2:</b><br>
<pre>
<b>Input:</b>
s = "abpcplea", d = ["a","b","c"]
<b>Output:</b>
"a"
</pre>
</p>
<p><b>Note:</b><br>
<ol>
<li>All the strings in the input will only contain lower-case letters.</li>
<li>The size of the dictionary won't exceed 1,000.</li>
<li>The length of all the strings in the input won't exceed 1,000.</li>
</ol>
</p><p>给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>
s = "abpcplea", d = ["ale","apple","monkey","plea"]
<strong>输出:</strong>
"apple"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>
s = "abpcplea", d = ["a","b","c"]
<strong>输出:</strong>
"a"
</pre>
<p><strong>说明:</strong></p>
<ol>
<li>所有输入的字符串只包含小写字母。</li>
<li>字典的大小不会超过 1000。</li>
<li>所有输入的字符串长度不会超过 1000。</li>
</ol>
<p>给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>
s = "abpcplea", d = ["ale","apple","monkey","plea"]
<strong>输出:</strong>
"apple"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>
s = "abpcplea", d = ["a","b","c"]
<strong>输出:</strong>
"a"
</pre>
<p><strong>说明:</strong></p>
<ol>
<li>所有输入的字符串只包含小写字母。</li>
<li>字典的大小不会超过 1000。</li>
<li>所有输入的字符串长度不会超过 1000。</li>
</ol>
**/
class Solution {
fun findLongestWord(s: String, d: List<String>): String {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 2,767 | leetcode | MIT License |
src/Day01.kt | BurgundyDev | 572,937,542 | false | {"Kotlin": 11050} | fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("../inputs/Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("../inputs/Day01")
println(part1(input))
println(part2(input))
}
fun groupElves(input: List<String>): MutableList<Int> {
var currentElf: Int = 0
val elves = mutableListOf<Int>()
for(line in input)
{
if(line.isNotEmpty())
{
currentElf += line.toInt()
}else
{
elves.add(currentElf)
currentElf = 0
}
}
elves.add(currentElf)
return elves
}
private fun part1(input: List<String>): Int {
val elves = groupElves(input)
return elves.max()
}
private fun part2(input: List<String>): Int {
val elves = groupElves(input)
elves.sort()
elves.reverse()
return elves.take(3).sum()
} | 0 | Kotlin | 0 | 0 | dd931604fa35f75599ef778fc3f0f8bc82b2fce0 | 949 | aoc2022-kotlin | Apache License 2.0 |
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/Utils.kt | jrhenderson1988 | 289,786,400 | false | {"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37} | package com.github.jrhenderson1988.adventofcode2019
import java.io.File
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
const val R90 = PI / 2
const val R360 = PI * 2
fun readFileAsString(name: String): String {
return File(name).readText()
}
fun readFileAsLines(name: String): List<String> {
return File(name).readLines()
}
fun manhattanDistance(a: Pair<Int, Int>, b: Pair<Int, Int>) = abs(a.first - b.first) + abs(a.second - b.second)
fun hcf(a: Int, b: Int): Int = if (b == 0) a else hcf(b, a % b)
fun lcm(a: Int, b: Int) = a / hcf(a, b) * b
fun hcf(a: Long, b: Long): Long = if (b == 0L) a else hcf(b, a % b)
fun lcm(a: Long, b: Long) = a / hcf(a, b) * b
fun delta(a: Pair<Int, Int>, b: Pair<Int, Int>): Pair<Int, Int> {
val deltaX = abs(a.first - b.first)
val deltaY = abs(a.second - b.second)
val hcf = hcf(deltaX, deltaY)
return Pair(
if (a.first == b.first) 0 else (deltaX / hcf) * (if (a.first > b.first) -1 else 1),
if (a.second == b.second) 0 else (deltaY / hcf) * (if (a.second > b.second) -1 else 1)
)
}
fun angle(a: Pair<Int, Int>, b: Pair<Int, Int>): Double {
val newA = Pair(a.first, a.second * -1)
val newB = Pair(b.first, b.second * -1)
val direction = Pair((newB.first - newA.first).toDouble(), (newB.second - newA.second).toDouble())
val angle = ((R360 - (atan2(direction.second, direction.first))) + R90) % R360
return angle * (180 / PI)
}
fun pointsBetween(a: Pair<Int, Int>, b: Pair<Int, Int>): Set<Pair<Int, Int>> {
val points = mutableSetOf<Pair<Int, Int>>()
val delta = delta(a, b)
val iterations = when {
delta.first != 0 -> (abs(a.first - b.first) / abs(delta.first)) - 1
delta.second != 0 -> (abs(a.second - b.second) / abs(delta.second)) - 1
else -> 0
}
var current = a
(0 until iterations).forEach { _ ->
current = Pair(current.first + delta.first, current.second + delta.second)
points.add(current)
}
return points.toSet()
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 2,029 | advent-of-code | Apache License 2.0 |
src/main/java/aoc_2019/Day02.kt | frenchfrie | 161,678,638 | false | {"Java": 64581, "Kotlin": 12191} | package aoc_2019
import org.slf4j.LoggerFactory
import java.util.function.Function
import java.util.stream.Collectors
import java.util.stream.Stream
class Day02 {
private val log = LoggerFactory.getLogger(javaClass)
fun solve(input: Stream<Int>, noun: Int? = null, verb: Int? = null): List<Int> {
val memory =
input.map(ReplaceValues(mapOf(Pair(1, noun), Pair(2, verb)))).collect(Collectors.toList()).toMutableList()
val program = Program(memory)
var failsafe = 0
while (failsafe < 100) {
val nextCommand = program.readNext()
if (nextCommand == 99) {
break
} else {
val command = commands[nextCommand]
if (command == null) {
log.info("No command for key {}.", nextCommand)
program.readNext()
} else {
command.execute(memory, program)
}
}
failsafe++
}
return memory
}
fun solve02(input: Stream<Int>) : Pair<Int, Int>{
val storedInput = input.collect(Collectors.toUnmodifiableList())
for (noun in 0..99) {
for (verb in 0..99) {
val result = solve(storedInput.stream(), noun, verb)[0]
if (result == 19690720) {
return Pair(noun, verb)
}
}
}
throw RuntimeException("Holy shit!")
}
private val commands = mapOf(Sum().toPair(), Multiplication().toPair())
private interface Command {
fun execute(memory : MutableList<Int>, program : Program)
fun toPair() : Pair<Int, Command>
}
private class Sum : Command {
private val log = LoggerFactory.getLogger(javaClass)
override fun execute(memory : MutableList<Int>, program : Program) {
log.info("Memory before sum: {}.", memory)
val firstVariable = program.readNext()
val secondVariable = program.readNext()
val storeLocation = program.readNext()
memory[storeLocation] = memory[firstVariable] + memory[secondVariable]
log.info("Summed element at {} and element at {} then stored it at {}. Memory: {}.", firstVariable, secondVariable, storeLocation, memory)
}
override fun toPair(): Pair<Int, Command> {
return Pair(1, this)
}
}
private class Multiplication : Command {
private val log = LoggerFactory.getLogger(javaClass)
override fun execute(memory : MutableList<Int>, program : Program) {
log.info("Memory before multiplication: {}.", memory)
val firstVariable = program.readNext()
val secondVariable = program.readNext()
val storeLocation = program.readNext()
memory[storeLocation] = memory[firstVariable] * memory[secondVariable]
log.info("Multiplied element at {} and element at {} then stored it at {}. Memory: {}.", firstVariable, secondVariable, storeLocation, memory)
}
override fun toPair(): Pair<Int, Command> {
return Pair(2, this)
}
}
private class Program (val memory : List<Int>){
var index = 0
fun readNext(): Int {
return memory[index++]
}
fun readAhead(): Int {
return memory[index]
}
}
private class ReplaceValues(val replacements: Map<Int, Int?>) : Function<Int, Int> {
var index = 0
override fun apply(t: Int): Int {
val replacement = replacements[index++]
if (replacement != null) {
return replacement
} else {
return t
}
}
}
}
| 2 | Java | 0 | 0 | b21c991277ce8ae76338620c7002699fb8279f75 | 3,789 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/wilerson/aoc/day5/Day05.kt | wilerson | 572,902,668 | false | {"Kotlin": 8272} | package dev.wilerson.aoc.day5
import dev.wilerson.aoc.utils.chunkedByPredicate
import dev.wilerson.aoc.utils.readInput
fun main() {
val input = readInput("day5input")
val (stacksWithNumbers, instructions) = input.chunkedByPredicate { it != "" }
val crateIndices = listOf(1, 5, 9, 13, 17, 21, 25, 29, 33)
val stacks = stacksWithNumbers.dropLast(1)
val movableStacks = MutableList<List<String>>(9) { emptyList() }
(0..8).forEach { i -> movableStacks[i] = stacks.mapNotNull { s(it, crateIndices[i]) }.filterNot { it.isBlank() } }
val r = Regex("""move (\d+) from (\d) to (\d)""")
instructions.forEach { instruction ->
val matchResult = r.matchEntire(instruction)
if (matchResult != null) {
val (howMany, from, to) = matchResult.groupValues.drop(1).map { it.toInt() }
val fromIndex = from - 1
val toIndex = to - 1
movableStacks[toIndex] = movableStacks[fromIndex].take(howMany) + movableStacks[toIndex]
movableStacks[fromIndex] = movableStacks[fromIndex].drop(howMany)
}
}
println(movableStacks.filterNot { it.isEmpty() }.joinToString(separator = "") { it.first() })
}
private fun s(it: String, startIndex: Int) =
if(startIndex < it.length) it.substring(startIndex, startIndex + 1) else null | 0 | Kotlin | 0 | 0 | d6121ef600783c18696211d43b62284f4700adeb | 1,324 | kotlin-aoc-2022 | Apache License 2.0 |
LeetCode/Medium/top-k-frequent-words/Solution.kt | GregoryHo | 254,657,102 | false | null | import java.util.PriorityQueue
class Solution {
fun topKFrequent(words: Array<String>, k: Int): List<String> {
val counts = HashMap<String, Int>()
for (word in words) {
counts[word] = counts.getOrDefault(word, 0) + 1
}
val priorityQueue = PriorityQueue<String>(Comparator { o1, o2 ->
if (counts[o1] == counts[o2]) {
o1.compareTo(o2)
} else {
counts[o2]!! - counts[o1]!!
}
})
for (key in counts.keys) {
priorityQueue.add(key)
}
val answer = mutableListOf<String>()
var i = 0
while (i < k) {
answer.add(priorityQueue.poll())
i++
}
return answer
}
}
fun main(args: Array<String>) {
val solution = Solution()
println(solution.topKFrequent(arrayOf("i", "love", "leetcode", "i", "love", "coding"), 2))
println(solution.topKFrequent(arrayOf("the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"), 4))
}
| 0 | Kotlin | 0 | 0 | 8f126ffdf75aa83a6d60689e0b6fcc966a173c70 | 942 | coding-fun | MIT License |
baparker/03/main.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File
import kotlin.collections.mutableListOf
fun getPowerConsumption() {
var countList = IntArray(12)
var lineCount = 0
File("input.txt").forEachLine {
for (index in it.indices) {
countList[index] += it[index].digitToInt()
}
lineCount++
}
var gammaRate = ""
var epsilonRate = ""
for (count in countList) {
if (count != 0 && lineCount / count <= 1) {
gammaRate = gammaRate.plus("1")
epsilonRate = epsilonRate.plus("0")
} else {
gammaRate = gammaRate.plus("0")
epsilonRate = epsilonRate.plus("1")
}
}
println(Integer.parseInt(epsilonRate, 2) * Integer.parseInt(gammaRate, 2))
}
fun greaterThanEqualTo(num1: Int, num2: Int): Boolean {
return num1 >= num2
}
fun lessThan(num1: Int, num2: Int): Boolean {
return num1 < num2
}
fun getRating(list: MutableList<MutableList<Int>>, compareFunc: (Int, Int) -> Boolean): Int {
var ratingList = list.toList()
for (column in list.indices) {
if (ratingList.size > 1) {
var zeroList: MutableList<MutableList<Int>> = mutableListOf()
var oneList: MutableList<MutableList<Int>> = mutableListOf()
for (row in ratingList.indices) {
val bit = ratingList.get(row).get(column)
if (bit == 0) {
zeroList.add(ratingList.get(row))
} else {
oneList.add(ratingList.get(row))
}
}
if (compareFunc(oneList.size, zeroList.size)) {
ratingList = oneList
} else {
ratingList = zeroList
}
}
}
return Integer.parseInt(ratingList.get(0).joinToString(""), 2)
}
fun getLifeSupportAndOxygenGenerator() {
var lineCount = 0
var dataList: MutableList<MutableList<Int>> = mutableListOf()
File("input.txt").forEachLine {
var lineList: MutableList<Int> = mutableListOf()
for (index in it.indices) {
val bit = it[index].digitToInt()
lineList.add(bit)
}
dataList.add(lineList)
lineCount++
}
var o2GenRating = getRating(dataList, ::greaterThanEqualTo)
var cO2ScrubberRating = getRating(dataList, ::lessThan)
println(o2GenRating * cO2ScrubberRating)
}
fun main() {
getPowerConsumption()
getLifeSupportAndOxygenGenerator()
}
| 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 2,451 | advent-of-code-2021 | MIT License |
src/main/kotlin/CollectionFunctions.kt | mustajab-ikram | 533,452,617 | false | {"Kotlin": 95245} | fun main() {
// #Remove Duplicate Strings
// There are many ways to remove duplicate strings from an array:
// Maintain the original order of items
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
println(devs.distinct()) // [Amit, Ali, Sumit, Himanshu]
// Maintain the original order of items
val devs2 = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
println(devs2.toSet()) // [Amit, Ali, Sumit, Himanshu]
// Maintain the original order of items
val devs3 = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
println(devs3.toMutableSet()) // [Amit, Ali, Sumit, Himanshu]
// DO NOT Maintain the original order of items
val devs4 = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
println(devs4.toHashSet()) // [Amit, Ali, Sumit, Himanshu]
// # Convert an array or list to a string
// You can convert an array or list into a string by using joinToString.For example, if you are having a list of cities(Delhi, Mumbai, Bangalore), then you can convert that list into a string such as "India is one the best countries for tourism. You can visit Delhi, Mumbai, Bangalore, etc, and enjoy your holidays". Here, Delhi, Mumbai, Bangalore are the list items which you were having.
val someKotlinCollectionFunctions = listOf(
"distinct", "map",
"isEmpty", "contains",
"filter", "first",
"last", "reduce",
"single", "joinToString"
)
val message = someKotlinCollectionFunctions.joinToString(
separator = ", ",
prefix = "Kotlin has many collection functions like: ",
postfix = "and they are awesome.",
limit = 3,
truncated = "etc "
)
println(message) // Kotlin has many collection functions like: distinct, map, isEmpty, etc and they are awesome.
// # Transform a collection into a single result
// If you want to transform a given collection into a single result, then you can use reduce function. For example, you can find the sum of all the elements present in a list:
val numList2 = listOf(1, 2, 3, 4, 5)
val result = numList2.reduce { result, item ->
result + item
}
println(result) // 15
// NOTE: If the list is empty, then it will throw a RuntimeException
// Find if all elements are satisfying a particular condition
// If you have an array or list of data elements and you want to find whether or not all the elements are satisfying a particular condition, then you can use “all” in Kotlin.
data class Users(val id: Int, val name: String, val isCricketLover: Boolean, val isFootballLover: Boolean)
val user1 = Users(id = 1, name = "Amit", isCricketLover = true, isFootballLover = true)
val user2 = Users(id = 2, name = "Ali", isCricketLover = true, isFootballLover = true)
val user3 = Users(id = 3, name = "Sumit", isCricketLover = true, isFootballLover = false)
val user4 = Users(id = 4, name = "Himanshu", isCricketLover = true, isFootballLover = false)
val users2 = arrayOf(user1, user2, user3, user4)
val allLoveCricket = users2.all { it.isCricketLover }
println(allLoveCricket) // true
val allLoveFootball = users2.all { it.isFootballLover }
println(allLoveFootball) // false
// Find a particular element based on a certain condition
// You can find a particular element from a list of elements that is satisfying a particular condition by using find and single in Kotlin . For example, out of a list of students, you can find the student having roll number 5.
// The find returns the first element matching the given condition or null if no such element was found.While single returns the single element matching the given condition or it will throw an exception if there are more than one matching element or no matching element in the list .
data class User3(val id: Int, val name: String)
val users3 = arrayOf(
User3(1, "Amit"),
User3(2, "Ali"),
User3(3, "Sumit"),
User3(4, "Himanshu")
)
val userWithId3 = users3.single { it.id == 3 }
println(userWithId3) // User(id=3, name=Sumit)
val userWithId1 = users3.find { it.id == 1 }
println(userWithId1) // User(id=1, name=Amit)
// Break your list into multiple sublists of smaller size
// There are many cases when you have a bigger list and you want to divide it into smaller parts and then perform some operation on those sublists.So, this can be easily achieved using the chunked function.
val numList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val chunkedLists = numList.chunked(3)
println(chunkedLists) // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
// Making copies of the array
// You can make copies of your existing array by using various functions such as :
// copyInto: This will replace the elements of one array into another array or it will throw an exception if the destination array can't hold the elements of the original array due to size constraints or the indexes are out of bounds.
val arrayOne = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val arrayTwo = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
arrayOne.copyInto(destination = arrayTwo, destinationOffset = 2, startIndex = 0, endIndex = 4)
arrayTwo.forEach { print("$it ") } // 11 12 1 2 3 4 17 18 19 20
// Similarly, there are other functions that can be used to copy the elements of an array. For example:
// copyOfRange(fromIndex, toIndex): Returns a new array which is a copy of the specified range of the original array.
// copyOf() or copyOf(newSize): Returns a new array which is a copy of the original array, resized to the given newSize, or if the newSize is not passed then the whole array will be copied.
// Changing type of collection to other
// Depending on the situation, you can change the type of collection. Here, either you can change the type of one collection to another type by making a new collection or by referring to the older one. For example:
// toIntArray, toBooleanArray, toLongArray, toShortArray, toByteArray, toDoubleArray, toList, toMap, toSet, toPair, etc can be used to change the type of one collection to another type.
var uIntArr = UIntArray(5) { 1U }
var intArr = uIntArr.toIntArray()
intArr[0] = 0
println(uIntArr.toList()) // [1, 1, 1, 1, 1]
println(intArr.toList()) // [0, 1, 1, 1, 1]
// Here, we are making a new collection and changes in the new collection will not be reflected in the older one. But, at the same time, you can change the type of collection by keeping the reference to the older one i.e. changes in one collection will automatically be reflected in the other. For this instead of to, we need to use as . For example:
// asIntArray, asLongArray, asShortArray, asByteArray, asList, etc.
var uIntArray = UIntArray(5) { 1U }
var intArray = uIntArray.asIntArray()
intArray[0] = 0
print(uIntArray.toList()) // [0, 1, 1, 1, 1]
print(intArray.toList()) // [0, 1, 1, 1, 1]
// Associating the data using some key
// If you are having a list of data and you want to associate the data with the help of some key present in your data element, then you can use associateBy.
data class Contact(val name: String, val phoneNumber: String)
val contactList = listOf(
Contact("Amit", "+9199XXXX1111"),
Contact("Ali", "+9199XXXX2222"),
Contact("Himanshu", "+9199XXXX3333"),
Contact("Sumit", "+9199XXXX4444")
)
//// val phoneNumberToContactMap = contactList.associateBy { it.phoneNumber }
// println(phoneNumberToContactMap)
//// Map with key: phoneNumber and value: Contact
//// {
//// +9199XXXX1111=Contact(name=Amit, phoneNumber=+9199XXXX1111),
//// +9199XXXX2222=Contact(name=Ali, phoneNumber=+9199XXXX2222),
//// +9199XXXX3333=Contact(name=Himanshu, phoneNumber=+9199XXXX3333),
//// +9199XXXX4444=Contact(name=Sumit, phoneNumber=+9199XXXX4444)
//// }
/*
In the above example, the key is phoneNumber and the value is Contact. If you don't want to have the whole Contact as the value, then you can simply pass the desired value like this:
val phoneNumberToContactMap = contactList.associateBy({ it.phoneNumber }, { it.name })
print(phoneNumberToContactMap)
*/
// Map with key: phoneNumber and value: name
// {
// +9199XXXX1111=Amit,
// +9199XXXX2222=Ali,
// +9199XXXX3333=Himanshu,
// +9199XXXX4444=Sumit}
// }
// Finding distinct elements in a collection
// We can use the distinct function to get the list of unique elements of a collection .
val list2 = listOf(1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
println(list2.distinct()) // [1, 2, 3, 4]
// Union of collections
// You can use the union function to get the unique elements of two collections . The order of the elements of both the collections will be preserved but the elements of the second collection will be added after the elements of the first collection .
val listx = listOf(1, 2, 3, 3, 4, 5, 6)
val listy = listOf(2, 2, 4, 5, 6, 7, 8)
println(listx.union(listy)) // [1, 2, 3, 4, 5, 6, 7, 8]
// Intersection of collections
// To get the elements that are common in two collections, you can use the intersect function which returns a set containing the common element of both collections.
val listxx = listOf(1, 2, 3, 3, 4, 5, 6)
val listyy = listOf(2, 2, 4, 5, 6, 7, 8)
println(listxx.intersect(listyy)) // [2, 4, 5, 6]
// Keep the specified elements only
// If in a collection, you want to keep the specified elements only then you can use retainAll function. Since this function will modify your list, so make sure that your list or array is mutable.
// retainAll will return true if any element is removed from the collection otherwise it will return false.
val listxxx = mutableListOf(1, 2, 3, 3, 4, 5, 6)
val listyyy = listOf(1, 2, 3, 3, 4, 5, 6)
val listzzz = listOf(1, 2, 3, 3, 4, 5, 7)
println(listxxx.retainAll(listyyy)) // false
println(listxxx.retainAll(listzzz)) // true
println(listxxx) // [1, 2, 3, 3, 4, 5]
// Similarly, you can use removeAll to remove all the elements of one collection that are present in another collection.
// Filter a collection based on some condition
// You can filter a collection based on certain conditions by using the filter.This returns a list containing elements that satisfy the given condition.
val list4 = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val filteredLst = list4.filter { it % 2 == 0 }
println(filteredLst) // [2, 4, 6, 8]
// Similarly, you can filter the collection based on the index of elements by using filterIndexed.
// If you want to store the filtered elements in some collection, then you can use the filterIndexedTo:
val list5 = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val filteredList = mutableListOf<Int>()
list4.filterIndexedTo(filteredList) { index, i -> list5[index] % 2 == 0 }
println(filteredList) // [2, 4, 6, 8]
// You can also find the elements that are instances of a specified type in a collection by using filterIsInstance.
val mixedList = listOf(1, 2, 3, "one", "two", 4, "three", "four", 5, 6, "five", 7)
val strList = mixedList.filterIsInstance<String>()
println(strList) // [one, two, three, four, five]
// Zip collections
// zip returns a list of pairs . The first element of the pair will be taken from the first collection and the second element of the pair will be taken from the second collection . The size of the returned list will be equal to the size of the shortest collection.
val listOne = listOf(1, 2, 3, 4, 5)
val listTwo = listOf("a", "b", "c", "d", "e", "f")
println(listOne zip listTwo) // [(1, a), (2, b), (3, c), (4, d), (5, e)]
// Zip with next in a collection
// zipWithNext return a list of pairs . The elements of the pair will be the adjacent elements of the collection .
val list5_1 = listOf(1, 2, 3, 4, 5)
println(list5_1.zipWithNext()) // [(1, 2), (2, 3), (3, 4), (4, 5)]
// Unzip a collection
// unzip returns a pair of lists . The first list is made from the first elements of each pair and the second list is made from the second element of each pair.
val list6 = listOf("Amit" to 8, "Ali" to 10, "Sumit" to 4, "Himanshu" to 2)
val (players, footballSkills) = list6.unzip()
println(players) // [Amit, Ali, Sumit, Himanshu]
println(footballSkills) // [8, 10, 4, 2]
// Split array into two parts based on some condition
// If you want to split your data into two parts based on some conditions like isFootballFan, then you can use partition.
data class User(val id: Int, val name: String, val isFootballLover: Boolean)
val users = listOf(
User(1, "Amit", true),
User(2, "Ali", true),
User(3, "Sumit", false),
User(4, "Himanshu", false)
)
val (footballLovers, nonFootballLovers) = users.partition { it.isFootballLover }
println(footballLovers) // [User(id=1, name=Amit, isFootballLover=true), User(id=2, name=Ali, isFootballLover=true)]
println(nonFootballLovers) // [User(id=3, name=Sumit, isFootballLover=false), User(id=4, name=Himanshu, isFootballLover=false)]
// Reverse a list
// You can reverse a list in Kotlin by using the reversed and asReversed function .
val list7 = listOf(1, 2, 3, 4, 5)
print(list7.reversed()) // [5, 4, 3, 2, 1]
print(list7.asReversed()) // [5, 4, 3, 2, 1]
/*
Both are giving the same output but these functions are different.The reversed () function can be applied on Array, List, and MutableList. It generates a new list that is the reverse of the original list.
But the asReversed() function can be applied on List and MutableList.It doesn 't generate a new list because, after reversal, the new elements are still referring to the old one. So any change in one of them will result in a change in the other one.
Similarly, there are other functions that can be used to reverse the elements such as reversedArray(), reverse().
*/
// Group elements of a collection based on some condition
// You can use groupBy () to group the elements of a collection based on certain conditions . For example, the below code will group the elements of the list based on the remainder when divided by 4 i.e. 4 groups will be there(when remainder = 0, 1, 2, and 3)
val list8 = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(list8.groupBy { it % 4 })
// {
// 1=[1, 5, 9],
// 2=[2, 6, 10],
// 3=[3, 7],
// 0=[4, 8]
// }
// Sort element of a collection
// You can sort the elements of a collection by using the sorted () function . This will return a sorted list.
val list = listOf(10, 4, 1, 3, 7, 2, 6)
println(list.sorted()) // [1, 2, 3, 4, 6, 7, 10]
// Similarly, there are other functions that can be used to sort the collection based on certain conditions. Some of these functions are sortedArray, sortedArrayWith, sortedBy, sortedByDescending, sortedArraydescending, sortedWith, etc.
} | 0 | Kotlin | 0 | 4 | f3293e91212e973945a96f6ae90f2c442acb9298 | 15,108 | Kotlin_Tutorial | MIT License |
2021/src/main/kotlin/de/skyrising/aoc2021/day23/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day23
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.ints.IntArrayList
import it.unimi.dsi.fastutil.ints.IntList
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
private const val DUMP_PATH = false
val test = TestInput("""
#############
#...........#
###B#C#B#D###
#A#D#C#A#
#########
""")
@PuzzleName("Amphipod")
fun PuzzleInput.part1() = solve(parseInput(lines), AmphipodLayout.SOLVED1)
fun PuzzleInput.part2(): Any {
val input = ArrayList(lines)
input.addAll(3, listOf(" #D#C#B#A#", " #D#B#A#C#"))
val layout = parseInput(input)
return solve(layout, AmphipodLayout.SOLVED2)
}
private fun solve(layout: AmphipodLayout, solved: AmphipodLayout): Int {
val reached = Object2IntOpenHashMap<AmphipodLayout>()
var minSolve = Int.MAX_VALUE
reached.defaultReturnValue(Int.MAX_VALUE)
reached[layout] = 0
val path = mutableMapOf<AmphipodLayout, AmphipodLayout>()
val untraversed = ArrayDeque<AmphipodLayout>()
untraversed.add(layout)
while (untraversed.isNotEmpty()) {
minSolve = solveStep(untraversed, reached, minSolve, path, solved)
}
if (DUMP_PATH) {
val pathList = mutableListOf(solved)
var l = path[solved]
while (l != null) {
pathList.add(0, l)
l = path[l]
}
var cost = 0
for (p in pathList) {
val c = reached.getInt(p)
println(c - cost)
cost = c
println(p)
}
}
return reached.getInt(solved)
}
private fun solveStep(
untraversed: ArrayDeque<AmphipodLayout>,
reached: Object2IntOpenHashMap<AmphipodLayout>,
minSolve: Int,
path: MutableMap<AmphipodLayout, AmphipodLayout>,
solved: AmphipodLayout
): Int {
val current = untraversed.removeFirst()
val cost = reached.getInt(current)
var minSolve1 = minSolve
current.forPossibleMoves { nextLayout, pathCost ->
val newCost = cost + pathCost
if (newCost >= minSolve1 || newCost >= reached.getInt(nextLayout)) return@forPossibleMoves
if (nextLayout == solved) {
minSolve1 = newCost
} else {
untraversed.add(nextLayout)
}
reached[nextLayout] = newCost
if (DUMP_PATH) path[nextLayout] = current
}
return minSolve1
}
private fun parseInput(input: List<String>): AmphipodLayout {
val data = CharArray(11 + (input.size - 3) * 4)
for (i in 0 until 11) data[i] = input[1][1 + i]
for (j in 0 until input.size - 3) {
for (i in 0 until 4) data[11 + 4 * j + i] = input[2 + j][3 + 2 * i]
}
return AmphipodLayout(data)
}
data class AmphipodLayout(val data: CharArray) {
private val hash = data.contentHashCode()
override fun equals(other: Any?) = this === other || (other is AmphipodLayout && hash == other.hash && data.contentEquals(other.data))
override fun hashCode() = hash
override fun toString(): String {
val sb = StringBuilder("#############\n#")
for (i in 0 until 11) sb.append(data[i])
sb.append("#\n###")
for (i in 11 until 15) sb.append(data[i]).append('#')
sb.append("##\n #")
for (i in 15 until data.size) {
sb.append(data[i]).append('#')
if ((i - 11) % 4 == 3) sb.append("\n #")
}
sb.append("########")
return sb.toString()
}
fun move(from: Int, to: Int): AmphipodLayout {
val newData = data.copyOf()
newData[to] = data[from]
newData[from] = '.'
return AmphipodLayout(newData)
}
// move to the bottom of the room if there is no foreign pod
inline fun collectMovesToRoom(from: Int, c: Char, targetRoom: Int, callback: (AmphipodLayout, Int) -> Unit): Boolean {
val data = this.data
var to = data.size - 4 + targetRoom
while (to >= 11) {
val present = data[to]
if (present != '.' && present != c) break
val cost = getCost(from, to)
if (cost != 0) {
callback(move(from, to), cost)
return true
}
to -= 4
}
return false
}
inline fun collectMovesToHallway(from: Int, callback: (AmphipodLayout, Int) -> Unit) {
if (from < 11) return
for (to in VALID_HALLWAY) {
val cost = getCost(from, to)
if (cost == 0) continue
callback(move(from, to), cost)
}
}
inline fun forPossibleMoves(callback: (AmphipodLayout, Int) -> Unit) {
val size = data.size
for (from in 0 until size) {
val c = data[from]
if (c == '.') continue
if (collectMovesToRoom(from, c, c - 'A', callback)) continue
collectMovesToHallway(from, callback)
}
}
fun getCost(from: Int, to: Int): Int {
val data = this.data
//if (data[from] == '.' || data[to] != '.') return 0
//if (to in 2..8 && to % 2 == 0) return 0
//if (to >= 15 && data[to - 4] != '.') return 0
//if (!isCorrectRoom(to, data[from])) return 0
val path = getPath(from, to)
for (i in path.indices) {
if (data[path.getInt(i)] != '.') return 0
}
return path.size * COST_MULTIPLIER[data[from] - 'A']
}
companion object {
val SOLVED1 = AmphipodLayout("...........ABCDABCD".toCharArray())
val SOLVED2 = AmphipodLayout("...........ABCDABCDABCDABCD".toCharArray())
private val COST_MULTIPLIER = intArrayOf(1, 10, 100, 1000)
val VALID_HALLWAY = intArrayOf(0, 1, 3, 5, 7, 9, 10)
private val PATHS = Array<IntList?>(27 * 27) { null }
private fun isCorrectRoom(room: Int, pod: Char): Boolean {
if (room < 11) return true
return (room - 11) % 4 == pod - 'A'
}
private fun getPositionInFront(pos: Int) = if (pos >= 11) 2 + 2 * ((pos - 11) % 4) else pos
private fun getPath(from: Int, to: Int): IntList {
val key = from * 27 + to
var path = PATHS[key]
if (path == null) {
path = computePath(from, to)
PATHS[key] = path
}
return path
}
private fun computePath(from: Int, to: Int): IntList {
val path = IntArrayList(12)
if (from == to) return path
var p = from
val via = getPositionInFront(to)
while (p >= 15) {
p -= 4
path.add(p)
}
if (p >= 11) {
p = 2 + 2 * ((p - 11) % 4)
path.add(p)
}
while (p > via) path.add(--p)
while (p < via) path.add(++p)
if (p == to) return path
p = 11 + (to - 11) % 4
path.add(p)
while (p < to) {
p += 4
path.add(p)
}
return path
}
}
} | 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 7,009 | aoc | MIT License |
src/medium/_36ValidSudoku.kt | ilinqh | 390,190,883 | false | {"Kotlin": 382147, "Java": 32712} | package medium
class _36ValidSudoku {
class HashMapSolution {
fun isValidSudoku(board: Array<CharArray>): Boolean {
val rows = Array(9) { HashMap<Int, Int>(9) }
val columns = Array(9) { HashMap<Int, Int>(9) }
val boxes = Array(9) { HashMap<Int, Int>(9) }
for (i in 0 until 9) {
for (j in 0 until 9) {
val c = board[i][j]
if (c != '.') {
val boxIndex = (i / 3) * 3 + (j / 3)
val num = c.digitToInt()
rows[i][num] = rows[i].getOrDefault(num, 0) + 1
columns[j][num] = columns[j].getOrDefault(num, 0) + 1
boxes[boxIndex][num] = boxes[boxIndex].getOrDefault(num, 0) + 1
if (rows[i][num]!! > 1 || columns[j][num]!! > 1 || boxes[boxIndex][num]!! > 1) {
return false
}
}
}
}
return true
}
}
class ArraySolution {
fun isValidSudoku(board: Array<CharArray>): Boolean {
val rows = Array(10) { BooleanArray(10) }
val columns = Array(10) { BooleanArray(10) }
val boxes = Array(10) { BooleanArray(10) }
for (i in 0 until 9) {
for (j in 0 until 9) {
val c = board[i][j]
if (c != '.') {
val boxIndex = (i / 3) * 3 + (j / 3)
val num = c - '0'
if (rows[i][num] || columns[j][num] || boxes[boxIndex][num]) {
return false
}
rows[i][num] = true
columns[j][num] = true
boxes[boxIndex][num] = true
}
}
}
return true
}
}
class Solution {
fun isValidSudoku(board: Array<CharArray>): Boolean {
val row = IntArray(10)
val col = IntArray(10)
val area = IntArray(10)
for (i in 0 until 9) {
for (j in 0 until 9) {
val ch = board[i][j]
if (ch != '.') {
val num = ch - '0'
val index = i / 3 * 3 + j / 3
if (((row[i] shr num) and 1) == 1 ||
((col[j] shr num) and 1) == 1 ||
((area[index] shr num) and 1) == 1
) {
return false
}
row[i] = row[i] or (1 shl num)
col[j] = col[j] or (1 shl num)
area[index] = area[index] or (1 shl num)
}
}
}
return true
}
}
} | 0 | Kotlin | 0 | 0 | 8d2060888123915d2ef2ade293e5b12c66fb3a3f | 2,958 | AlgorithmsProject | Apache License 2.0 |
kotlin.web.demo.server/examples/Kotlin Koans/Generics/Generic functions/Solution.kt | JetBrains | 3,602,279 | false | null | import java.util.*
<answer>fun <T, C: MutableCollection<T>> Collection<T>.partitionTo(first: C, second: C, predicate: (T) -> Boolean): Pair<C, C> {
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}</answer>
fun partitionWordsAndLines() {
val (words, lines) = listOf("a", "a b", "c", "d e").
partitionTo(ArrayList<String>(), ArrayList()) { s -> !s.contains(" ") }
words == listOf("a", "c")
lines == listOf("a b", "d e")
}
fun partitionLettersAndOtherSymbols() {
val (letters, other) = setOf('a', '%', 'r', '}').
partitionTo(HashSet<Char>(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z'}
letters == setOf('a', 'r')
other == setOf('%', '}')
}
| 14 | Kotlin | 75 | 169 | 74eb79018f3f6b8d023fa0ef1a4b853503fe97a5 | 836 | kotlin-web-demo | Apache License 2.0 |
solutions/aockt/y2023/Y2023D22.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.parse
import aockt.util.spacial.Area
import aockt.util.spacial.overlaps
import aockt.util.spacial3d.Point3D
import io.github.jadarma.aockt.core.Solution
object Y2023D22 : Solution {
/** A line of sand cubes, defined by the [start] and [end] coordinates. */
private data class SandBrick(val start: Point3D, val end: Point3D) {
init {
require(start.z <= end.z) { "Start and end given out of order." }
require(start.z >= 1) { "Sand brick collides with ground." }
val isHorizontal = start.z == end.z && (start.x == end.x || start.y == end.y)
val isVertical = start.x == end.x && start.y == end.y
require(isHorizontal || isVertical) { "The sand brick must be a straight line." }
}
/** The area this line occupies on a flat plane, which can cause collisions when falling. */
val fallingArea: Area = Area(
xRange = minOf(start.x, end.x)..maxOf(start.x, end.x),
yRange = minOf(start.y, end.y)..maxOf(start.y, end.y),
)
/** Returns the state of the sand brick if it were to fall until the [start] rests at the given [restHeight]. */
fun fallTo(restHeight: Long): SandBrick = SandBrick(
start = start.copy(z = restHeight),
end = end.copy(z = end.z - start.z + restHeight),
)
/** Checks if this and the [other] brick will stack on each other after falling to the ground. */
fun fallingAreaOverlaps(other: SandBrick): Boolean = fallingArea overlaps other.fallingArea
}
/** A physics simulator for magical sand brick. */
private class SandBrickSimulator(bricks: Iterable<SandBrick>) {
/** The resting position of all bricks. */
val settledBricks: List<SandBrick> =
bricks
.toMutableList()
.apply {
sortBy { it.start.z }
forEachIndexed { index, brick ->
this[index] = slice(0..<index)
.filter { brick.fallingAreaOverlaps(it) }
.maxOfOrNull { it.end.z + 1 }
.let { restHeight -> brick.fallTo(restHeight ?: 1L) }
}
}
.sortedBy { it.start.z }
/** A mapping from a brick to all bricks that it rests directly on top of. */
val supportedBy: Map<SandBrick, Set<SandBrick>>
/** Syntactical sugar for getting all bricks resting directly on top of this one. */
private val SandBrick.supportedBricks: Set<SandBrick> get() = supportedBy.getValue(this)
/** A mapping from a brick to all bricks that rest directly on top of it. */
val supporting: Map<SandBrick, Set<SandBrick>>
/** Syntactical sugar for getting all bricks that this brick rests directly on top of. */
private val SandBrick.standingOn: Set<SandBrick> get() = supporting.getValue(this)
init {
val supportedBy: Map<SandBrick, MutableSet<SandBrick>> = settledBricks.associateWith { mutableSetOf() }
val supporting: Map<SandBrick, MutableSet<SandBrick>> = settledBricks.associateWith { mutableSetOf() }
settledBricks.forEachIndexed { index, above ->
settledBricks.slice(0..<index).forEach { below ->
if (below.fallingAreaOverlaps(above) && above.start.z == below.end.z + 1) {
supportedBy.getValue(below).add(above)
supporting.getValue(above).add(below)
}
}
}
this.supportedBy = supportedBy
this.supporting = supporting
}
/**
* The bricks that do not contribute to the structural integrity of the sand formation.
* They can be disintegrated without causing other bricks to fall.
*/
val redundantBricks: Set<SandBrick> =
settledBricks
.filter { it.supportedBricks.all { supported -> supported.standingOn.count() >= 2 } }
.toSet()
/** Simulate disintegrating the [brick] and return all bricks which would fall as a result. */
fun fallingBricksIfDisintegrating(brick: SandBrick): Set<SandBrick> = buildSet {
require(brick in supporting) { "The brick $brick is not part of the simulation." }
val fallingBricks = this
brick.supportedBricks
.filter { supported -> supported.standingOn.size == 1 }
.let(fallingBricks::addAll)
val queue = ArrayDeque(elements = fallingBricks)
while (queue.isNotEmpty()) {
queue.removeFirst()
.supportedBricks
.minus(fallingBricks)
.filter { supportedByFalling -> fallingBricks.containsAll(supportedByFalling.standingOn) }
.onEach(fallingBricks::add)
.forEach(queue::add)
}
}
}
/** Parses the [input] and returns the list of [SandBrick]s. */
private fun parseInput(input: String): List<SandBrick> = parse {
input
.lineSequence()
.map { line -> line.replace('~', ',') }
.map { line -> line.split(',', limit = 6).map(String::toInt) }
.onEach { require(it.size == 6) }
.map {
SandBrick(
start = it.take(3).let { (x, y, z) -> Point3D(x, y, z) },
end = it.takeLast(3).let { (x, y, z) -> Point3D(x, y, z) },
)
}
.toList()
}
override fun partOne(input: String) = parseInput(input).let(::SandBrickSimulator).redundantBricks.count()
override fun partTwo(input: String) = parseInput(input).let(::SandBrickSimulator).run {
settledBricks
.map(::fallingBricksIfDisintegrating)
.sumOf { it.count() }
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 6,003 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/org/domnikl/algorithms/sorting/QuickSort.kt | domnikl | 231,452,742 | false | null | package org.domnikl.algorithms.sorting
fun <T : Comparable<T>> Array<T>.quickSort(): Array<T> {
return this.quickSort(0, this.size - 1)
}
private fun <T : Comparable<T>> Array<T>.quickSort(low: Int, high: Int): Array<T> {
if (low < high) {
val p = this.partition(low, high)
this.quickSort(low, p)
this.quickSort(p + 1, high)
}
return this
}
private fun <T : Comparable<T>> Array<T>.partition(low: Int, high: Int): Int {
val pivot = this[low]
var i = low - 1
var j = high + 1
while (true) {
do {
i++
} while (this[i] < pivot)
do {
j--
} while (this[j] > pivot)
if (i >= j) {
return j
}
this[i] = this[j].also { this[j] = this[i] }
}
}
| 5 | Kotlin | 3 | 13 | 3b2c191876e58415d8221e511e6151a8747d15dc | 794 | algorithms-and-data-structures | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem655/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem655
import com.hj.leetcode.kotlin.common.model.TreeNode
/**
* LeetCode page: [655. Print Binary Tree](https://leetcode.com/problems/print-binary-tree/);
*/
class Solution {
private val strOfEmptyCell = ""
/* Complexity:
* Time O(H * 2^H) and Space O(H * 2^H) where H is the height of root;
*/
fun printTree(root: TreeNode?): List<List<String>> {
val height = root.height()
val matrix = newMatrixContainer(height, strOfEmptyCell)
if (root != null) updateMatrix(matrix, root)
return matrix
}
private fun TreeNode?.height(): Int =
if (this == null) 0 else 1 + maxOf(left.height(), right.height())
private fun newMatrixContainer(treeHeight: Int, initialValue: String): List<MutableList<String>> {
val totalColumn = (1 shl treeHeight) - 1
return List(treeHeight) {
MutableList(totalColumn) { initialValue }
}
}
private fun updateMatrix(
matrix: List<MutableList<String>>,
node: TreeNode,
rowOfNode: Int = 0,
columnOfNode: Int = matrix[0].lastIndex shr 1
) {
matrix[rowOfNode][columnOfNode] = node.`val`.toString()
val rowOfChild = rowOfNode + 1
node.left?.let {
val columnOfLeft = columnOfNode - (1 shl (matrix.lastIndex - rowOfChild))
updateMatrix(matrix, it, rowOfChild, columnOfLeft)
}
node.right?.let {
val columnOfRight = columnOfNode + (1 shl (matrix.lastIndex - rowOfChild))
updateMatrix(matrix, it, rowOfChild, columnOfRight)
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,639 | hj-leetcode-kotlin | Apache License 2.0 |
2021/src/main/kotlin/org/suggs/adventofcode/Day10SyntaxScoring.kt | suggitpe | 321,028,552 | false | {"Kotlin": 156836} | package org.suggs.adventofcode
import org.slf4j.LoggerFactory
object Day10SyntaxScoring {
private val log = LoggerFactory.getLogger(this::class.java)
private val charMap: Map<Char, Char> = mapOf('{' to '}', '<' to '>', '[' to ']', '(' to ')')
private val valueMap: Map<Char, Int> = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137)
private val closeValueMap: Map<Char, Int> = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4)
fun calculateScoreOfRemainder(dataSet: List<String>): Long {
val foo = dataSet.asSequence().map { removeNestedPairs(it) }.filter { isValid(it) }.map { createClosingSyntaxFrom(it) }.map { calculateValueOf(it) }.map { it }.sorted().toList()
return foo[foo.size / 2]
}
private fun calculateValueOf(switchedSyntax: String): Long {
fun calculateValueOf(switchedSyntax: CharArray, aggregate: Long): Long {
return when {
switchedSyntax.isEmpty() -> aggregate
else -> calculateValueOf(switchedSyntax.drop(1).toCharArray(), (aggregate * 5) + closeValueMap[switchedSyntax.first()]!!)
}
}
return calculateValueOf(switchedSyntax.toCharArray(), 0L)
}
private fun createClosingSyntaxFrom(remainder: String): String =
remainder.reversed().map { charMap[it]!! }.joinToString("")
private fun isValid(syntax: String) =
syntax.filterNot { charMap.contains(it) }.isEmpty()
fun calculateSyntaxScoreFrom(dataSet: List<String>) =
dataSet.sumOf { calculateSyntaxScoreFrom(removeNestedPairs(it)) }
private fun calculateSyntaxScoreFrom(pairlessSyntax: String): Int {
val remainder = pairlessSyntax.filterNot { charMap.contains(it) }
return when {
remainder.isEmpty() -> 0
else -> valueMap[remainder.first()]!!
}
}
private fun removeNestedPairs(original: String): String {
fun removePairsFrom(syntax: String) =
syntax.replace("<>", "").replace("()", "").replace("[]", "").replace("{}", "")
val cleaned = removePairsFrom(original)
return when (cleaned.length) {
original.length -> cleaned
else -> removeNestedPairs(cleaned)
}
}
} | 0 | Kotlin | 0 | 0 | 9485010cc0ca6e9dff447006d3414cf1709e279e | 2,237 | advent-of-code | Apache License 2.0 |
src/Day11.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | import java.util.concurrent.atomic.AtomicLong
class MonkeyRouter(rule: String, ifTrue: String, ifFalse: String) {
val divisible: Long
private val trueRoute: Int
private val falseRoute: Int
init {
divisible = rule.removePrefix(" Test: divisible by ").toLong()
trueRoute = ifTrue.removePrefix(" If true: throw to monkey ").toInt()
falseRoute = ifFalse.removePrefix(" If false: throw to monkey ").toInt()
}
fun route(old: Long): Int = if (old % divisible == 0L) trueRoute else falseRoute
}
data class InspectionResult(val worryLevel: Long, val thrown: Int)
class Monkey(startingItems: List<Long>, private val modification: Modification, val router: MonkeyRouter) {
private val items: MutableList<Long> = ArrayList(startingItems)
private var inspectionsMade = 0L
fun inspect(): Iterator<InspectionResult> = object : Iterator<InspectionResult> {
override fun hasNext(): Boolean = items.isNotEmpty()
override fun next(): InspectionResult {
inspectionsMade++
val worryLevel = modification.apply(items.removeFirst())
return InspectionResult(worryLevel, router.route(worryLevel))
}
}
fun inspections(): Long = inspectionsMade
fun catch(worryLevel: Long) = items.add(worryLevel)
override fun toString(): String {
return "Monkey: ${inspections()}"
}
}
fun interface Modification {
fun apply(x: Long): Long
}
fun interface Operand {
fun value(old: Long): Long
}
val Old = Operand { it }
private val Num: (Long) -> Operand = { value: Long -> Operand { _: Long -> value } }
class Plus(private val operand: Operand) : Modification {
override fun apply(x: Long): Long = x + operand.value(x)
}
class Minus(private val operand: Operand) : Modification {
override fun apply(x: Long): Long = x - operand.value(x)
}
class Mult(private val operand: Operand) : Modification {
override fun apply(x: Long): Long = x * operand.value(x)
}
class Divide(private val operand: Operand) : Modification {
override fun apply(x: Long): Long = x / operand.value(x)
}
fun main() {
fun parseMonkeys(
input: List<String>,
modificationDecorator: (Modification) -> Modification
): List<Monkey> {
val inputIterator = input.iterator()
val monkeys = mutableListOf<Monkey>()
while (inputIterator.hasNext()) {
inputIterator.next()
val startingItems = inputIterator.next().removePrefix(" Starting items: ").split(", ").map { it.toLong() }
val (operator, operand) = inputIterator.next().removePrefix(" Operation: new = old ").split(" ")
val parsedOperand = if (operand == "old") Old else Num(operand.toLong())
val operation = when (operator) {
"+" -> Plus(parsedOperand)
"-" -> Minus(parsedOperand)
"*" -> Mult(parsedOperand)
else -> Divide(parsedOperand)
}
val router = MonkeyRouter(inputIterator.next(), inputIterator.next(), inputIterator.next())
if (inputIterator.hasNext()) inputIterator.next()
monkeys.add(Monkey(startingItems, modificationDecorator(operation), router))
}
return monkeys
}
fun part1(input: List<String>): Long {
val monkeys = parseMonkeys(input) { mod -> Modification { value -> mod.apply(value) / 3 } }
for (i in 1..20) {
monkeys.forEach { monkey ->
monkey.inspect().forEach { (worryLevel, routed) ->
monkeys[routed].catch(worryLevel)
}
}
}
val sorted = monkeys.sortedByDescending { it.inspections() }
return sorted[0].inspections() * sorted[1].inspections()
}
fun part2(input: List<String>): Long {
val div = AtomicLong(1)
val monkeys = parseMonkeys(input) { Modification { value -> it.apply(value) % div.toLong() } }
monkeys.map { it.router.divisible }.reduceRight { v, acc -> v * acc }.also { div.set(it) }
for (i in 1..10_000) {
monkeys.forEach { monkey ->
monkey.inspect().forEach { (worryLevel, routed) ->
monkeys[routed].catch(worryLevel)
}
}
}
val sorted = monkeys.sortedByDescending { it.inspections() }
return sorted[0].inspections() * sorted[1].inspections()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
check(part1(input) == 67830L)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 4,784 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day10.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package days
import util.DAY_FILE
import util.DayInput
import util.GridCell
import util.Matrix
import java.util.*
class Day10 : Day("10") {
/*
| is a vertical pipe connecting north and south.
- is a horizontal pipe connecting east and west.
L is a 90-degree bend connecting north and east.
J is a 90-degree bend connecting north and west.
7 is a 90-degree bend connecting south and west.
F is a 90-degree bend connecting south and east.
. is ground; there is no pipe in this tile.
S is the starting position of the animal; there is a pipe on this tile, but your sketch doesn't show what shape the pipe has.
*/
enum class Item(val value: Char, val direction1: Direction?, val direction2: Direction?) {
VERTICAL('|', Direction.NORTH, Direction.SOUTH),
HORIZONTAL(
'-',
Direction.EAST,
Direction.WEST
),
NORTH_EAST('L', Direction.NORTH, Direction.EAST),
NORTH_WEST('J', Direction.NORTH, Direction.WEST),
SOUTH_WEST(
'7',
Direction.SOUTH,
Direction.WEST
),
SOUTH_EAST('F', Direction.SOUTH, Direction.EAST),
GROUND('.', null, null),
START('S', null, null);
fun directionFrom(direction: Direction): Direction? {
return when (direction) {
direction1 -> direction2
direction2 -> direction1
else -> null
}
}
companion object {
fun fromChar(char: Char): Item = entries.first { it.value == char }
}
}
enum class Direction() {
NORTH, SOUTH, EAST, WEST;
fun opposite(): Direction {
return when (this) {
NORTH -> SOUTH
SOUTH -> NORTH
EAST -> WEST
WEST -> EAST
}
}
fun right(): Direction {
return when (this) {
NORTH -> EAST
SOUTH -> WEST
EAST -> SOUTH
WEST -> NORTH
}
}
fun left(): Direction {
return right().opposite()
}
}
fun cellDirection(cell: GridCell<Item>, direction: Direction): Pair<Direction, GridCell<Item>> {
val gridCell = when (direction) {
Direction.NORTH -> cell.up()
Direction.SOUTH -> cell.down()
Direction.EAST -> cell.right()
Direction.WEST -> cell.left()
}
return direction to gridCell
}
override fun partOne(dayInput: DayInput): Any {
val map = dayInput.inputList().map {
it.toCharArray().map { Item.fromChar(it) }.toTypedArray()
}.toTypedArray()
val matrix = Matrix<Item>(map)
val startCell = matrix.find { it.value == Item.START }!!
val first = listOf(
cellDirection(startCell, Direction.NORTH),
cellDirection(startCell, Direction.SOUTH),
cellDirection(startCell, Direction.EAST),
cellDirection(startCell, Direction.WEST)
).filter { it.second.valid() }.filter { it.second.value != Item.GROUND }.first()
val goWithPath = goWithPath(first)
return (goWithPath.size / 2) + (goWithPath.size % 2)
}
fun goWithPath(start: Pair<Direction, GridCell<Item>>): MutableList<Pair<Direction, GridCell<Item>>> {
val result: MutableList<Pair<Direction, GridCell<Item>>> = mutableListOf()
var count = 0
var current = start
while (current.second.value != Item.START) {
count++
result.add(current)
val newDirection = current.second.value.directionFrom(current.first.opposite())!!
current = cellDirection(current.second, newDirection)
}
return result
}
fun straightCellDirections(cell: GridCell<Item>): List<Pair<Direction, GridCell<Item>>> {
return listOf(
cellDirection(cell, Direction.NORTH),
cellDirection(cell, Direction.SOUTH),
cellDirection(cell, Direction.EAST),
cellDirection(cell, Direction.WEST)
)
}
override fun partTwo(dayInput: DayInput): Any {
val map = dayInput.inputList().map {
it.toCharArray().map { Item.fromChar(it) }.toTypedArray()
}.toTypedArray()
val matrix = Matrix<Item>(map)
val startCell = matrix.find { it.value == Item.START }!!
val first =
straightCellDirections(startCell).filter { it.second.valid() }.filter { it.second.value != Item.GROUND }
.first()
val goWithPath = goWithPath(first)
val mainTiles = goWithPath + listOf(goWithPath.last().first to startCell)
val mainTilesSet = mainTiles.map { it.second }.toSet()
val startFrom = (matrix.lastRow() + matrix.firstRow() + matrix.lastColumn() + matrix.firstColumn()).filterNot {
mainTilesSet.contains(it)
}.distinct()
val visited =
visit(mainTilesSet, startFrom)
val right = true/*= mainTiles.map { it to straightCellDirections(it.second).find { pair -> visited.contains(pair.second) } }
.filter { it.second != null }.map { it.first.first.right() == it.second!!.first }.first()
*/
val hiddentAreas = mainTiles.filter { it.second.value!=Item.START }.flatMap {item->
val direction1 = item.second.value.directionFrom(item.first.opposite())!!
val direction2 = item.first
listOf(direction1, direction2)
.map {
if (right) it.right() else it.left()
}.map {
cellDirection(item.second, it)
}
}.filter { it.second.valid() }
.filterNot { visited.contains(it.second) }
.filterNot { mainTilesSet.contains(it.second) }
val hiddenValues = hiddentAreas.map { it.second }.distinct()
val gridCells = visit(mainTilesSet, hiddenValues) + visited
return matrix.count() - gridCells.size - mainTilesSet.size
}
fun visit(
mainTiles: Set<GridCell<Item>>, startFrom: List<GridCell<Item>>
): Set<GridCell<Item>> {
val visited: MutableSet<GridCell<Item>> = mutableSetOf()
val linkedList = LinkedList<GridCell<Item>>()
linkedList.addAll(startFrom)
while (linkedList.isNotEmpty()) {
val current = linkedList.removeFirst()
if (current.valid() && (visited.contains(current) || mainTiles.contains(current))) {
continue
}
visited.add(current)
linkedList.addAll(current.straightNeighbours())
}
return visited
}
}
fun main() {
println(Day10().partOne(DayInput(day = "10", DAY_FILE.INPUT)))
}
| 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 6,867 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/leetcode/Problem1402.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
import kotlin.math.max
/**
* https://leetcode.com/problems/reducing-dishes/
*/
class Problem1402 {
fun maxSatisfaction(satisfaction: IntArray): Int {
satisfaction.sort()
return maxSatisfaction(satisfaction, 0, 1, Array(satisfaction.size) {
IntArray(
satisfaction.size + 1
) { -1 }
})
}
private fun maxSatisfaction(satisfaction: IntArray, index: Int, time: Int, memo: Array<IntArray>): Int {
if (satisfaction.size == index) {
return 0
}
if (memo[index][time] != -1) {
return memo[index][time]
}
val m = max(
maxSatisfaction(satisfaction, index + 1, time, memo),
maxSatisfaction(satisfaction, index + 1, time + 1, memo) + satisfaction[index] * time)
memo[index][time] = m
return m
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 889 | leetcode | MIT License |
src/main/kotlin/days/Day13.kt | andilau | 726,429,411 | false | {"Kotlin": 37060} | package days
@AdventOfCodePuzzle(
name = "Point of Incidence",
url = "https://adventofcode.com/2023/day/13",
date = Date(day = 13, year = 2023)
)
class Day13(input: List<String>) : Puzzle {
private val patterns: List<List<String>> = extractPatterns(input)
override fun partOne(): Int =
patterns.sumOf { pattern -> 100 * pattern.verticalMirror() + pattern.horizontalMirror() }
override fun partTwo(): Int =
patterns.sumOf { pattern -> 100 * pattern.verticalMirror(1) + pattern.horizontalMirror(1) }
private fun extractPatterns(input: List<String>) =
input.fold(mutableListOf(mutableListOf<String>())) { acc, line ->
if (line.isBlank()) {
acc.add(mutableListOf())
} else {
acc.last().add(line)
}
acc
}
private fun List<String>.verticalMirror(difference: Int = 0): Int =
(1..lastIndex).firstNotNullOfOrNull { iy ->
val top = subList(0, iy)
val bottom = subList(iy, lastIndex + 1)
top.reversed().zip(bottom)
.sumOf { pair -> pair.first.indices.count { pair.first[it] != pair.second[it] } }
.let { if (it == difference) iy else null }
} ?: 0
private fun List<String>.horizontalMirror(difference: Int = 0): Int =
transpose().verticalMirror(difference)
private fun List<String>.transpose(): List<String> =
first().indices.map { x -> this.map { line -> line[x] }.joinToString("") }
} | 3 | Kotlin | 0 | 0 | 9a1f13a9815ab42d7fd1d9e6048085038d26da90 | 1,537 | advent-of-code-2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/org/example/adventofcode/puzzle/Day08.kt | nikos-ds | 573,046,617 | false | null | package org.example.adventofcode.puzzle
import org.example.adventofcode.util.FileLoader
import java.util.stream.IntStream
object Day08 {
private const val FILE_PATH = "/day-08-input.txt"
fun printSolution() {
println("- part 1: ${getResult(Day08::part1Calculator)}")
println("- part 2: ${getResult(Day08::part2Calculator)}")
}
private fun getResult(calculator: (Set<String>, List<List<Int>>) -> Int): Int {
val allLines = FileLoader.loadFromFile<String>(FILE_PATH).stream()
.map { it.toCharArray() }
.map { it -> it.map { it.digitToInt() } }
.toList()
val allColumns = IntStream.range(0, allLines[0].size)
.mapToObj { i -> allLines.stream().map { l -> l[i] }.toList() }
.toList()
val visibleInteriorTrees: Set<String> = getVisibleInteriorTrees(allLines, allColumns)
return calculator(visibleInteriorTrees, allLines)
}
private fun part1Calculator(
visibleInteriorTrees: Set<String>,
allLines: List<List<Int>>
) = visibleInteriorTrees.size + 2 * allLines[0].size + 2 * allLines.size - 4
private fun part2Calculator(
visibleInteriorTrees: Set<String>,
allLines: List<List<Int>>
): Int = visibleInteriorTrees.stream()
.map { treeCoords -> calculateVisibilityScore(treeCoords, allLines) }
.toList().max()
private fun calculateVisibilityScore(treeCoords: String, allLines: List<List<Int>>): Int {
val (x, y) = treeCoords.split(",").map { it.toInt() }
val currentTreeHeight = allLines[x][y]
var viewingDistanceLeft = 0
var viewingDistanceRight = 0
var viewingDistanceTop = 0
var viewingDistanceBottom = 0
for (i in y - 1 downTo 0) {
viewingDistanceLeft += 1
if (allLines[x][i] >= currentTreeHeight) {
break
}
}
for (i in y + 1 until allLines.size) {
viewingDistanceRight += 1
if (allLines[x][i] >= currentTreeHeight) {
break
}
}
for (i in x - 1 downTo 0) {
viewingDistanceTop += 1
if (allLines[i][y] >= currentTreeHeight) {
break
}
}
for (i in x + 1 until allLines[0].size) {
viewingDistanceBottom += 1
if (allLines[i][y] >= currentTreeHeight) {
break
}
}
return viewingDistanceLeft * viewingDistanceRight * viewingDistanceTop * viewingDistanceBottom
}
private fun getVisibleInteriorTrees(
allLines: MutableList<List<Int>>,
allColumns: MutableList<MutableList<Int>>
): Set<String> {
val maxRowIndex = allLines[0].size - 1
val maxColumnIndex = allLines.size - 1
val visibleInteriorTrees: MutableSet<String> = mutableSetOf()
for (x in 1 until maxColumnIndex) {
for (y in 1 until maxRowIndex) {
val currentRow = allLines[x]
val currentColumn = allColumns[y]
val currentTreeHeight = currentRow[y]
val maxHeightLeft = currentRow.subList(0, y).max()
val maxHeightRight = currentRow.subList(y + 1, currentRow.size).max()
val maxHeightTop = currentColumn.subList(0, x).max()
val maxHeightBottom = currentColumn.subList(x + 1, currentColumn.size).max()
val minimumHeightForVisibility =
listOf(maxHeightLeft, maxHeightRight, maxHeightTop, maxHeightBottom).min()
if (currentTreeHeight > minimumHeightForVisibility) {
visibleInteriorTrees.add("${x},${y}")
}
}
}
return visibleInteriorTrees
}
} | 0 | Kotlin | 0 | 0 | 3f97096ebcd19f971653762fe29ddec1e379d09a | 3,821 | advent-of-code-2022-kotlin | MIT License |
src/main/kotlin/ca/kiaira/advent2023/day15/Day15.kt | kiairatech | 728,913,965 | false | {"Kotlin": 78110} | package ca.kiaira.advent2023.day15
import ca.kiaira.advent2023.Puzzle
import java.util.*
/**
* Day15 is an object representing the puzzle for Advent of Code 2023, Day 15.
* It inherits from the [Puzzle] class with a generic type of [List]<[String]>.
*
* This object provides methods to parse the input, solve both parts of the puzzle,
* and calculate hash values for certain strings.
*
* @author <NAME> <<EMAIL>>
* @since December 15th, 2023
*/
object Day15 : Puzzle<List<String>>(15) {
/**
* Parses the input by joining lines, splitting by ',' and filtering out empty strings.
*
* @param input A sequence of strings representing the input data.
* @return A list of non-empty strings.
*/
override fun parse(input: Sequence<String>): List<String> {
return input.joinToString(separator = "").split(',').filter { it.isNotEmpty() }
}
/**
* Solves Part 1 of the puzzle.
*
* @param input A list of input strings.
* @return The sum of hash values of the input strings.
*/
override fun solvePart1(input: List<String>): Any {
val hashValues = input.map { calculateHash(it) }
return hashValues.sum()
}
/**
* Solves Part 2 of the puzzle.
*
* @param input A list of input strings.
* @return The sum of focusing powers calculated from lenses in boxes.
*/
override fun solvePart2(input: List<String>): Any {
val boxes = Array(256) { LinkedList<Lens>() }
for (command in input) {
if (command.endsWith('-')) {
val labelToRemove = command.dropLast(1)
val hashToRemove = calculateHash(labelToRemove)
boxes[hashToRemove].removeIf { it.label == labelToRemove }
} else {
val (label, focalString) = command.split('=')
val focalLength = focalString.toInt()
val hash = calculateHash(label)
val index = boxes[hash].indexOfFirst { it.label == label }
if (index == -1) {
boxes[hash].add(Lens(label, focalLength))
} else {
boxes[hash][index].focalLength = focalLength
}
}
}
val focusingPowers = boxes.flatMapIndexed { hash, box ->
box.mapIndexed { index, lens -> (hash + 1) * (index + 1) * lens.focalLength }
}
return focusingPowers.sum()
}
/**
* Calculates the hash value of a string.
*
* @param str The input string.
* @return The hash value as an integer.
*/
private fun calculateHash(str: String): Int {
var hash = 0
for (char in str) {
hash += char.toInt()
hash *= 17
hash %= 256
}
return hash
}
} | 0 | Kotlin | 0 | 1 | 27ec8fe5ddef65934ae5577bbc86353d3a52bf89 | 2,464 | kAdvent-2023 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumTilings.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
/**
* 790. Domino and Tromino Tiling
* @see <a href="https://leetcode.com/problems/domino-and-tromino-tiling/">Source</a>
*/
fun interface NumTilings {
operator fun invoke(n: Int): Int
}
class NumTilingsDP : NumTilings {
override operator fun invoke(n: Int): Int {
val dp = LongArray(n + 2)
dp[0] = 1; dp[1] = 2
val dpa = LongArray(n + 2)
dpa[1] = 1
for (i in 2 until n) {
dp[i] = (dp[i - 1] + dp[i - 2] + dpa[i - 1] * 2) % MOD
dpa[i] = (dp[i - 2] + dpa[i - 1]) % MOD
}
return dp[n - 1].toInt()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,272 | kotlab | Apache License 2.0 |
year2017/src/main/kotlin/net/olegg/aoc/year2017/day23/Day23.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2017.day23
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2017.DayOf2017
import java.math.BigInteger
/**
* See [Year 2017, Day 23](https://adventofcode.com/2017/day/23)
*/
object Day23 : DayOf2017(23) {
override fun first(): Any? {
val ops = lines.map { it.split(" ") }
var position = 0
val regs = mutableMapOf<String, BigInteger>()
var muls = 0
while (position in ops.indices) {
val op = ops[position]
when (op[0]) {
"set" -> regs[op[1]] = extract(regs, op[2])
"sub" -> regs[op[1]] = extract(regs, op[1]) - extract(regs, op[2])
"mul" -> {
regs[op[1]] = extract(regs, op[1]) * extract(regs, op[2])
muls += 1
}
"jnz" -> if (extract(regs, op[1]) != BigInteger.ZERO) position += (extract(regs, op[2]).toInt() - 1)
}
position += 1
}
return muls
}
override fun second(): Any? {
val ops = lines.map { it.split(" ") }
var position = 0
val regs = mutableMapOf("a" to BigInteger.ONE)
while (position in ops.indices) {
val op = ops[position]
when (op[0]) {
"set" -> regs[op[1]] = extract(regs, op[2])
"sub" -> regs[op[1]] = extract(regs, op[1]) - extract(regs, op[2])
"mul" -> regs[op[1]] = extract(regs, op[1]) * extract(regs, op[2])
"jnz" -> if (extract(regs, op[1]) != BigInteger.ZERO) position += (extract(regs, op[2]).toInt() - 1)
}
position += 1
}
return extract(regs, "h")
}
private fun extract(
map: Map<String, BigInteger>,
field: String
): BigInteger {
return field.toBigIntegerOrNull() ?: map.getOrDefault(field, BigInteger.ZERO)
}
}
fun main() = SomeDay.mainify(Day23)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,743 | adventofcode | MIT License |
src/Java/LeetcodeSolutions/src/main/java/leetcode/solutions/concrete/kotlin/Solution_66_Plus_One.kt | v43d3rm4k4r | 515,553,024 | false | {"Kotlin": 40113, "Java": 25728} | package leetcode.solutions.concrete.kotlin
import leetcode.solutions.*
import leetcode.solutions.ProblemDifficulty.*
import leetcode.solutions.validation.SolutionValidator.*
import leetcode.solutions.annotations.ProblemInputData
import leetcode.solutions.annotations.ProblemSolution
import kotlin.math.log10
/**
* __Problem:__ You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit
* of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large
* integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of
* digits.
*
* __Constraints:__
* - 1 <= digits.length <= 100
- 0 <= digits at _i_ <= 9
- digits does not contain any leading 0's.
* __Solution 1:__ This solution is based on converting an array to a number and vice versa. It does not look too elegant
* and is not the most effective.
*
* __Time:__ O(N)
*
* __Space:__ O(N)
*
* __Solution 2:__ Iteratively go through the array from lower to higher digits. If the current number is less than 9,
* just increment it and return an array. If the number is 9, then we reset the current digit and move on to the next
* iteration. If the array was not returned when exiting the loop, this means that all values are zeros, and you will
* have to add one to the beginning.
*
* __Time:__ O(N)
*
* __Space:__ O(N)
*
* @author <NAME>
*/
class Solution_66_Plus_One : LeetcodeSolution(EASY) {
@ProblemSolution(timeComplexity = "O(N)", spaceComplexity = "O(N)")
private fun plusOne1(digits: IntArray): IntArray {
var asInteger = 0
var digit = 1
for (i in digits.indices.reversed()) {
asInteger += digits[i] * digit
digit *= 10
}
++asInteger
val result = mutableListOf<Int>()
for (i in log10(asInteger.toFloat()).toInt() downTo 0) {
digit = asInteger % 10
result.add(0, digit)
asInteger /= 10
}
return result.toIntArray()
}
@ProblemSolution(timeComplexity = "O(N)", spaceComplexity = "O(N)")
private fun plusOne2(digits: IntArray): IntArray {
for (i in digits.indices.reversed()) {
if (digits[i] == 9) {
digits[i] = 0
continue;
}
++digits[i]
return digits
}
val tempList = digits.toMutableList() // don`t now why leetcode solutions templates takes static arrays ...
tempList.add(0, 1)
return tempList.toIntArray()
}
@ProblemInputData
override fun run() {
ASSERT_EQ(intArrayOf(1,2,4), plusOne1(intArrayOf(1,2,3)))
ASSERT_EQ(intArrayOf(4,3,2,2), plusOne1(intArrayOf(4,3,2,1)))
ASSERT_EQ(intArrayOf(1,0,0,0,0), plusOne1(intArrayOf(9,9,9,9)))
ASSERT_EQ(intArrayOf(1,2,4), plusOne2(intArrayOf(1,2,3)))
ASSERT_EQ(intArrayOf(4,3,2,2), plusOne2(intArrayOf(4,3,2,1)))
ASSERT_EQ(intArrayOf(1,0,0,0,0), plusOne2(intArrayOf(9,9,9,9)))
}
} | 0 | Kotlin | 0 | 1 | c5a7e389c943c85a90594315ff99e4aef87bff65 | 3,123 | LeetcodeSolutions | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2022/d18/Day18.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2022.d18
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.points.adjacents
import com.groundsfam.advent.timed
import com.groundsfam.advent.points.Point3 as Point
import kotlin.io.path.div
import kotlin.io.path.useLines
fun surfaceArea1(points: List<Point>): Int {
val prevPoints = mutableSetOf<Point>()
return points.fold(0) { area, point ->
if (point in prevPoints) area
else {
prevPoints.add(point)
area + 6 - 2 * (prevPoints intersect point.adjacents().toSet()).size
}
}
}
fun surfaceArea2(points: List<Point>): Int {
// bounds for the 3D rectangle to look within for air blocks touching the surface
// of the droplet
var (minX, minY, minZ) = points.first()
var (maxX, maxY, maxZ) = points.first()
val droplet = mutableSetOf<Point>()
points.forEach { point ->
droplet.add(point)
val (x, y, z) = point
if (x < minX) minX = x
if (y < minY) minY = y
if (z < minZ) minZ = z
if (x > maxX) maxX = x
if (y > maxY) maxY = y
if (z > maxZ) maxZ = z
}
minX--
minY--
minZ--
maxX++
maxY++
maxZ++
fun inBounds(point: Point): Boolean =
point.x in minX..maxX &&
point.y in minY..maxY &&
point.z in minZ..maxZ
val start = Point(minX, minY, minZ)
val queue = ArrayDeque(listOf(start))
val prevQueued = mutableSetOf(start)
var area = 0
while (queue.isNotEmpty()) {
val point = queue.removeFirst()
point.adjacents().forEach { adjPoint ->
if (adjPoint in droplet) {
area++
} else if (inBounds(adjPoint) && adjPoint !in prevQueued) {
queue.add(adjPoint)
prevQueued.add(adjPoint)
}
}
}
return area
}
fun main() = timed {
val points = (DATAPATH / "2022/day18.txt").useLines { lines ->
lines.toList().map { line ->
val (x, y, z) = line.split(",").map { it.toInt() }
Point(x, y, z)
}
}
println("Part one: ${surfaceArea1(points)}")
println("Part two: ${surfaceArea2(points)}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,215 | advent-of-code | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[77]组合.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.util.*
import kotlin.collections.ArrayList
//给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
//
// 你可以按 任何顺序 返回答案。
//
//
//
// 示例 1:
//
//
//输入:n = 4, k = 2
//输出:
//[
// [2,4],
// [3,4],
// [2,3],
// [1,2],
// [1,3],
// [1,4],
//]
//
// 示例 2:
//
//
//输入:n = 1, k = 1
//输出:[[1]]
//
//
//
// 提示:
//
//
// 1 <= n <= 20
// 1 <= k <= n
//
// Related Topics 数组 回溯
// 👍 652 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun combine(n: Int, k: Int): List<List<Int>> {
//递归 回溯
var res = ArrayList<ArrayList<Int>>()
dfs(1,n,k,LinkedList<Int>(),res)
return res
}
private fun dfs(index: Int, n: Int, k: Int, tempList: LinkedList<Int>, res: java.util.ArrayList<java.util.ArrayList<Int>>) {
//递归结束条件
if (tempList.size == k){
res.add(ArrayList(tempList))
return
}
//逻辑处理
for (i in index..n){
tempList.add(i)
dfs(i+1,n,k,tempList,res)
//回溯
tempList.removeLast()
}
//数据reverse
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,350 | MyLeetCode | Apache License 2.0 |
library/src/main/java/com/dawan/multilingualcomparator/MultilingualismComparator.kt | hedawan | 327,342,004 | false | null | package com.dawan.multilingualcomparator
import java.util.*
class MultilingualismComparator : Comparator<String> {
private val comparatorList = LinkedList<LanguageComparator>()
override fun compare(str1: String?, str2: String?): Int {
var result = 0
// 判空处理
when {
str1 == null && str2 != null -> result = -1
str1 != null && str2 == null -> result = 1
str1 == null && str2 == null -> result = 0
}
if (str1 == null || str2 == null) return result
var startPosition1 = 0
var startPosition2 = 0
var endPosition1: Int
var endPosition2: Int
var substring1: String
var substring2: String
var sameLanguageComparator: LanguageComparator
while (true) {
endPosition1 = getSameLanguageEndPosition(str1, startPosition1)
endPosition2 = getSameLanguageEndPosition(str2, startPosition2)
substring1 = str1.substring(startPosition1, endPosition1)
substring2 = str2.substring(startPosition2, endPosition2)
sameLanguageComparator =
getSameLanguageComparator(substring1.first(), substring2.first())
result = sameLanguageComparator.compare(substring1, substring2)
if (result != 0) {
break
} else if (endPosition1 == str1.length || endPosition2 == str2.length) {
result = str1.length.compareTo(str2.length)
break
} else {
startPosition1 = endPosition1
startPosition2 = endPosition2
}
}
return result
}
private fun getSameLanguageEndPosition(string: String, startPosition: Int): Int {
var endPosition = startPosition
var char: Char
var languagesComparator1: LanguageComparator? = null
var languagesComparator2: LanguageComparator
val handleRange = startPosition until string.length
for (i in handleRange) {
char = string[i]
if (languagesComparator1 == null) {
languagesComparator1 = getLanguageComparator(char)
} else {
languagesComparator2 = getLanguageComparator(char)
if (languagesComparator1 != languagesComparator2) {
break
}
}
endPosition = i
}
return ++endPosition
}
private fun getLanguageComparator(char: Char): LanguageComparator {
var targetComparator: LanguageComparator? = null
var comparator: LanguageComparator
val listIterator = comparatorList.listIterator(comparatorList.size)
while (listIterator.hasPrevious()) {
comparator = listIterator.previous()
if (comparator.isLanguage(char)) {
targetComparator = comparator
break
}
}
if (targetComparator == null) {
throw RuntimeException("无法处理当前语言,nowLanguage=${char},请添加相应的MultilingualComparator。")
}
return targetComparator
}
private fun getSameLanguageComparator(char1: Char, char2: Char): LanguageComparator {
var targetComparator: LanguageComparator? = null
var comparator: LanguageComparator
val listIterator = comparatorList.listIterator(comparatorList.size)
while (listIterator.hasPrevious()) {
comparator = listIterator.previous()
if (comparator.isLanguage(char1) && comparator.isLanguage(char2)) {
targetComparator = comparator
break
}
}
if (targetComparator == null) {
throw RuntimeException("无法处理当前两种语言,nowLanguage1=${char1},nowLanguage2=${char2},请添加相应的MultilingualComparator。")
}
return targetComparator
}
fun addLanguageComparator(comparator: LanguageComparator): MultilingualismComparator {
comparatorList.offerLast(comparator)
return this
}
fun removeLanguageComparator(comparator: LanguageComparator): Boolean {
return comparatorList.removeLastOccurrence(comparator)
}
} | 0 | Kotlin | 0 | 0 | 06286e379d5f736ea0b58c16e7c793be163c3640 | 4,263 | MultilingualComparator | Apache License 2.0 |
problems/2021adventofcode16a/submissions/accepted/Stefan.kt | stoman | 47,287,900 | false | {"C": 169266, "C++": 142801, "Kotlin": 115106, "Python": 76047, "Java": 68331, "Go": 46428, "TeX": 27545, "Shell": 3428, "Starlark": 2165, "Makefile": 1582, "SWIG": 722} | import java.util.*
abstract class Packet(val version: Int, val type: Int, val bitCount: Int) {
fun versionSum(): Int = version + if(this is Operator) subPackets.sumOf { it.versionSum() } else 0
}
class Literal(version: Int, type: Int, bitCount: Int, val value: Int) : Packet(version, type, bitCount)
class Operator(version: Int, type: Int, bitCount: Int, val subPackets: List<Packet>) : Packet(version, type, bitCount)
fun Char.toBits(): List<Int> {
var v = lowercaseChar().digitToInt(16)
val r = mutableListOf<Int>()
repeat(4) {
r.add(v % 2)
v /= 2
}
return r.reversed()
}
fun List<Int>.parseBits(): Int {
var r = 0
for (bit in this) {
r *= 2
r += bit
}
return r
}
fun List<Int>.parsePacket(): Packet {
val version = slice(0..2).parseBits()
when (val type = slice(3..5).parseBits()) {
// Literal value.
4 -> {
val value = mutableListOf<Int>()
var i = 1
do {
i += 5
value.addAll(slice(i + 1..i + 4))
} while (get(i) == 1)
return Literal(version, type, i + 5, value.parseBits())
}
// Operator
else -> {
val subPackets = mutableListOf<Packet>()
var parsedBits = 0
when(get(6)) {
0 -> {
val subLength = slice(7..21).parseBits()
parsedBits = 22
while(parsedBits < 22 + subLength) {
val nextPacket = drop(parsedBits).parsePacket()
subPackets.add(nextPacket)
parsedBits += nextPacket.bitCount
}
}
1 -> {
val subLength = slice(7..17).parseBits()
parsedBits = 18
while(subPackets.size < subLength) {
val nextPacket = drop(parsedBits).parsePacket()
subPackets.add(nextPacket)
parsedBits += nextPacket.bitCount
}
}
}
return Operator(version, type, parsedBits, subPackets)
}
}
}
fun main() {
val packet = Scanner(System.`in`).next().flatMap { it.toBits() }.parsePacket()
println(packet.versionSum())
}
| 0 | C | 1 | 3 | ee214c95c1dc1d5e9510052ae425d2b19bf8e2d9 | 2,028 | CompetitiveProgramming | MIT License |
src/main/kotlin/org/example/e3fxgaming/adventOfCode/aoc2023/day06/Day06.kt | E3FxGaming | 726,041,587 | false | {"Kotlin": 38290} | package org.example.e3fxgaming.adventOfCode.aoc2023.day06
import org.example.e3fxgaming.adventOfCode.utility.Day
import org.example.e3fxgaming.adventOfCode.utility.InputParser
import org.example.e3fxgaming.adventOfCode.utility.MultiLineInputParser
class Day06(input: String) : Day<Pair<Int, Int>, Pair<Long, Long>> {
override val partOneParser: InputParser<Pair<Int, Int>> = object : MultiLineInputParser<Pair<Int, Int>>(input) {
override fun parseFullInput(fullInput: String): List<Pair<Int, Int>> =
fullInput.split(System.lineSeparator()).map { lineString ->
lineString.substringAfter(':').split(' ')
.filter { it.isNotEmpty() }.map { it.toInt() }
}.let { (timeSteps, distanceSteps) -> timeSteps.zip(distanceSteps) }
}
override val partTwoParser: InputParser<Pair<Long, Long>> = object : MultiLineInputParser<Pair<Long, Long>>(input) {
override fun parseFullInput(fullInput: String): List<Pair<Long, Long>> =
fullInput.split(System.lineSeparator()).map { lineString ->
lineString.substringAfter(':').replace(" ", "").toLong()
}.zipWithNext()
}
override fun solveFirst(given: List<Pair<Int, Int>>): String =
given.map { (time, distance) ->
(0..time).count { windUpTime ->
(windUpTime * (time - windUpTime)) > distance
}
}.reduce(Int::times).toString()
override fun solveSecond(given: List<Pair<Long, Long>>): String {
val (time, distance) = given.first()
val firstPossible = (0..time).first { windUpTime ->
(windUpTime * (time - windUpTime)) > distance
}
val lastPossible = (time downTo 0).first { windUpTime ->
(windUpTime * (time - windUpTime)) > distance
}
return (lastPossible - firstPossible + 1).toString()
}
}
fun main() = Day06(
Day06::class.java.getResource("/2023/day06/realInput1.txt")!!.readText()
).runBoth() | 0 | Kotlin | 0 | 0 | 3ae9e8b60788733d8bc3f6446d7a9ae4b3dabbc0 | 2,007 | adventOfCode | MIT License |
src/Day01.kt | BenHopeITC | 573,352,155 | false | null | fun main() {
fun calsPerElf(input: String): List<Int> {
return input.split("\n\n").map(String::toInt)
}
fun part1(input: String): Int {
return calsPerElf(input).max()
}
fun part2(input: String): Int {
return calsPerElf(input).sorted().takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// println(part1(testInput))
// check(part1(testInput) == 24000)
// test if implementation meets criteria from the description, like:
// val testInput2 = readInput("Day01_test")
// println(part2(testInput2))
// check(part2(testInput2) == 45000)
val input = readInputAsText("Day01")
println(part1(input))
println(part2(input))
check(part1(input) == 70369)
check(part2(input) == 203002)
}
| 0 | Kotlin | 0 | 0 | 851b9522d3a64840494b21ff31d83bf8470c9a03 | 855 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/it/unito/probability/bayes/CustomEliminationAsk.kt | lamba92 | 138,590,514 | false | {"Kotlin": 123126} | package it.unito.probability.bayes
import aima.core.probability.CategoricalDistribution
import aima.core.probability.RandomVariable
import aima.core.probability.bayes.BayesInference
import aima.core.probability.bayes.BayesianNetwork
import aima.core.probability.bayes.FiniteNode
import aima.core.probability.bayes.impl.CPT
import aima.core.probability.proposition.AssignmentProposition
import it.unito.probability.CustomFactor
import it.unito.probability.CustomProbabilityTable
import it.unito.probability.utils.convertToCustom
import it.unito.probability.utils.multiplyAll
open class CustomEliminationAsk(val inferenceMethod: InferenceMethod = InferenceMethod.STANDARD): BayesInference {
enum class InferenceMethod {
STANDARD, MPE, MAP
}
override fun ask(X: Array<RandomVariable>, observedEvidences: Array<AssignmentProposition>, bn: BayesianNetwork): CategoricalDistribution? {
checkQuery(X, bn, observedEvidences)
val (hidden, vars) = when(inferenceMethod){
InferenceMethod.MPE -> Pair(ArrayList<RandomVariable>(), ArrayList<RandomVariable>(bn.variablesInTopologicalOrder))
else -> calculateVariables(X, observedEvidences, bn)
}
val factors = ArrayList<CustomFactor>()
for (rv in vars) {
factors.add(0, makeFactor(rv, observedEvidences, bn))
}
return when(inferenceMethod){
InferenceMethod.STANDARD -> exactInference((order(bn, hidden)), factors)
InferenceMethod.MPE -> mpeInference((order(bn, vars)), factors)
InferenceMethod.MAP -> mapInference((order(bn, hidden)), X.apply { this.forEach { println(it) } }, factors)
}
}
private fun mapInference(hidden: ArrayList<RandomVariable>, queries: Array<RandomVariable>, factors: ArrayList<CustomFactor>): CategoricalDistribution {
var newFactors = ArrayList(factors)
hidden.forEach {
newFactors = sumOut(it, newFactors)
}
queries.forEach {
var (newFactors, block) = maxOut(it, newFactors)
}
return newFactors.map { it as CustomProbabilityTable }.multiplyAll()
}
private fun exactInference(orderedHiddenRVs: ArrayList<RandomVariable>,
factors: ArrayList<CustomFactor>): CategoricalDistribution {
var newFactors = ArrayList(factors)
for(rv in orderedHiddenRVs){
newFactors = sumOut(rv, newFactors)
}
return (pointwiseProduct(newFactors) as CustomProbabilityTable).normalize()
}
private fun mpeInference(hiddenOrdered : ArrayList<RandomVariable>,
factors: ArrayList<CustomFactor>): CategoricalDistribution {
var newFactors = ArrayList(factors)
val finalAssignments = ArrayList<ArrayList<ArrayList<HashMap<RandomVariable, ArrayList<HashMap<RandomVariable, Any>>>>>>()
for(rv in hiddenOrdered){
val a = maxOut(rv, newFactors)
newFactors = a.first
finalAssignments.add(a.second)
}
val tables = ArrayList<ArrayList<HashMap<RandomVariable, Any>>>()
finalAssignments.forEach { block ->
block.forEach { it.forEach { it.forEach { table -> tables.add(table.value) } } }
}
val mpeAssignments = getMpeAssignments(tables)
println("\n" + mpeAssignments)
return newFactors.map { it as CustomProbabilityTable}.multiplyAll()
}
private fun getMpeAssignments(tables: ArrayList<ArrayList<HashMap<RandomVariable, Any>>>): HashSet<Map.Entry<RandomVariable, Any>> {
do {
val size = tables.size - 1
for (i in 0..size) {
for (j in 0..size) {
if (i != j) {
val (firstTable, secondTable)
= intersectAssignments(tables[i], tables[j])
tables[i] = firstTable
tables[j] = secondTable
}
}
}
} while (tables.count { it.size == 1 } != tables.size)
val resultSet = HashSet<Map.Entry<RandomVariable, Any>>()
tables.forEach {
it.forEach {
resultSet.addAll(it.entries)
}
}
return resultSet
}
private fun intersectAssignments(table1: ArrayList<HashMap<RandomVariable, Any>>,
table2: ArrayList<HashMap<RandomVariable, Any>>) :
Pair<ArrayList<HashMap<RandomVariable, Any>>, ArrayList<HashMap<RandomVariable, Any>>> {
val commonColumn = table1.first().keys.intersect(table2.first().keys)
val diff1 = table1.first().keys.minus(commonColumn)
val diff2 = table2.first().keys.minus(commonColumn)
if (commonColumn.isNotEmpty()) {
val deleteSet = HashSet<Map<RandomVariable, Any>>()
val newTable2 = ArrayList<HashMap<RandomVariable, Any>>()
table1.forEach { row -> deleteSet.add(row.minus(diff1)) }
table2.filterTo(newTable2) { row ->
deleteSet.any {
row.entries.containsAll(it.entries)
}
}
deleteSet.clear()
val newTable1 = ArrayList<HashMap<RandomVariable, Any>>()
table2.forEach { row -> deleteSet.add(row.minus(diff2)) }
table1.filterTo(newTable1) { row ->
deleteSet.any {
row.entries.containsAll(it.entries)
}
}
return Pair(newTable1, newTable2)
}
return Pair(table1, table2)
}
private fun checkQuery(X: Array<RandomVariable>, bn: BayesianNetwork, observedEvidences: Array<AssignmentProposition>) {
if (inferenceMethod == InferenceMethod.STANDARD) {
if (X.isEmpty())
throw java.lang.IllegalArgumentException("Cannot apply elimination without a query.")
if (!bn.variablesInTopologicalOrder.containsAll(X.toList()) || !bn.variablesInTopologicalOrder.containsAll(observedEvidences.map { it.termVariable }))
throw java.lang.IllegalArgumentException("Cannot apply elimination on variables not inside the net.")
} else if (inferenceMethod == InferenceMethod.MPE) {
if (!bn.variablesInTopologicalOrder.containsAll(observedEvidences.map { it.termVariable }))
throw java.lang.IllegalArgumentException("Cannot apply MPE elimination on variables not inside the net.")
if (X.isNotEmpty()) println("Query array is not empty. MPE does not need any query variable. Computation will continue...")
}
}
/**
* Override this method for a more efficient implementation as
* outlined in AIMA3e pgs. 527-28. Calculate the hidden variables from the
* Bayesian Network. The default implementation does not perform any of
* these.
*
* Two calcuations to be performed here in order to optimize iteration over
* the Bayesian Network:<br>
* 1. Calculate the hidden variables to be enumerated over. An optimization
* (AIMA3e pg. 528) is to remove 'every variable that is not an ancestor of
* a query variable or evidence variable as it is irrelevant to the query'
* (i.e. sums to 1). 2. The subset of variables from the Bayesian Network to
* be retained after irrelevant hidden variables have been removed.
*
* @param X Query random variables.
* @param e Evidences on the network.
* @param bn The [BayesianNetwork] on which execute the ordering.
* @return A [Pair]<[Set]<[RandomVariable]>, [ArrayList]<[RandomVariable]>> where the first element are the relevant hidden, the second all the relevant hiddens comprising the query variables
*/
open fun calculateVariables(X: Array<RandomVariable>, e: Array<AssignmentProposition>, bn: BayesianNetwork)
: Pair<Set<RandomVariable>, Collection<RandomVariable>> {
val hidden = HashSet<RandomVariable>(bn.variablesInTopologicalOrder)
hidden.removeAll(X)
hidden.removeAll(e.map { it.termVariable })
val relevantRVs = ArrayList(hidden).apply { addAll(X); addAll(e.map { it.termVariable }) }
return Pair(hidden, relevantRVs)
}
private fun makeFactor(rv: RandomVariable,
e: Array<AssignmentProposition>,
bn: BayesianNetwork): CustomFactor {
val n = bn.getNode(rv) as? FiniteNode ?: throw IllegalArgumentException("Elimination-Ask only works with finite Nodes.")
val relevantEvidences = e.filter { n.cpt.contains(it.termVariable) }
return (n.cpt as CPT).convertToCustom().getFactorFor(relevantEvidences)
}
/**
* Override this method for a more efficient implementation as
* outlined in AIMA3e pgs. 527-28. The default implementation does not
* perform any of these.
* @param vars The collection [RandomVariable]s to order.
* @param bn The network from which generate the ordering of [vars]
*/
open fun order(bn: BayesianNetwork,
vars: Collection<RandomVariable>): ArrayList<RandomVariable>{
return ArrayList(vars.reversed())
}
private fun sumOut(rv: RandomVariable, factors: List<CustomFactor>): ArrayList<CustomFactor> {
val summedOutFactors = ArrayList<CustomFactor>()
val (toMultiply, notTo) = factors.partition { it.contains(rv) }
summedOutFactors.addAll(notTo)
summedOutFactors.add(pointwiseProduct(toMultiply).sumOut(rv) as CustomFactor)
return summedOutFactors
}
private fun maxOut(rv: RandomVariable, factors: List<CustomFactor>)
: Pair<ArrayList<CustomFactor>, ArrayList<ArrayList<HashMap<RandomVariable, ArrayList<HashMap<RandomVariable, Any>>>>>>{
val maxedOutFactors = ArrayList<CustomFactor>()
val (toMultiply, notTo) = factors.partition { it.contains(rv) }
maxedOutFactors.addAll(notTo)
val pointWised = pointwiseProduct(toMultiply)
val maxedOut = pointWised.maxOut(rv)
maxedOutFactors.add(maxedOut)
//maxedOut contiene finalAssignment. Devi ritornarlo!
return Pair(maxedOutFactors, (maxedOut as CustomProbabilityTable).finalAssignment)
}
private fun pointwiseProduct(factors: List<CustomFactor>): CustomFactor {
var product = factors[0]
for (i in 1 until factors.size) {
product = product.pointwiseProduct(factors[i]) as CustomFactor
}
return product
}
}
| 0 | Kotlin | 2 | 7 | 716c241e314e56c9c2b82414a53d9c2336a22070 | 10,573 | bayesian-net-project | MIT License |
codechef/snackdown2021/preelim/goodranking_randomized.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codechef.snackdown2021.preelim
import java.util.*
private fun solve(magic: Int = 96): List<Int> {
val n = readInt()
val e = List(n) { readLn() }
val diff = (n + 1) / 2
fun won(i: Int, j: Int) = e[i][j] == '1'
val level = IntArray(n)
val r = Random(566)
var tries = 0
for (mid in e.indices.shuffled(r)) {
val (weak, strong) = (e.indices - mid).partition { won(mid, it) }.toList().map { it.toMutableList() }
if (maxOf(weak.size, strong.size) > diff + 1) continue
if (++tries == magic) break
level.fill(0)
for (a in listOf(weak, strong)) {
for (i in a.indices) for (j in 0 until i) {
if (won(a[i], a[j])) level[a[i]]++ else level[a[j]]++
}
a.sortBy { level[it] }
}
val p = weak + mid + strong
var good = true
for (i in p.indices) for (j in i + 1..minOf(i + diff, n - 1)) {
if (won(p[i], p[j])) {
good = false
break
}
}
if (good) {
return p.toIntArray().reversed().map { it + 1 }
}
}
return listOf(-1)
}
@Suppress("UNUSED_PARAMETER") // Kotlin 1.2
fun main(args: Array<String>) = repeat(readInt()) { println(solve().joinToString(" ")) }
private fun readLn() = readLine()!!.trim()
private fun readInt() = readLn().toInt()
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,193 | competitions | The Unlicense |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MissingNumber.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
/**
* Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
*/
fun interface AbstractMissingNumberStrategy {
operator fun invoke(nums: IntArray): Int
}
// Time complexity : O(n lg n)
// Space complexity : O(1) or O(n)
class MissingNumberSorting : AbstractMissingNumberStrategy {
override operator fun invoke(nums: IntArray): Int {
nums.sort()
if (nums.isEmpty()) return 0
if (nums.last() != nums.size) {
return nums.size
} else if (nums.first() != 0) {
return 0
}
for (i in 1 until nums.size) {
val expectedNum = nums[i - 1] + 1
if (nums[i] != expectedNum) {
return expectedNum
}
}
return -1
}
}
// Time complexity : O(n)
// Space complexity : O(n)
class MissingNumberHashSet : AbstractMissingNumberStrategy {
override operator fun invoke(nums: IntArray): Int {
val numSet: MutableSet<Int> = HashSet()
for (num in nums) {
numSet.add(num)
}
val expectedNumCount = nums.size + 1
for (number in 0 until expectedNumCount) {
if (!numSet.contains(number)) {
return number
}
}
return -1
}
}
// Time complexity : O(n)
// Space complexity : O(1)
class MissingNumberBitManipulation : AbstractMissingNumberStrategy {
override operator fun invoke(nums: IntArray): Int {
var missing = nums.size
for (i in nums.indices) {
missing = missing xor (i xor nums[i])
}
return missing
}
}
// Time complexity : O(n)
// Space complexity : O(1)
class MissingNumberGaussFormula : AbstractMissingNumberStrategy {
override operator fun invoke(nums: IntArray): Int {
val local = nums.size + 1
val expectedSum = nums.size * local / 2
var actualSum = 0
for (num in nums) {
actualSum += num
}
return expectedSum - actualSum
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,698 | kotlab | Apache License 2.0 |
2021/src/Day17.kt | Bajena | 433,856,664 | false | {"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454} | import java.util.*
// https://adventofcode.com/2021/day/17
fun main() {
fun computeY(vy: Int, currX: Int, currVx : Int, currentStep : Int, minX: Int, maxX: Int, minY: Int, maxY: Int) : Int {
var steps = currentStep
var currentX = currX
var currentVx = currVx
var currentVy = vy - currentStep
var currentY = ((2 * vy - currentStep + 1) / 2.0 * currentStep).toInt()
while (currentX in minX..maxX && currentY > maxY) {
steps++
currentX += currentVx
currentY += currentVy
if (currentVx > 0) currentVx--
currentVy--
}
return if (currentX in minX..maxX && currentY in minY..maxY) currentStep else -1
}
fun height(vy: Int, maxStep: Int) : Int {
return (0..1000).maxOf { currentStep ->
((2 * vy - currentStep + 1) / 2.0 * currentStep).toInt()
}
}
fun calcStepOfHit(vx: Int, minX: Int, maxX: Int, minY: Int, maxY: Int) : Int {
var currentVx = vx
var steps = 0
var currentX = 0
while (currentX < minX && currentVx > 0) {
steps++
currentX += currentVx
if (currentVx > 0) currentVx--
}
if (currentX !in minX..maxX) return -1000
var maxHeight = -1000
for (vy in minY..-minY) {
val maxStep = computeY(vy, currentX, currentVx, steps, minX, maxX, minY, maxY)
if (maxStep > 0) {
val height = height(vy, maxStep)
if (height > maxHeight) {
maxHeight = height
}
println("vx:$vx, vy:$vy, step:$maxStep, height:${height}")
}
}
return maxHeight
}
fun calcCoords(vx: Int, minX: Int, maxX: Int, minY: Int, maxY: Int) : List<Pair<Int, Int>> {
var currentVx = vx
var steps = 0
var currentX = 0
while (currentX < minX && currentVx > 0) {
steps++
currentX += currentVx
if (currentVx > 0) currentVx--
}
if (currentX !in minX..maxX) return listOf()
var result = mutableListOf<Pair<Int, Int>>()
for (vy in minY..-minY) {
val maxStep = computeY(vy, currentX, currentVx, steps, minX, maxX, minY, maxY)
if (maxStep > 0) {
result.add(Pair(vx, vy))
println("vx:$vx, vy:$vy")
}
}
return result
}
fun part1() {
// var minX = 20
// var maxX = 30
// var minY = -10
// var maxY = -5
//
// var minVx = 6 // https://www.wolframalpha.com/input/?i=x2%2Bx-40%3D0
var minX = 25
var maxX = 67
var minY = -260
var maxY = -200
var minVx = 7 // https://www.wolframalpha.com/input/?i=x2%2Bx-50%3D0
var maxHeight = -1000
for (vx in minVx..maxX) {
val height = calcStepOfHit(vx, minX, maxX, minY, maxY)
if (height > maxHeight) maxHeight = height
}
println(maxHeight)
}
fun part2() {
var minX = 20
var maxX = 30
var minY = -10
var maxY = -5
var minVx = 6 // https://www.wolframalpha.com/input/?i=x2%2Bx-40%3D0
// var minX = 25
// var maxX = 67
// var minY = -260
// var maxY = -200
//
// var minVx = 7 // https://www.wolframalpha.com/input/?i=x2%2Bx-50%3D0
var result = mutableListOf<Pair<Int, Int>>()
for (vx in minVx..maxX) {
result.addAll(calcCoords(vx, minX, maxX, minY, maxY))
}
println(result.count())
}
// part1()
part2()
}
| 0 | Kotlin | 0 | 0 | a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a | 3,237 | advent-of-code | Apache License 2.0 |
src/kotlin2022/Day04.kt | egnbjork | 571,981,366 | false | {"Kotlin": 18156} | package kotlin2022
import readInput
fun main() {
val gameInput = readInput("Day04_test")
val pairs = gameInput.map{it.split(",")}
var count = 0
for(pair in pairs) {
if(rangeInRange(pair)) {
count++
}
}
println(count)
}
fun rangeInRange(pair: List<String>): Boolean {
val range1String = pair[0].split("-")
val range2String = pair[1].split('-')
val range1 = range1String[0].toInt().rangeTo(range1String[1].toInt())
val range2 = range2String[0].toInt().rangeTo(range2String[1].toInt())
return inRange(range1, range2) || inRange(range2, range1)
}
fun inRange(range1: IntRange, range2: IntRange): Boolean{
return range1.first - range2.first <= 0 &&
range1.last - range2.first >= 0
}
| 0 | Kotlin | 0 | 0 | 1294afde171a64b1a2dfad2d30ff495d52f227f5 | 772 | advent-of-code-kotlin | Apache License 2.0 |
src/Day01.kt | mjossdev | 574,439,750 | false | {"Kotlin": 81859} | fun main() {
fun readCalories(input: List<String>): List<Int> = buildList {
var current = 0
for (line in input) {
if (line.isEmpty() && current > 0) {
add(current)
current = 0
} else {
current += line.toInt()
}
}
}
fun part1(input: List<String>): Int = readCalories(input).max()
fun part2(input: List<String>): Int = readCalories(input).sortedDescending().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")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | afbcec6a05b8df34ebd8543ac04394baa10216f0 | 778 | advent-of-code-22 | Apache License 2.0 |
aoc/src/main/kotlin/com/bloidonia/aoc2023/day20/Main.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.day20
import com.bloidonia.aoc2023.lcm
import com.bloidonia.aoc2023.text
import java.time.LocalTime
private enum class Pulse {
LOW, HIGH
}
private data class Signal(val source: String, val target: String, val pulse: Pulse) {
override fun toString() = "$source -${pulse}-> $target"
}
private abstract class Module(val name: String, val targets: List<String>) {
abstract fun pulse(circuit: Map<String, Module>, pulse: Signal): List<Signal>
}
private class FlipFlop(name: String, targets: List<String>) : Module(name, targets) {
private var on: Boolean = false
override fun pulse(circuit: Map<String, Module>, pulse: Signal): List<Signal> {
if (pulse.pulse == Pulse.LOW) {
on = !on
return targets.map { Signal(name, it, if (on) Pulse.HIGH else Pulse.LOW) }
}
return listOf()
}
override fun toString() = "FlipFlop(name='$name', targets=$targets)"
}
private class Broadcast(targets: List<String>) : Module("broadcast", targets) {
override fun pulse(circuit: Map<String, Module>, pulse: Signal): List<Signal> {
return targets.map { Signal("broadcaster", it, pulse.pulse) }
}
override fun toString() = "Broadcast(targets=$targets)"
}
private class Conjunction(name: String, targets: List<String>, val inputs: MutableMap<String, Pulse> = mutableMapOf()) :
Module(name, targets) {
fun setInputs(names: List<String>) {
names.forEach {
this.inputs[it] = Pulse.LOW
}
}
override fun pulse(circuit: Map<String, Module>, pulse: Signal): List<Signal> {
inputs[pulse.source] = pulse.pulse
if (inputs.values.all { it == Pulse.HIGH }) {
return targets.map { Signal(name, it, Pulse.LOW) }
}
return targets.map { Signal(name, it, Pulse.HIGH) }
}
override fun toString() = "Conjunction(name='$name', targets=$targets, inputs=$inputs)"
}
private fun parse(input: String) = input.lines().associate {
val (name, targets) = it.split(" -> ")
val targetNames = targets.split(", ")
when {
name == "broadcaster" -> name to Broadcast(targetNames)
name.startsWith("%") -> name.drop(1) to FlipFlop(name.drop(1), targetNames)
else -> name.drop(1) to Conjunction(name.drop(1), targetNames)
}
}.let { circuit ->
circuit.values
.filterIsInstance<Conjunction>()
.forEach { c -> c.setInputs(circuit.values.filter { it.targets.contains(c.name) }.map { it.name }) }
circuit
}
private fun part1(circuit: Map<String, Module>): Map<Pulse, Int> {
val totals = mutableMapOf(
Pulse.LOW to 0,
Pulse.HIGH to 0
)
for (i in 1..1000) {
val signals = mutableListOf(Signal("button", "broadcaster", Pulse.LOW))
while (signals.isNotEmpty()) {
signals.forEach { signal ->
totals[signal.pulse] = totals[signal.pulse]!! + 1
}
signals.flatMap { signal ->
circuit[signal.target]?.pulse(circuit, signal) ?: listOf()
}.let {
signals.clear()
signals.addAll(it)
}
}
}
return totals
}
private fun emitsHigh(circuit: Map<String, Module>, name: String): Long {
var i = 1L
while (true) {
val signals = mutableListOf(Signal("button", "broadcaster", Pulse.LOW))
while (signals.isNotEmpty()) {
if (signals.any { it.source == name && it.pulse == Pulse.HIGH }) {
return i
}
signals.flatMap { signal ->
circuit[signal.target]?.pulse(circuit, signal) ?: listOf()
}.let {
signals.clear()
signals.addAll(it)
}
}
if (++i % 10000000 == 0L) println("${LocalTime.now()} $i")
}
}
private const val example = """broadcaster -> a
%a -> inv, con
&inv -> b
%b -> con
&con -> output"""
fun main() {
val example = parse(example)
part1(example).let {
println("Example Total: ${it[Pulse.LOW]!! * it[Pulse.HIGH]!!} (Low: ${it[Pulse.LOW]}, High: ${it[Pulse.HIGH]})")
}
part1(parse(text("/day20.input"))).let {
println("Part 1 Total: ${it[Pulse.LOW]!! * it[Pulse.HIGH]!!} (Low: ${it[Pulse.LOW]}, High: ${it[Pulse.HIGH]})")
}
println((parse(text("/day20.input")).values.first { it.targets.contains("rx") } as Conjunction)
.inputs
.keys)
// It's the LCM of the steps until the Conjunctions that lead to it fire a high signal
// Once they all fire HIGH at the same time, then a HIGH is sent to the rx node
(parse(text("/day20.input")).values.first { it.targets.contains("rx") } as Conjunction)
.inputs
.keys
.map { name ->
emitsHigh(parse(text("/day20.input")), name)
}
.toLongArray()
.let { println("Part 2: ${lcm(*it)}") }
} | 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 4,920 | aoc-2023 | MIT License |
2019/src/main/kotlin/days/Day1.kt | pgrosslicht | 160,153,674 | false | null | package days
import Day
class Day1 : Day(1) {
/*--- Day 1: The Tyranny of the Rocket Equation ---
Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
The Elves quickly load you into a spacecraft and prepare to launch.
At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet.
Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 3.
For example:
For a mass of 13, divide by 3 and round down to get 4, then subtract 2 to get 2.
For a mass of 15, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
For a mass of 1970, the fuel required is 654.
For a mass of 100757, the fuel required is 33583.
The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
What is the sum of the fuel requirements for all of the modules on your spacecraft?*/
override fun partOne(): Int = dataList.map(String::toInt)
.sumBy { it / 3 - 2 }
/*--- Part Two ---
During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence. Apparently, you forgot to include additional fuel for the fuel you just added.
Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However, that fuel also requires fuel, and that fuel requires fuel, and so on. Any mass that would require negative fuel should instead be treated as if it requires zero fuel; the remaining mass, if any, is instead handled by wishing really hard, which has no mass and is outside the scope of this calculation.
So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. For example:
A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which would call for a negative fuel), so the total fuel required is still just 2.
At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
The fuel required by a module of mass 100756 and its fuel is: 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.)*/
override fun partTwo(): Int = dataList.map(String::toInt)
.map { it / 3 - 2 }
.flatMap { makeSequence(it).asIterable() }
.sum()
private fun makeSequence(value: Int): Sequence<Int> =
generateSequence(value) { it / 3 - 2 }.takeWhile { it > 0 }
}
fun main() = Day.mainify(Day1::class) | 0 | Kotlin | 0 | 0 | 1f27fd65651e7860db871ede52a139aebd8c82b2 | 3,777 | advent-of-code | MIT License |
native/native.tests/tests/org/jetbrains/kotlin/konan/test/blackbox/support/util/TreeNode.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.konan.test.blackbox.support.util
import org.jetbrains.kotlin.konan.test.blackbox.support.PackageName
internal interface TreeNode<T> {
val packageSegment: PackageName
val items: Collection<T>
val children: Collection<TreeNode<T>>
companion object {
fun <T> oneLevel(vararg items: T) = oneLevel(listOf(*items))
fun <T> oneLevel(items: Iterable<T>): List<TreeNode<T>> = listOf(object : TreeNode<T> {
override val packageSegment get() = PackageName.EMPTY
override val items = items.toList()
override val children get() = emptyList<TreeNode<T>>()
})
}
}
internal fun <T, R> Collection<T>.buildTree(extractPackageName: (T) -> PackageName, transform: (T) -> R): Collection<TreeNode<R>> {
val groupedItems: Map<PackageName, List<R>> = groupBy(extractPackageName).mapValues { (_, items) -> items.map(transform) }
// Fast pass.
when (groupedItems.size) {
0 -> return TreeNode.oneLevel()
1 -> return TreeNode.oneLevel(groupedItems.values.first())
}
// Long pass.
val root = TreeBuilder<R>(PackageName.EMPTY)
// Populate the tree.
groupedItems.forEach { (packageName, items) ->
var node = root
packageName.segments.forEach { packageSegment ->
val packageSegmentAsName = PackageName(listOf(packageSegment))
node = node.childrenMap.computeIfAbsent(packageSegmentAsName) { TreeBuilder(packageSegmentAsName) }
}
node.items += items
}
// Skip meaningless nodes starting from the root.
val meaningfulNode = root.skipMeaninglessNodes().apply { compress() }
// Compress the resulting tree.
return if (meaningfulNode.items.isNotEmpty() || meaningfulNode.childrenMap.isEmpty())
listOf(meaningfulNode)
else
meaningfulNode.childrenMap.values
}
private class TreeBuilder<T>(override var packageSegment: PackageName) : TreeNode<T> {
override val items = mutableListOf<T>()
val childrenMap = hashMapOf<PackageName, TreeBuilder<T>>()
override val children: Collection<TreeBuilder<T>> get() = childrenMap.values
}
private tailrec fun <T> TreeBuilder<T>.skipMeaninglessNodes(): TreeBuilder<T> =
if (items.isNotEmpty() || childrenMap.size != 1)
this
else
childrenMap.values.first().skipMeaninglessNodes()
private fun <T> TreeBuilder<T>.compress() {
while (items.isEmpty() && childrenMap.size == 1) {
val childNode = childrenMap.values.first()
items += childNode.items
childrenMap.clear()
childrenMap += childNode.childrenMap
packageSegment = joinPackageNames(packageSegment, childNode.packageSegment)
}
childrenMap.values.forEach { it.compress() }
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,987 | kotlin | Apache License 2.0 |
src/main/kotlin/io/github/raphaeltarita/days/Day15.kt | RaphaelTarita | 433,468,222 | false | {"Kotlin": 89687} | package io.github.raphaeltarita.days
import io.github.raphaeltarita.structure.AoCDay
import io.github.raphaeltarita.util.Twin
import io.github.raphaeltarita.util.day
import io.github.raphaeltarita.util.ds.heap.ArrayHeap
import io.github.raphaeltarita.util.ds.heap.MutableHeap
import io.github.raphaeltarita.util.inModRange
import io.github.raphaeltarita.util.inputPath
import kotlinx.datetime.LocalDate
import kotlin.io.path.readLines
object Day15 : AoCDay {
override val day: LocalDate = day(15)
private fun getInput(): List<List<Byte>> {
return inputPath.readLines()
.map { line -> line.map { it.digitToInt().toByte() } }
}
private fun adjacentTo(vertex: Twin<Int>, xsize: Int, ysize: Int): List<Twin<Int>> {
val result = ArrayList<Twin<Int>>(4)
if (vertex.first > 0) result += (vertex.first - 1) to vertex.second
if (vertex.first < xsize - 1) result += (vertex.first + 1) to vertex.second
if (vertex.second > 0) result += vertex.first to (vertex.second - 1)
if (vertex.second < ysize - 1) result += vertex.first to (vertex.second + 1)
return result
}
private fun dijkstra(weights: List<List<Byte>>, start: Twin<Int>, end: Twin<Int>): Int {
val xsize = weights.first().size
val ysize = weights.size
val processed = mutableSetOf(start)
val minPaths = adjacentTo(start, xsize, ysize).associateWith { (x, y) -> weights[y][x].toInt() }
.toMutableMap()
.withDefault { Int.MAX_VALUE }
minPaths[start] = 0
val heap: MutableHeap<Twin<Int>> = ArrayHeap(adjacentTo(0 to 0, xsize, ysize)) { o1, o2 ->
minPaths.getValue(o1) - minPaths.getValue(o2)
}
while (heap.isNotEmpty()) {
val current = heap.popMin()
processed += current
if (current == end) break
for (adj in adjacentTo(current, xsize, ysize)) {
if (adj in processed) continue
val nextCost = minPaths.getValue(current) + weights[adj.second][adj.first]
val heapIdx = heap.indexOf(adj)
if (heapIdx < 0) {
minPaths[adj] = nextCost
heap += adj
} else if (nextCost < minPaths.getValue(heap[heapIdx])) {
minPaths[adj] = nextCost
heap.decreaseKey(heapIdx, adj)
}
}
}
return minPaths.getValue((xsize - 1) to (ysize - 1))
}
override fun executePart1(): Int {
val grid = getInput()
val xsize = grid.first().size
val ysize = grid.size
return dijkstra(grid, 0 to 0, (xsize - 1) to (ysize - 1))
}
override fun executePart2(): Int {
val grid = getInput()
val xsize = grid.first().size
val ysize = grid.size
val fullGrid = List(5 * ysize) { y ->
List(5 * xsize) { x ->
((grid[y % ysize][x % xsize] + (x / xsize + y / ysize)).inModRange(1, 10)).toByte()
}
}
return dijkstra(fullGrid, 0 to 0, (xsize * 5 - 1) to (ysize * 5 - 1))
}
} | 0 | Kotlin | 0 | 3 | 94ebe1428d8882d61b0463d1f2690348a047e9a1 | 3,156 | AoC-2021 | Apache License 2.0 |
src/main/kotlin/Day3.kt | aisanu | 112,855,402 | false | {"Kotlin": 15773} | object Day3 {
// TODO: How to fix this mess
fun manhattanDistance(est: Long): Long {
val last = (1..Long.MAX_VALUE).takeWhile { Day3.bottomRightValue(it) <= est }.last()
val box = Day3.bottomRightValue(last)
var diff = est - box
val n = 2 * last
var (x, y) = (last - 1) to -(last - 1)
if(diff > 0L){
x++
diff--
for(i in 1..n - 1) {
if(diff <= 0) break
y++
diff--
}
for(i in 1..n) {
if(diff <= 0) break
x--
diff--
}
for(i in 1..n) {
if(diff <= 0) break
y--
diff--
}
for(i in 1..n) {
if(diff <= 0) break
x++
diff--
}
}
return Math.abs(x) + Math.abs(y)
}
fun bottomRightValue(x: Long): Long {
require(x > 0) { "Only non negative number allowed" }
return when(x) {
1L -> 1
else -> bottomRightValue(x - 1) + 8 * (x - 1)
}
}
fun populateMapsky(first: Int, output: MutableMap<Pair<Int, Int>, Long>) {
val start = bottomRightValue(first.toLong())
val end = bottomRightValue((first + 1).toLong())
var diff = end - start - 1
var x = first
var y = -(first - 1)
var n = (first) * 2
output[x to y] = sumNeighboor(output, x, y)
if(diff > 0L){
for(i in 1..n - 1) {
if(diff <= 0) break
y++
diff--
output[x to y]
output[x to y] = sumNeighboor(output, x, y)
}
for(i in 1..n) {
if(diff <= 0) break
x--
diff--
output[x to y] = sumNeighboor(output, x, y)
}
for(i in 1..n) {
if(diff <= 0) break
y--
diff--
output[x to y] = sumNeighboor(output, x, y)
}
for(i in 1..n) {
if(diff <= 0) break
x++
diff--
output[x to y] = sumNeighboor(output, x, y)
}
}
}
fun sumNeighboor(map: MutableMap<Pair<Int, Int>, Long>, x: Int, y: Int): Long {
val retVal = map.getOrDefault((x + 1) to (y + 0), 0L) +
map.getOrDefault((x + 1) to (y + 1), 0L) +
map.getOrDefault((x + 0) to (y + 1), 0L) +
map.getOrDefault((x + -1) to (y + 1), 0L) +
map.getOrDefault((x + -1) to (y + 0), 0L) +
map.getOrDefault((x + -1) to (y + -1), 0L) +
map.getOrDefault((x + 0) to (y + -1), 0L) +
map.getOrDefault((x + 1) to (y + -1), 0L)
if(retVal >= 277678) println("Found at ($x, $y): $retVal")
return retVal
}
} | 0 | Kotlin | 0 | 0 | 25dfe70e2bbb9b83a6ece694648a9271d1e21ddd | 2,989 | advent-of-code | The Unlicense |
src/test/kotlin/adventofcode/day07/Day07.kt | jwcarman | 573,183,719 | false | {"Kotlin": 183494} | /*
* Copyright (c) 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package adventofcode.day07
import adventofcode.util.isNumeric
import adventofcode.util.readAsLines
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
const val TOTAL_SPACE = 70000000
const val REQUIRED_SPACE = 30000000
class Day07 {
@Test
fun example1() {
assertEquals(95437, calculatePart1(readAsLines("day07-example.txt")))
}
@Test
fun part1() {
assertEquals(1306611, calculatePart1(readAsLines("day07.txt")))
}
@Test
fun example2() {
assertEquals(24933642, calculatePart2(readAsLines("day07-example.txt")))
}
@Test
fun part2() {
assertEquals(13210366, calculatePart2(readAsLines("day07.txt")))
}
private fun calculatePart1(lines: List<String>): Int {
val fs = buildFilesystem(lines)
return fs.findFiles { (_, size) -> size <= 100000 }.values.sum()
}
private fun calculatePart2(lines: List<String>): Int {
val fs = buildFilesystem(lines)
val used = fs.sizeOf("/")
val unused = TOTAL_SPACE - used
val needed = REQUIRED_SPACE - unused
return fs.findFiles { (_, size) -> size >= needed }.values.minOf { it }
}
private fun buildFilesystem(lines: List<String>): Filesystem {
val fs = Filesystem()
lines.forEach { line ->
val splits = line.split(" ")
when {
line == "$ cd .." -> fs.cdup()
line.startsWith("$ cd ") -> fs.cd(splits.last())
splits[0].isNumeric() -> fs.addFile(splits[0].toInt())
}
}
return fs
}
class Filesystem {
val dirSizes = mutableMapOf<String, Int>()
var pwd = mutableListOf<String>()
fun cd(dir: String) {
if (pwd.isEmpty()) {
pwd.add(dir)
} else {
pwd.add(0, pwd.first() + dir + "/")
}
}
fun sizeOf(dir: String): Int = dirSizes.getOrDefault(dir, -1)
fun cdup() {
pwd.removeFirst()
}
fun addFile(size: Int) {
pwd.forEach { dir ->
dirSizes[dir] = dirSizes.getOrDefault(dir, 0) + size
}
}
fun findFiles(predicate: (Map.Entry<String, Int>) -> Boolean) = dirSizes.filter(predicate)
}
} | 0 | Kotlin | 0 | 0 | d6be890aa20c4b9478a23fced3bcbabbc60c32e0 | 2,915 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/g0201_0300/s0221_maximal_square/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0201_0300.s0221_maximal_square
// #Medium #Top_100_Liked_Questions #Array #Dynamic_Programming #Matrix
// #Dynamic_Programming_I_Day_16 #Big_O_Time_O(m*n)_Space_O(m*n)
// #2022_09_10_Time_614_ms_(44.00%)_Space_76.2_MB_(65.33%)
class Solution {
fun maximalSquare(matrix: Array<CharArray>): Int {
val m = matrix.size
if (m == 0) {
return 0
}
val n: Int = matrix[0].size
if (n == 0) {
return 0
}
val dp = Array(m + 1) { IntArray(n + 1) }
var max = 0
for (i in 0 until m) {
for (j in 0 until n) {
if (matrix[i][j] == '1') {
// 1 + minimum from cell above, cell to the left, cell diagonal upper-left
val next = 1 + Math.min(dp[i][j], Math.min(dp[i + 1][j], dp[i][j + 1]))
// keep track of the maximum value seen
if (next > max) {
max = next
}
dp[i + 1][j + 1] = next
}
}
}
return max * max
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,120 | LeetCode-in-Kotlin | MIT License |
src/day02/Day02.kt | Frank112 | 572,910,492 | false | null | package day02
import assertThat
import readInput
fun main() {
fun parseInput(input: List<String>): List<Pair<String, String>> {
return input.map { s -> Pair(s.substring(0, 1), s.substring(2)) }
}
fun <T> mapper(map: Map<String, T>): (s: String) -> T {
return { s -> map[s] ?: throw IllegalArgumentException("Input could not be mapped: $s") }
}
val opponentShapeMapper =
mapper(mapOf(Pair("A", Shape.Rock), Pair("B", Shape.Paper), Pair("C", Shape.Scissor)))
fun part1(input: List<Pair<String, String>>): Int {
val ownShapeMapper =
mapper(mapOf(Pair("X", Shape.Rock), Pair("Y", Shape.Paper), Pair("Z", Shape.Scissor)))
return input.map { p ->
Pair(
opponentShapeMapper.invoke(p.first),
ownShapeMapper.invoke(p.second)
)
}
.sumOf { p -> p.second.fight(p.first).value + p.second.value }
}
fun part2(input: List<Pair<String, String>>): Int {
val resultMapper = mapper(mapOf(Pair("X", Result.LOST), Pair("Y", Result.DRAW), Pair("Z", Result.WON)))
return input.map { p -> Pair(opponentShapeMapper(p.first), resultMapper.invoke(p.second)) }
.map { p -> Pair(p.first, p.first.selectShapeByResult(p.second)) }
.sumOf { p -> p.second.fight(p.first).value + p.second.value }
}
// test if implementation meets criteria from the description, like:
val testInput = parseInput(readInput("day02/Day02_test"))
assertThat(part1(testInput), 15)
assertThat(part2(testInput), 12)
val input = parseInput(readInput("day02/Day02"))
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1e927c95191a154efc0fe91a7b89d8ff526125eb | 1,694 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g2001_2100/s2012_sum_of_beauty_in_the_array/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2012_sum_of_beauty_in_the_array
// #Medium #Array #2023_06_23_Time_511_ms_(100.00%)_Space_56.5_MB_(50.00%)
class Solution {
fun sumOfBeauties(nums: IntArray): Int {
val maxArr = IntArray(nums.size)
maxArr[0] = nums[0]
for (i in 1 until nums.size - 1) {
maxArr[i] = Math.max(maxArr[i - 1], nums[i])
}
val minArr = IntArray(nums.size)
minArr[nums.size - 1] = nums[nums.size - 1]
for (i in nums.size - 2 downTo 0) {
minArr[i] = Math.min(minArr[i + 1], nums[i])
}
var sum = 0
for (i in 1 until nums.size - 1) {
if (nums[i] > maxArr[i - 1] && nums[i] < minArr[i + 1]) {
sum += 2
} else if (nums[i] > nums[i - 1] && nums[i] < nums[i + 1]) {
sum += 1
}
}
return sum
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 881 | LeetCode-in-Kotlin | MIT License |
src/Day21.kt | kipwoker | 572,884,607 | false | null | import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
enum class MathOperator {
Plus,
Minus,
Multiply,
Divide
}
class Day21 {
data class Monkey(val name: String, var value: Long?, val left: String?, val right: String?, val op: MathOperator?)
fun parseOperator(value: String): MathOperator {
return when (value) {
"*" -> MathOperator.Multiply
"+" -> MathOperator.Plus
"-" -> MathOperator.Minus
"/" -> MathOperator.Divide
else -> throw RuntimeException("Unknown op $value")
}
}
fun parse(input: List<String>): List<Monkey> {
return input.map { line ->
val parts = line.split(' ')
if (parts.size == 4) {
Monkey(parts[0], null, parts[1], parts[3], parseOperator(parts[2]))
} else {
Monkey(parts[0], parts[1].toLong(), null, null, null)
}
}
}
fun calc1(name: String, map: Map<String, Monkey>): Long {
val monkey = map.getValue(name)
if (monkey.value != null) {
return monkey.value!!
}
val left = calc1(monkey.left!!, map)
val right = calc1(monkey.right!!, map)
val result = when (monkey.op!!) {
MathOperator.Plus -> left + right
MathOperator.Minus -> left - right
MathOperator.Multiply -> left * right
MathOperator.Divide -> left / right
}
monkey.value = result
return result
}
fun calc2(name: String, map: Map<String, Monkey>): Long {
val monkey = map.getValue(name)
if (monkey.value != null) {
return monkey.value!!
}
val left = calc2(monkey.left!!, map)
val right = calc2(monkey.right!!, map)
if (monkey.name == "root") {
return right - left
}
val result = when (monkey.op!!) {
MathOperator.Plus -> left + right
MathOperator.Minus -> left - right
MathOperator.Multiply -> left * right
MathOperator.Divide -> left / right
}
monkey.value = result
return result
}
fun part1(input: List<String>): String {
val monkeys = parse(input)
val monkeyMap = monkeys.associateBy { it.name }
val result = calc1("root", monkeyMap)
return result.toString()
}
fun part2(input: List<String>): String {
var r = 5000000000000L
var l = 0L
while (r - l > 1) {
val h = (r + l) / 2
val monkeys = parse(input)
val monkeyMap = monkeys.associateBy { it.name }
monkeyMap["humn"]!!.value = h
val result = calc2("root", monkeyMap)
if (result != 0L) {
if (result < 0) {
l = h
} else {
r = h
}
continue
}
return h.toString()
}
return "Not Found"
}
}
@OptIn(ExperimentalTime::class)
@Suppress("DuplicatedCode")
fun main() {
val solution = Day21()
val name = solution.javaClass.name
val execution = setOf(
ExecutionMode.Test1,
ExecutionMode.Test2,
ExecutionMode.Exec1,
ExecutionMode.Exec2
)
fun test() {
val expected1 = "152"
val expected2 = "301"
val testInput = readInput("${name}_test")
if (execution.contains(ExecutionMode.Test1)) {
println("Test part 1")
assert(solution.part1(testInput), expected1)
println("> Passed")
}
if (execution.contains(ExecutionMode.Test2)) {
println("Test part 2")
assert(solution.part2(testInput), expected2)
println("> Passed")
println()
}
println("=================================")
println()
}
fun run() {
val input = readInput(name)
if (execution.contains(ExecutionMode.Exec1)) {
val elapsed1 = measureTime {
println("Part 1: " + solution.part1(input))
}
println("Elapsed: $elapsed1")
println()
}
if (execution.contains(ExecutionMode.Exec2)) {
val elapsed2 = measureTime {
println("Part 2: " + solution.part2(input))
}
println("Elapsed: $elapsed2")
println()
}
}
test()
run()
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 4,518 | aoc2022 | Apache License 2.0 |
src/main/kotlin/str/KMP.kt | yx-z | 106,589,674 | false | null | // KMP Algorithm for Pattern Matching
fun main(args: Array<String>) {
val kmp = KMP("aabacaabaabaaa", "aabaabaaa")
println(kmp.match())
kmp.pattern = "1"
println(kmp.match())
}
class KMP(var matching: String, pattern: String) {
var pattern: String = pattern
set(value) {
field = value
this.patternArray = buildPatternArray()
}
private var patternArray: Array<Int> = buildPatternArray()
private fun buildPatternArray(): Array<Int> {
val len = pattern.length
val arr = Array(len) { 0 }
var j = 0
var i = 1
while (i < len) {
when {
pattern[i] == pattern[j] -> {
arr[i] = j + 1
j++
i++
}
j != 0 -> j = arr[j - 1]
else -> {
arr[i] = 0
i++
}
}
}
return arr
}
fun match(): Boolean {
var i = 0
var j = 0
while (i < matching.length && j < pattern.length) {
when {
matching[i] == pattern[j] -> {
i++
j++
}
j != 0 -> j = patternArray[j - 1]
else -> i++
}
}
return j == pattern.length
}
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,014 | AlgoKt | MIT License |
src/main/kotlin/ctci/chaptertwo/SumLists.kt | amykv | 538,632,477 | false | {"Kotlin": 169929} | package ctci.chaptertwo
// 2.5 - page 95
// You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in
// reverse order, such that the 1's digit is at the head of the list. In Kotlin, write a function that adds the two
// numbers and returns the sum as a linked list. Not allowed to just convert the linked list to an integer.
fun main() {
val list1 = Node(9, null)
var current1 = list1
current1.next = Node(9, null)
current1 = current1.next!!
current1.next = Node(9, null)
val list2 = Node(1, null)
var current2 = list2
current2.next = Node(8, null)
current2 = current2.next!!
current2.next = Node(3, null)
val sumList = addLists(list1, list2)
var current = sumList
while (current != null) {
print("${current.value} ")
current = current.next
}
// should print "0 0 1 "
}
//This function takes two linked lists, each representing a number. It iterates through the two linked lists at the
// same time, adding the corresponding digits and the carry from the previous addition. If one of the lists is
// shorter than the other, it considers the missing digits as 0. If the final carry is greater than 0, it adds a new node with the carry value to the resulting list.
fun addLists(l1: Node?, l2: Node?): Node? {
var dummyHead = Node(0, null)
var current = dummyHead
var carry = 0
var p1 = l1
var p2 = l2
while (p1 != null || p2 != null) {
var x = if (p1 != null) p1.value else 0
var y = if (p2 != null) p2.value else 0
val sum = carry + x + y
carry = sum / 10
current.next = Node(sum % 10, null)
current = current.next!!
if (p1 != null) p1 = p1.next
if (p2 != null) p2 = p2.next
}
if (carry > 0) {
current.next = Node(carry, null)
}
return dummyHead.next
}
//It has O(max(n,m)) time complexity, where n and m are the number of digits in the two input lists.
// Because it iterates through both lists once, and performs a constant amount of operations for each digit.
//
//This solution has O(max(n,m)) space complexity because it creates a new linked list with max(n,m) elements. | 0 | Kotlin | 0 | 2 | 93365cddc95a2f5c8f2c136e5c18b438b38d915f | 2,235 | dsa-kotlin | MIT License |
letcode/src/main/java/daily/LeetCode154.kt | chengw315 | 343,265,699 | false | null | package daily
fun main() {
val solution = Solution154()
//1
val array = solution.minArray(intArrayOf(3, 4, 5, 1, 2))
//1
val array1 = solution.minArray(intArrayOf(1, 2, 3, 4, 5))
//5
val array2 = solution.minArray(intArrayOf(5, 15, 5, 5, 5))
//4
val array4 = solution.minArray(intArrayOf(5, 15, 4, 5, 5))
//1
val array3 = solution.minArray(intArrayOf(5, 5, 5, 1, 2))
}
class Solution154 {
fun minArray(numbers: IntArray): Int {
//未旋转
if (numbers[0] < numbers[numbers.size-1]) return numbers[0]
return lbs(numbers,0,numbers.size-1)
}
/**
* 向左二分查找 (left,right]
*/
fun lbs(numbers: IntArray,left:Int,right:Int):Int {
if(left>=right-1) return numbers[right]
val mid = (left+right)/2
return if(numbers[right] > numbers[mid]) lbs(numbers,left,mid)
else if(numbers[right] < numbers[mid]) lbs(numbers,mid,right)
else Math.min(lbs(numbers, left, mid),lbs(numbers, mid, right))
}
} | 0 | Java | 0 | 2 | 501b881f56aef2b5d9c35b87b5bcfc5386102967 | 1,030 | daily-study | Apache License 2.0 |
facebook/y2021/qual/c1.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package facebook.y2021.qual
private fun solve(): Int {
val n = readInt()
val c = readInts()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (v, u) = readInts().map { it - 1 }
nei[v].add(u)
nei[u].add(v)
}
fun dfs(v: Int, p: Int): Int {
return c[v] + ((nei[v] - p).maxOfOrNull { dfs(it, v) } ?: 0)
}
return c[0] + nei[0].map { dfs(it, 0) }.sorted().takeLast(2).sum()
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 659 | competitions | The Unlicense |
src/Day20.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | import java.util.LinkedList
enum class SignalType {
LOW, HIGH
}
typealias Signal = Triple<String, SignalType, String>
sealed class Module(val name: String, var next: List<String>) {
abstract fun handleSignal(input: Signal): List<Signal>
class Broadcaster(next: List<String>) : Module("broadcaster", next) {
override fun handleSignal(input: Signal): List<Signal> {
return next.map { Triple(name, SignalType.LOW, it) }
}
}
class FlipFlop(name: String, next: List<String>) : Module(name, next) {
private var isOn: Boolean = false
override fun handleSignal(input: Signal): List<Signal> {
val (_, st, _) = input
if (st == SignalType.HIGH)
return listOf()
isOn = !isOn
return next.map {
val signalType = if (isOn) SignalType.HIGH else SignalType.LOW
Triple(name, signalType, it)
}
}
}
class Conjunction(name: String, next: List<String>) : Module(name, next) {
private val srcMap = mutableMapOf<String, SignalType>()
fun setSource(source: List<String>) {
source.forEach { srcMap[it] = SignalType.LOW }
}
fun getSource() = srcMap.keys
override fun handleSignal(input: Signal): List<Signal> {
val (src, st, _) = input
srcMap[src] = st
val signalToSend = if (srcMap.values.all { it == SignalType.HIGH }) SignalType.LOW else SignalType.HIGH
return next.map { Triple(name, signalToSend, it) }
}
}
}
fun Input.buildCircuit(): Map<String, Module> {
val modules = this.map { line ->
val (src, tgt) = line.split(" -> ", limit = 2)
val next = tgt.split(",").map { it.trim() }
when (src) {
"broadcaster" -> Module.Broadcaster(next)
else -> {
when (src.first()) {
'%' -> Module.FlipFlop(src.drop(1), next)
'&' -> Module.Conjunction(src.drop(1), next)
else -> error("cannot happen")
}
}
}
}
val sourceMap = mutableMapOf<String, MutableSet<String>>()
modules.forEach { m ->
m.next.forEach { s ->
sourceMap.getOrPut(s) { mutableSetOf() }.add(m.name)
}
}
modules.filterIsInstance<Module.Conjunction>().forEach {
it.setSource(sourceMap[it.name]?.toList() ?: listOf())
}
return modules.associateBy { it.name }
}
fun main() {
fun part1(input: List<String>): Long {
val circuit = input.buildCircuit()
var highCount = 0L
var lowCount = 0L
val buttonCount = 1000
val queue = LinkedList<Signal>()
repeat(buttonCount) {
queue.add(Triple("button", SignalType.LOW, "broadcaster"))
while (queue.isNotEmpty()) {
val signal = queue.pop()
println("${signal.first} - ${signal.second} -> ${signal.third}")
if (signal.second == SignalType.HIGH)
highCount++
else lowCount++
val module = circuit[signal.third] ?: continue
queue.addAll(module.handleSignal(signal))
}
}
return highCount * lowCount
}
fun part2(input: List<String>): Long {
val circuit = input.buildCircuit()
val queue = LinkedList<Signal>()
var buttonCount = 0L
// so "rx" receives input from "hp", which is a conjunction.
// hence, all sources of "hp" must send HIGH in order for rx to receive LOW
val rxSource = (circuit["hp"] as? Module.Conjunction)?.getSource() ?: setOf()
val cycleCounts = mutableListOf<Long>()
while (cycleCounts.size < rxSource.size) {
buttonCount++
queue.add(Triple("button", SignalType.LOW, "broadcaster"))
while (queue.isNotEmpty()) {
val signal = queue.pop()
if (signal.first in rxSource && signal.second == SignalType.HIGH) {
println("${signal.first} sent ${signal.second} on button click $buttonCount")
cycleCounts.add(buttonCount)
}
val module = circuit[signal.third] ?: continue
queue.addAll(module.handleSignal(signal))
}
}
// Find LCM of cycle counts.
// i.e., 4 modules of our interest cycle to HIGH at each of these intervals
return cycleCounts.fold(1L) { acc, it -> lcm(acc, it) }
}
val input = readInput("Day20")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 4,675 | aoc-2023 | Apache License 2.0 |
src/main/day05/Day05.kt | FlorianGz | 573,204,597 | false | {"Kotlin": 8491} | package main.day05
import kotlinx.coroutines.*
import readInput
fun main() = runBlocking {
suspend fun part1(): String {
return getCode(reversed = true)
}
suspend fun part2(): String {
return getCode(reversed = false)
}
println(part1())
println(part2())
}
suspend fun getCode(reversed: Boolean): String = runBlocking {
val cratesInput = readInput("main/day05/day05")
val cratesMapDeferred = async { getInitialCratesMap(cratesInput) }
val instructionsDeferred = async { getInstructions(cratesInput) }
val cratesMap = cratesMapDeferred.await().toMutableMap()
val instructions = instructionsDeferred.await()
instructions.forEach { instruction ->
cratesMap[instruction.from]?.let {
val index = if(it.length - instruction.quantity < 0) 0 else it.length - instruction.quantity
val toExtract = it.substring(index, it.length)
cratesMap[instruction.from] = it.substring(0, index)
cratesMap[instruction.to] = cratesMap[instruction.to] + if (reversed) toExtract.reversed() else toExtract
}
}
cratesMap.toSortedMap().mapNotNull { it.value.lastOrNull() }.joinToString("")
}
fun getInitialCratesMap(cratesInput: List<String>): Map<Int, String> {
val crateRegexp = Regex("\\[([A-Z])\\]\\s*")
val cratesMap = mutableMapOf<Int, String>()
cratesInput.takeWhile { it.isNotBlank() }.map { it.chunked(4) }.map { items ->
items.forEachIndexed { index, input ->
if(crateRegexp.matches(input)) {
val matches = crateRegexp.find(input)!!.groupValues[1]
if(cratesMap[index] == null) cratesMap[index] = matches
else cratesMap[index] = matches + cratesMap[index]
}
}
}
return cratesMap
}
fun getInstructions(cratesInput: List<String>): List<Instructions> {
val instructionRegexp = Regex("move (\\d+) from (\\d+) to (\\d+)")
return cratesInput.mapNotNull { instruction ->
val match = instructionRegexp.find(instruction)
match?.let { matchResult ->
val (quantity, from, to) = matchResult.destructured.toList().map { it.toInt() }
Instructions(quantity = quantity, from = from - 1, to = to - 1)
}
}
}
| 0 | Kotlin | 0 | 0 | 58c9aa8fdec77c25a9d9945ca8e77ecd1170321b | 2,285 | aoc-kotlin-2022 | Apache License 2.0 |
src/Day08.kt | fonglh | 573,269,990 | false | {"Kotlin": 48950, "Ruby": 1701} | fun main() {
fun printForest(forest: Array<IntArray>) {
for(i in 0 until forest.size) {
for (j in 0 until forest[i].size) {
print(forest[i][j])
}
println()
}
}
fun buildForest(input: List<String>): Array<IntArray> {
var forest = Array(input.size) { IntArray(input[0].length) }
input.forEachIndexed { index, line ->
forest[index] = line.map { it.toString().toInt() }.toIntArray()
}
return forest
}
fun isTreeVisible(forest: Array<IntArray>, row: Int, col: Int): Boolean {
val treeHeight = forest[row][col]
var leftBlocked = false
var rightBlocked = false
var upBlocked = false
var downBlocked = false
// Consider refactoring with `all` function, but this manual looping made
// it much easier to adapt for part 2.
// Check to the left
for(currCol in col-1 downTo 0) {
if(forest[row][currCol] >= treeHeight) {
leftBlocked = true
break
}
}
// Check to the right
for(currCol in col+1 until forest[row].size) {
if(forest[row][currCol] >= treeHeight) {
rightBlocked = true
break
}
}
// Check up
for(currRow in row-1 downTo 0) {
if(forest[currRow][col] >= treeHeight) {
upBlocked = true
break
}
}
// Check down
for(currRow in row+1 until forest.size) {
if(forest[currRow][col] >= treeHeight) {
downBlocked = true
break
}
}
return !(leftBlocked && rightBlocked && upBlocked && downBlocked)
}
fun part1(input: List<String>): Int {
var forest = buildForest(input)
var totalVisible = 0
for (row in forest.indices) {
for(col in forest[row].indices) {
if (isTreeVisible(forest, row, col)) {
totalVisible++
}
}
}
return totalVisible
}
fun scenicScore(forest: Array<IntArray>, row: Int, col: Int): Int {
val treeHeight = forest[row][col]
var leftView = 0
var rightView = 0
var upView = 0
var downView = 0
// Check to the left
for(currCol in col-1 downTo 0) {
leftView++
if(forest[row][currCol] >= treeHeight) {
break
}
}
// Check to the right
for(currCol in col+1 until forest[row].size) {
rightView++
if(forest[row][currCol] >= treeHeight) {
break
}
}
// Check up
for(currRow in row-1 downTo 0) {
upView++
if(forest[currRow][col] >= treeHeight) {
break
}
}
// Check down
for(currRow in row+1 until forest.size) {
downView++
if(forest[currRow][col] >= treeHeight) {
break
}
}
return leftView * rightView * upView * downView
}
fun part2(input: List<String>): Int {
var forest = buildForest(input)
var highestScenicScore = 0
for (row in forest.indices) {
for(col in forest[row].indices) {
val currScenicScore = scenicScore(forest, row, col)
if (currScenicScore > highestScenicScore) {
highestScenicScore = currScenicScore
}
}
}
return highestScenicScore
}
// 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 | ef41300d53c604fcd0f4d4c1783cc16916ef879b | 3,967 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day20.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2021/day/20",
date = Date(day = 20, year = 2021)
)
class Day20(val input: List<String>) : Puzzle {
private val enhancement = input.first().toCharArray().map { if (it == '#') 1 else 0 }
private val image = Image.parse(input.drop(2))
override fun partOne() =
(0 until 2).fold(image) { i, _ -> i.enhance(enhancement) }.litPixels()
override fun partTwo() =
(0 until 50).fold(image) { i, _ -> i.enhance(enhancement) }.litPixels()
data class Image(val data: List<List<Int>>, val default: Int) {
private val height = data.size
private val width = data.first().size
companion object {
fun parse(lines: List<String>): Image {
val data = lines.map { l -> l.map { if (it == '#') 1 else 0 } }
return Image(data, 0)
}
}
fun enhance(mapping: List<Int>) =
Image(
data = (-1..height).map { y ->
(-1..width).map { x ->
Point(x, y)
.neighborsAndSelf()
.map { at(it) }
.joinToString("")
.toInt(2)
.let { mapping[it] }
}
}, default =
if (mapping[0] == 1) (1 - default) else default
)
fun litPixels() = data.sumOf { it.sum() }
private fun at(point: Point): Int {
if (point.x in 0 until width && point.y >= 0 && point.y < height) {
return data[point.y][point.x]
}
return default
}
override fun toString(): String =
data.joinToString("\n") { row ->
row.map { if (it == 1) '#' else '.' }.joinToString("")
}
}
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 1,930 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/solutions/Day03.kt | chutchinson | 573,586,343 | false | {"Kotlin": 21958} | class Day03 : Solver {
override fun solve (input: Sequence<String>) {
val rucksacks = input.toList()
println(first(rucksacks))
println(second(rucksacks))
}
fun priority (ch: Char): Int = when(ch) {
in 'A'..'Z' -> ch.code - 64 + 26
in 'a'..'z' -> ch.code - 96
else -> 0
}
fun first (rucksacks: Iterable<String>) = rucksacks
// build compartments
.map { it.chunked(it.length / 2) }
// find intersection of letters in first compartment with second compartment
.map { it[0].toSet() intersect it[1].toSet() }
.map { it.first() }
// calculate priorities and sum
.map(::priority)
.sum()
fun second (rucksacks: Iterable<String>) = rucksacks
// select groups of 3 rucksacks
.chunked(3)
// find intersection of all 3 rucksacks in each group
.map { chunk -> chunk.map { it.toSet() }}
.map { chunk -> chunk.reduce { all, set -> all intersect set }}
.flatten()
// calculate priorities and sum
.map(::priority)
.sum()
} | 0 | Kotlin | 0 | 0 | 5076dcb5aab4adced40adbc64ab26b9b5fdd2a67 | 1,116 | advent-of-code-2022 | MIT License |
2022/Day25.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
val numbers = mapOf(
2 to '2',
1 to '1',
0 to '0',
-1 to '-',
-2 to '=',
)
fun decodeDigit(c: Char) = numbers.entries.find { it.value == c }!!.key
fun encodeDigit(x: Int) = numbers[x]!!
fun decode(s: String): Long {
var p = 1L
var res = 0L
for (i in s.indices.reversed()) {
res += p*decodeDigit(s[i])
p *= 5
}
return res
}
fun encode(x: Long): String {
val a = mutableListOf<Long>(0)
var p = 1L
while (2*p + a.last() < x) {
a.add(2*p + a.last())
p *= 5
}
val res = StringBuilder()
var x1 = x
while (p > 0) {
val b = if (x1 >= 0) {
(x1 + a.last()) / p
} else {
(x1 - a.last()) / p
}
res.append(encodeDigit(b.toInt()))
x1 -= b * p
p /= 5L
a.removeLast()
}
assert(x1 == 0L)
return res.toString()
}
val input = readInput("Day25")
var res1 = 0L
for (s in input) {
val n = decode(s)
res1 += n
}
println(res1)
println(encode(res1))
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,237 | advent-of-code-kotlin | Apache License 2.0 |
codeforces/round573/TokitsukazeMadjong.kt | grine4ka | 183,575,046 | false | {"Kotlin": 98723, "Java": 28857, "C++": 4529} | package codeforces.round573
// https://codeforces.com/contest/1191/problem/B
fun main(args: Array<String>) {
val listM = arrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0)
val listP = arrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0)
val listS = arrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0)
val input = readLine()!!.split(" ").map {
Card(it[0].toString().toInt(), it[1].toString())
}
input.forEach {
when(it.type) {
"m" -> listM[it.number-1]++
"p" -> listP[it.number-1]++
"s" -> listS[it.number-1]++
}
}
val koutsuM = listM.max()!!
val shuntsuM = shuntsu(listM)
if (koutsuM >= 3 || shuntsuM >= 3) {
println("0")
return
}
val koutsuP = listP.max()!!
val shuntsuP = shuntsu(listP)
if (koutsuP >= 3 || shuntsuP >= 3) {
println("0")
return
}
val koutsuS = listS.max()!!
val shuntsuS = shuntsu(listS)
if (koutsuS >= 3 || shuntsuS >= 3) {
println("0")
return
}
if (koutsuM >= 2 || shuntsuM >= 2 ||
koutsuS >= 2 || shuntsuS >= 2 ||
koutsuP >= 2 || shuntsuP >= 2) {
println("1")
return
}
println("2")
}
// return the number of subsequence > 0
fun shuntsu(list: Array<Int>): Int {
val seq = ArrayList<Triple<Int, Int, Int>>()
for (i in 0 until 7) {
seq.add(Triple(list[i], list[i+1], list[i+2]))
}
var one = 0
var two = 0
for (triple in seq) {
if (triple.first > 0 && triple.second > 0 && triple.third > 0) {
return 3
} else if (triple.first > 0 && triple.second > 0) {
two++
} else if (triple.first > 0 && triple.third > 0) {
two++
} else if (triple.second > 0 && triple.third > 0) {
two++
} else if (triple.first > 0 || triple.second > 0 || triple.third > 0) {
one++
}
}
if (two > 0) return 2
if (one > 0) return 1
return 0
}
class Card(val number: Int, val type: String) | 0 | Kotlin | 0 | 0 | c967e89058772ee2322cb05fb0d892bd39047f47 | 2,026 | samokatas | MIT License |
src/main/kotlin/dev/austinzhu/algods/containers/tree/Trie.kt | AustinZhu | 287,033,539 | false | null | package dev.austinzhu.algods.containers.tree
import dev.austinzhu.algods.containers.util.NAryTreePrinter
import dev.austinzhu.algods.containers.util.Operation
import kotlin.math.sqrt
import kotlin.random.Random
class Trie<T> : AbstractTrie<T>() {
open inner class Node(var value: T? = null) : Tree.Node<String, T, Node> {
val next = arrayOfNulls<Node>(Char.MAX_VALUE.code)
override fun getChildren(): List<Node?> {
class NodeWrapper(val char: Char, val node: Node?) : Node() {
override fun toString(): String {
if (node == null) return ""
return if (node.value == null) "'$char'" else "'$char': ${node.value}"
}
override fun getChildren(): List<NodeWrapper?> {
return if (node == null) emptyList() else listOf(*node.next).indices.map {
if (node.next[it] != null) NodeWrapper(it.toChar(), node.next[it]) else null
}
}
}
return NodeWrapper('\u0000', this).getChildren()
}
override fun hasAll() = next.all { it != null }
override fun hasNone() = next.all { it == null }
override fun toString() = "''"
}
companion object {
fun init(size: Int, bound: Int): Trie<Int> {
val capacity = Random.nextInt(size)
val trie = Trie<Int>()
val keys = Array(capacity) { it.toString() }
val alphabets = ('a'..'z').toList()
val prefixes = Array(sqrt(capacity.toFloat()).toInt()) {
(1..capacity)
.map { Random.nextInt(0, alphabets.size) }
.map(alphabets::get)
.joinToString("")
}
for (k in keys) {
val i = Random.nextInt(prefixes.size)
trie.add(prefixes[i] + k, Random.nextInt(bound))
}
return trie
}
}
@Operation
override fun add(idx: String, value: T) {
if (root == null) {
root = Node()
}
var node = root!!
for (c in idx) {
val code = c.code
if (node.next[code] == null) {
node.next[code] = Node()
}
node = node.next[code]!!
}
node.value = value
}
@Operation
override fun get(idx: String): T {
var node = root ?: throw NoSuchElementException()
for (c in idx) {
val code = c.code
node = node.next[code] ?: throw NoSuchElementException()
}
return node.value ?: throw NoSuchElementException()
}
@Operation
override fun set(idx: String, value: T) {
var last = root ?: throw NoSuchElementException()
for (c in idx) {
last = last.next[c.code] ?: throw NoSuchElementException()
}
last.value = value
}
@Operation
override fun delete(idx: String): T {
var del: T? = null
fun helper(node: Node? = root, depth: Int = 0): Node? {
if (node == null) return null
if (depth == idx.length) {
del = node.value
node.value = null
} else {
val code = idx[depth].code
node.next[code] = helper(node.next[code], depth + 1)
}
// remove subtrie if it is empty
if (node.value != null) {
return node
}
for (n in node.next) {
if (n != null) {
return n
}
}
return null
}
helper()
return del ?: throw NoSuchElementException()
}
@Operation
fun keysWithPrefix(prefix: String): ArrayList<String> {
val res = ArrayList<String>()
fun collect(node: Node?, prefixChars: MutableList<Char> = prefix.toMutableList()) {
if (node == null) return
if (node.value != null) {
val str = prefixChars.fold("", String::plus)
res.add(str)
}
for (c in 0 until 256) {
prefixChars.add(c.toChar())
collect(node.next[c], prefixChars)
prefixChars.removeLast()
}
}
var last: Node? = root
for (c in prefix) {
if (last == null) return res
val code = c.code
last = last.next[code]
}
collect(last)
return res
}
override fun toString(): String {
return NAryTreePrinter(root).toString()
}
}
| 0 | Kotlin | 0 | 0 | e0188bad8a6519e571bdc3ee21c41764c1271f10 | 4,655 | AlgoDS | MIT License |
src/main/kotlin/day11/solution.kt | bukajsytlos | 433,979,778 | false | {"Kotlin": 63913} | package day11
import java.io.File
fun main() {
val lines = File("src/main/kotlin/day11/input.txt").readLines()
val mapSize = lines.size
val energyLevelsMap: Array<IntArray> = Array(mapSize) { i -> lines[i].map { it.digitToInt() }.toIntArray() }
val dumboOctopuses: MutableMap<Coordinate, DumboOctopus> = mutableMapOf()
for (y in energyLevelsMap.indices) {
for (x in energyLevelsMap[y].indices) {
val coordinate = Coordinate(x, y)
val dumboOctopus = DumboOctopus(coordinate, energyLevelsMap[y][x])
dumboOctopuses[coordinate] = dumboOctopus
if (y > 0) dumboOctopuses.getValue(Coordinate(x, y - 1)).addAdjacent(dumboOctopus)
if (x > 0) dumboOctopuses.getValue(Coordinate(x - 1, y)).addAdjacent(dumboOctopus)
if (x > 0 && y > 0) dumboOctopuses.getValue(Coordinate(x - 1, y - 1)).addAdjacent(dumboOctopus)
if (x < mapSize - 1 && y > 0) dumboOctopuses.getValue(Coordinate(x + 1, y - 1)).addAdjacent(dumboOctopus)
}
}
var flashCount = 0
for (step in 1..100) {
dumboOctopuses.values.forEach { it.increaseChargeLevel() }
flashCount += dumboOctopuses.values.count { it.flash() }
}
println(flashCount)
var stepAllFlashed = 100
var allFlashed = false
while(!allFlashed) {
stepAllFlashed++
dumboOctopuses.values.forEach { it.increaseChargeLevel() }
allFlashed = dumboOctopuses.values.count { it.flash() } == dumboOctopuses.size
}
println(stepAllFlashed)
}
class DumboOctopus(val coordinate: Coordinate, var energyLevel: Int) {
private val adjacents: MutableSet<DumboOctopus> = mutableSetOf()
fun increaseChargeLevel() {
energyLevel++
if (energyLevel == FLASH_ENERGY_LEVEL) {
adjacents.forEach { it.increaseChargeLevel() }
}
}
fun addAdjacent(adjacent: DumboOctopus) {
if (adjacent !in adjacents) {
adjacents.add(adjacent)
adjacent.addAdjacent(this)
}
}
fun flash(): Boolean {
val charged = energyLevel >= FLASH_ENERGY_LEVEL
if (charged) energyLevel = 0
return charged
}
companion object {
const val FLASH_ENERGY_LEVEL = 10
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as DumboOctopus
if (coordinate != other.coordinate) return false
return true
}
override fun hashCode(): Int {
return coordinate.hashCode()
}
override fun toString(): String {
return "DumboOctopus(coordinate=$coordinate, chargeLevel=$energyLevel)"
}
}
data class Coordinate(val x: Int, val y: Int) | 0 | Kotlin | 0 | 0 | f47d092399c3e395381406b7a0048c0795d332b9 | 2,779 | aoc-2021 | MIT License |
semestr.06/ТРСиПВ/bellman/src/main/kotlin/bellman/graph/algorithm/bellmanFord.kt | justnero | 43,222,066 | false | null | package bellman.graph.algorithm
import bellman.graph.Adjacency
import bellman.graph.AdjacencyList
import bellman.graph.INFINITE
import bellman.graph.Util.AdjacencyUtil.destination
import bellman.graph.Util.AdjacencyUtil.source
import bellman.graph.Util.AdjacencyUtil.weight
fun bellmanFord(adjacencyList: AdjacencyList,
sourceVertex: Int,
vertexNumber: Int,
edgeNumber: Int = adjacencyList.size): IntArray {
val distance = IntArray(vertexNumber, { INFINITE }).apply { this[sourceVertex] = 0 }
for (i in 0..vertexNumber - 1) {
if (!adjacencyList.relaxAll(distance))
return distance
}
return distance
}
inline fun AdjacencyList.relaxAll(distance: IntArray, from: Int = 0, to: Int = lastIndex) =
(from..to).map { get(it).relax(distance) }.onEach { if (it) return@relaxAll true }.let { false }
fun Adjacency.relax(distance: IntArray): Boolean {
val lastValue = distance[destination]
if (distance[source] < INFINITE) {
distance[destination] =
minOf(distance[destination].toLong(), distance[source].toLong() + weight).toInt()
}
val isRelaxed = lastValue != distance[destination]
return isRelaxed
}
| 0 | Java | 6 | 16 | 14f58f135e57475b98826c4128b2b880b6a2cb9a | 1,239 | university | MIT License |
src/main/kotlin/processor/Matrix.kt | joseluisgs | 446,332,521 | true | {"HTML": 42079, "Java": 16420, "Kotlin": 10815, "JavaScript": 5252, "CSS": 3780} | package processor
import kotlin.system.exitProcess
fun main() {
doMenuActions()
}
/**
* Menu and Actions
* @param data List of data
* @param index Index of data
*/
private fun doMenuActions() {
do {
val menu = readMenuOption()
when (menu) {
0 -> exit()
1 -> addMatrices()
2 -> multiplyByConstant()
3 -> multiplyMatrices()
4 -> transposeMatrix()
5 -> determinantMatrix()
6 -> inverseMatrix()
}
} while (menu != 0)
}
/**
* Inverse of a Matrix
*/
fun inverseMatrix() {
val m = readMatrix("")
inverseMatrix(m)
}
/**
* Calculate the inverse of a Matrix
*/
fun inverseMatrix(mat: Array<Array<Double>>) {
/*
If det(A) != 0
A-1 = adj(A)/det(A)
Else
"Inverse doesn't exist"
*/
val det = determinantMatrix(mat, mat.size, mat.size)
if (det != 0.0) {
val adj = Array(mat.size) { Array(mat.size) { 0.0 } }
adjoint(mat, adj, mat.size)
// Find Inverse using formula "inverse(A) = adj(A)/det(A)"
// Find Inverse using formula "inverse(A) = adj(A)/det(A)"
val inverse = Array(mat.size) { Array(mat.size) { 0.0 } }
for (i in mat.indices)
for (j in mat.indices)
inverse[i][j] = adj[i][j] / det
printMatrix(inverse)
} else {
println("This matrix doesn't have an inverse.")
}
}
/**
* Determinat of a Matrix
*/
fun determinantMatrix() {
val m = readMatrix("")
val determinant = determinantMatrix(m, m.size, m.size)
println("The result is:")
println(determinant)
}
/**
* Function to get cofactor (sub matrix) of mat(p)(q) in temp[][]. n is current dimension of mat[][]
* @param mat Matrix
* @param temp Matrix
* @param p Row
* @param q Column
* @param n Size of matrix
*/
fun getCofactor(
mat: Array<Array<Double>>, temp: Array<Array<Double>>,
p: Int, q: Int, n: Int
) {
var i = 0
var j = 0
// Looping for each element of
// the matrix
for (row in 0 until n) {
for (col in 0 until n) {
// Copying into temporary matrix
// only those element which are
// not in given row and column
if (row != p && col != q) {
temp[i][j++] = mat[row][col]
// Row is filled, so increase
// row index and reset col
// index
if (j == n - 1) {
j = 0
i++
}
}
}
}
}
/**
* Calculate Determinant of a Matrix Recursive
* @param mat Matrix
* @param n Size of actual Matrix
* @param Size of Matrix Original Matrix
* @return Determinant of Matrix
*/
fun determinantMatrix(mat: Array<Array<Double>>, n: Int, Size: Int): Double {
var det = 0.0 // Initialize result
// Base case : if matrix contains single
// element
if (n == 1) return mat[0][0]
// To store cofactors
val temp = Array(Size) { Array(Size) { 0.0 } }
// To store sign multiplier
var sign = 1
// Iterate for each element of first row
for (f in 0 until n) {
// Getting Cofactor of mat[0][f]
getCofactor(mat, temp, 0, f, n)
det += (sign * mat[0][f] * determinantMatrix(temp, n - 1, Size))
// terms are to be added with
// alternate sign
sign = -sign
}
return det
}
/**
* Get adjoint of A(N)(N) in adj(N)(N).
*/
fun adjoint(mat: Array<Array<Double>>, adj: Array<Array<Double>>, Size: Int) {
if (Size == 1) {
adj[0][0] = 1.0
return
}
// temp is used to store cofactors of A[][]
var sign = 1
val temp = Array(Size) { Array(Size) { 0.0 } }
for (i in 0 until Size) {
for (j in 0 until Size) {
// Get cofactor of A[i][j]
getCofactor(mat, temp, i, j, Size)
// sign of adj[j][i] positive if sum of row
// and column indexes is even.
sign = if ((i + j) % 2 == 0) 1 else -1
// Interchanging rows and columns to get the
// transpose of the cofactor matrix
adj[j][i] = sign * determinantMatrix(temp, Size - 1, Size)
}
}
}
/**
* Menu Options Transpose Matrix
*/
fun transposeMatrix() {
var menu = 0
do {
menu = readMenuTranposeOption()
when (menu) {
1 -> {
transposeMain()
menu = 0
}
2 -> {
transposeSide()
menu = 0
}
3 -> {
transposeVertical()
menu = 0
}
4 -> {
transposeHorizontal()
menu = 0
}
}
} while (menu != 0)
doMenuActions()
}
/**
* Trasnpose Horizontal Matrix
*/
fun transposeHorizontal() {
val m = readMatrix("")
transposeHorizontal(m)
}
/**
* Trasnpose Horizontal Matrix
* @param m Matrix
*/
fun transposeHorizontal(mat: Array<Array<Double>>) {
val mT = Array(mat[0].size) { Array(mat.size) { 0.0 } }
val n = mat.size
for (i in 0 until n) {
for (j in 0 until n) {
mT[(n - 1) - i][j] = mat[i][j]
}
}
println("Transpose Vertical")
printMatrix(mT)
}
/**
* Transpose Vertical Matrix
*/
fun transposeVertical() {
val m = readMatrix("")
transposeVertical(m)
}
/**
* Tranpose Vertical Matrix
* @param m Matrix
*/
fun transposeVertical(mat: Array<Array<Double>>) {
val mT = Array(mat[0].size) { Array(mat.size) { 0.0 } }
val n = mat.size
for (i in 0 until n) {
for (j in 0 until n) {
mT[i][(n - 1) - j] = mat[i][j]
}
}
println("Transpose Vertical")
printMatrix(mT)
}
/**
* Tranpose Side Diagonal
*/
fun transposeSide() {
val m = readMatrix("")
transposeSide(m)
}
/**
* Tranpose Side Diagonal
* @param m Matrix
*/
fun transposeSide(mat: Array<Array<Double>>) {
val mT = Array(mat[0].size) { Array(mat.size) { 0.0 } }
val n = mat.size
for (i in mat.indices) {
for (j in 0 until mat[0].size) {
mT[(n - 1) - j][(n - 1) - i] = mat[i][j]
}
}
printMatrix(mT)
}
/**
* Transpose Matrix Main Diagonal
*/
fun transposeMain() {
val m = readMatrix("")
transposeMain(m)
}
/**
* Transpose Matrix Side Diagonal
*
*/
fun transposeMain(mat: Array<Array<Double>>) {
val mT = Array(mat[0].size) { Array(mat.size) { 0.0 } }
for (i in mat.indices) {
for (j in 0 until mat[0].size) {
mT[j][i] = mat[i][j]
}
}
printMatrix(mT)
}
/**
* Reads Menu Transpose Matrix
* @return Menu option
*/
fun readMenuTranposeOption(): Int {
var option: Int
do {
println("1. Main diagonal")
println("2. Side diagonal")
println("3. Vertical line")
println("4. Horizontal line")
print("Your choice: ")
option = readLine()!!.toIntOrNull() ?: -1
if (option !in 1..4) {
println("Incorrect option! Try again.")
}
} while (option !in 1..4)
return option
}
/**
* Multiply Matrices
*/
fun multiplyMatrices() {
val m1 = readMatrix("first")
val m2 = readMatrix("second")
multiplayMatrices(m1, m2)
}
/**
* Multiply Matrices
* @param m1 First Matrix
* @param m2 Second Matrix
*/
fun multiplayMatrices(m1: Array<Array<Double>>, m2: Array<Array<Double>>) {
// m1. columns == m2.rows
if (m1[0].size != m2.size) {
println("The operation cannot be performed.")
} else {
//
val m3 = Array(m1.size) { Array(m2[0].size) { 0.0 } }
for (i in m1.indices) {
for (j in 0 until m2[0].size) {
for (k in m2.indices) {
m3[i][j] += m1[i][k] * m2[k][j]
}
}
}
// imprimimos la matriz resultado
printMatrix(m3)
}
}
/**
* Multiply matrix by constant
*/
fun multiplyByConstant() {
val m = readMatrix("")
val c = readConstant()
matrixByNumber(m, c)
}
/**
* Reads the constant
*/
fun readConstant(): Double {
var c: Double
do {
print("Enter constant: ")
c = readLine()!!.toDoubleOrNull() ?: Double.MAX_VALUE
} while (c == Double.MAX_VALUE)
return c
}
/**
* Add Matrices
*/
fun addMatrices() {
val m1 = readMatrix("first")
val m2 = readMatrix("second")
addMatrices(m1, m2)
}
/**
* Reads Menu
* @return Menu option
*/
fun readMenuOption(): Int {
var option: Int
do {
println("1. Add matrices")
println("2. Multiply matrix by a constant")
println("3. Multiply matrices")
println("4. Transpose matrix")
println("5. Calculate a determinant")
println("6. Inverse matrix")
println("0. Exit")
print("Your choice: ")
option = readLine()!!.toIntOrNull() ?: -1
if (option !in 0..6) {
println("Incorrect option! Try again.")
}
} while (option !in 0..6)
return option
}
/**
* Exits the program.
*/
fun exit() {
exitProcess(0)
}
/**
* Multiply matrix by number
* @param m Matrix
* @param c Number
*/
fun matrixByNumber(matrix: Array<Array<Double>>, c: Double) {
val res = Array(matrix.size) { Array(matrix[0].size) { 0.0 } }
for (i in matrix.indices) {
for (j in 0 until matrix[i].size) {
res[i][j] = c * matrix[i][j]
}
}
printMatrix(res)
}
/**
* Print a Matrix
* @param m Matrix
*/
fun printMatrix(m: Array<Array<Double>>) {
// println()
println("The result is: ")
for (i in m.indices) {
for (j in m[i].indices) {
print("${m[i][j]} ")
}
println()
}
}
/**
* Add two matrices
* @param m1 first matrix
* @param m2 second matrix
*/
fun addMatrices(m1: Array<Array<Double>>, m2: Array<Array<Double>>) {
if (m1.size != m2.size || m1[0].size != m2[0].size) {
println("The operation cannot be performed.")
} else {
val m3 = Array(m1.size) { Array(m1[0].size) { 0.0 } }
for (i in m1.indices) {
for (j in m1[i].indices) {
m3[i][j] = m1[i][j] + m2[i][j]
}
}
// imprimimos la matriz resultado
printMatrix(m3)
}
}
/**
* Read a matrix from the console
* @return a matrix
*/
fun readMatrix(type: String): Array<Array<Double>> {
print("Enter size of $type matrix: ")
val (f, c) = readLine()!!.split(" ").map { it.toInt() }
val matrix = Array(f) { Array(c) { 0.0 } }
println("Enter $type matrix: ")
for (i in 0 until f) {
val line = readLine()!!.split(" ").map { it.toDouble() }
for (j in 0 until c) {
matrix[i][j] = line[j]
}
}
return matrix
}
| 0 | HTML | 1 | 1 | b0d49e42c3e40b9cdd193e07169b25075a06f409 | 10,815 | Kotlin-NumericMatrixProcessor | MIT License |
solutions/src/WaysToMakeFairArray.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} | /**
* https://leetcode.com/problems/ways-to-make-a-fair-array/
*
* Got correct big O(N) complexity but timeout still reached
*/
class WaysToMakeFairArray {
fun waysToMakeFair(nums: IntArray): Int {
var sumEven = 0
var sumOdd = 0
val sumEvenAscending = mutableListOf<Int>()
val sumOddAscending = mutableListOf<Int>()
val sumEvenDescending = mutableListOf<Int>()
val sumOddDescending = mutableListOf<Int>()
for (i in nums.indices) {
if (i % 2 == 0) {
sumEven+=nums[i]
}
else {
sumOdd+=nums[i]
}
sumEvenAscending.add(sumEven)
sumOddAscending.add(sumOdd)
}
sumEven = 0
sumOdd = 0
for (i in nums.lastIndex downTo 0) {
if (i % 2 == 0) {
sumEven+=nums[i]
}
else {
sumOdd+=nums[i]
}
sumEvenDescending.add(0,sumEven)
sumOddDescending.add(0,sumOdd)
}
var ways = 0
if (nums.size == 1) {
return 1
}
for (i in nums.indices) {
if (i == 0) {
if (sumEvenDescending[i+1] == sumOddDescending[i+1]) {
ways++
}
}
else if (i == nums.lastIndex) {
if (sumEvenAscending[i-1] == sumOddAscending[i-1]) {
ways++
}
}
else {
val newOddSum = sumOddAscending[i-1]+sumEvenDescending[i+1]
val newEvenSum = sumEvenAscending[i-1]+sumOddDescending[i+1]
if (newEvenSum == newOddSum) {
ways++
}
}
}
return ways
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,821 | leetcode-solutions | MIT License |
src/main/kotlin/de/consuli/aoc/year2022/days/Day10.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2022.days
import de.consuli.aoc.common.Day
class Day10 : Day(10, 2022) {
override fun partOne(testInput: Boolean): Int {
return intArrayOf(20, 60, 100, 140, 180, 220).sumOf { mapInputToCpuCycles(testInput).getSignalStrength(it) }
}
override fun partTwo(testInput: Boolean): String {
val cpu = mapInputToCpuCycles(testInput)
var outputString = ""
(1..240).forEach { currentPixel ->
val valueAtCurrentCycle = cpu.cycles.elementAt(currentPixel - 1).value
outputString += if ((currentPixel) % 40 in (valueAtCurrentCycle)..(valueAtCurrentCycle + 2)) {
"#"
} else {
"."
}
}
return outputString.chunked(40).joinToString("\n", "\n")
}
private fun mapInputToCpuCycles(testInput: Boolean): CPU {
val cpu = CPU()
getInput(testInput).forEach { line ->
if (line.trim().contains(" ")) {
val (_, value) = line.split(' ')
cpu.addX(value.toInt())
} else if (line.trim() == "noop") {
cpu.noop()
}
}
return cpu
}
}
internal class CPU {
internal var registerValue: Int = 1
var cycles: Iterable<IndexedValue<Int>> = ArrayList<Int>().withIndex()
private var currentCycle: Int = 1
fun addX(value: Int) {
cycles = cycles.plusElement(IndexedValue(currentCycle++, registerValue))
cycles = cycles.plusElement(IndexedValue(currentCycle++, registerValue))
registerValue += value
}
fun noop() {
cycles = cycles.plusElement(IndexedValue(currentCycle++, registerValue))
}
fun getSignalStrength(cycleNumber: Int): Int {
return cycles.elementAt(cycleNumber - 1).value * cycleNumber
}
}
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 1,831 | advent-of-code | Apache License 2.0 |
src/main/kotlin/exs/FunWithVowels.kt | alexaugustobr | 289,400,808 | false | {"Kotlin": 16766, "Java": 861} |
val vowelList = listOf<Char>('a', 'e', 'i', 'o', 'u')
fun main(args: Array<String>) {
val vowel = readLine()!!
//val vowel = "aeiouaeiouaeiouaaeeiioouu"
println(longestSubsequence(vowel))
}
fun longestSubsequence(searchVowel: String): Int {
val chars = searchVowel.toCharArray()
val lastIndex = chars.size
var initialIndex = 0
var lastLongestSequence = 0;
while (initialIndex < lastIndex) {
var curretLongestSequence = 0
var currentVowelIndex = 0
for (index in initialIndex until lastIndex) {
if(isVowel(chars[index])) {
val isTheSameVowel = vowelList[currentVowelIndex] == chars[index]
val isNextSequence = currentVowelIndex < vowelList.size - 1
&& vowelList[currentVowelIndex+1] == chars[index]
if (isTheSameVowel) {
curretLongestSequence++
} else if (isNextSequence) {
currentVowelIndex++
curretLongestSequence++
}
}
}
initialIndex += 1
if (curretLongestSequence > lastLongestSequence) lastLongestSequence = curretLongestSequence
}
return lastLongestSequence
}
fun isVowel(c: Char): Boolean {
return vowelList.contains(c)
} | 0 | Kotlin | 0 | 0 | c70e56d67f44f57053e270a917028e04c2ea2da0 | 1,113 | kotlin-exercises | MIT License |
src/main/kotlin/days/Day15.kt | TheMrMilchmann | 433,608,462 | false | {"Kotlin": 94737} | /*
* Copyright (c) 2021 <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 days
import utils.*
import java.util.*
fun main() {
val costs = readInput().map { it.toList().map(Char::digitToInt) }.toGrid()
fun Grid<Int>.calculateCost(start: GridPos, dest: GridPos): Int {
fun flatIndexOf(pos: GridPos) =
(pos.y.intValue * width) + pos.x.intValue
val risks = IntArray(positions.size) { Int.MAX_VALUE }
risks[flatIndexOf(start)] = 0
val queue = PriorityQueue<Pair<GridPos, Int>>(compareBy { (_, priority) -> priority })
queue.add(start to 0)
while (queue.isNotEmpty()) {
val (pos, _) = queue.remove()
val index = flatIndexOf(pos)
if (pos == dest) return risks[index]
for (vPos in getAdjacentPositions(pos)) {
val vIndex = flatIndexOf(vPos)
val alt = risks[index] + this[vPos]
if (alt < risks[vIndex]) {
risks[vIndex] = alt
queue.add(vPos to alt)
}
}
}
error("Cost calculation aborted unexpectedly")
}
fun part1() = costs.calculateCost(start = costs.positions.first(), costs.positions.last())
fun part2(): Int {
val actualGrid = Grid(costs.width * 5, costs.height * 5) { pos ->
val increase = (pos.x.intValue / costs.width) + (pos.y.intValue / costs.height)
((costs[pos.x % costs.width, pos.y % costs.height] + increase - 1) % 9) + 1
}
return actualGrid.calculateCost(start = actualGrid.positions.first(), actualGrid.positions.last())
}
println("Part 1: ${part1()}")
println("Part 2: ${part2()}")
} | 0 | Kotlin | 0 | 1 | dfc91afab12d6dad01de552a77fc22a83237c21d | 2,775 | AdventOfCode2021 | MIT License |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem024.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
import dev.mikeburgess.euler.common.factorial
/**
* Problem 24
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
*
* 012 021 102 120 201 210
*
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
*/
class Problem024 : Problem {
override fun solve(): Long {
val digits = (0..9).toMutableList()
var index = 999_999
var result = 0L
while (digits.size > 1) {
val temp = factorial(digits.size - 1L).toInt()
val i = index / temp
index -= (i * temp)
result = result * 10 + digits.removeAt(i)
}
return result * 10 + digits[0]
}
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 969 | project-euler | MIT License |
kotlin/src/main/kotlin/com/pbh/soft/day6/Day6Solver.kt | phansen314 | 579,463,173 | false | {"Kotlin": 105902} | package com.pbh.soft.day6
import cc.ekblad.konbini.*
import com.pbh.soft.common.Solver
import com.pbh.soft.common.parsing.ParsingUtils.onSuccess
import com.pbh.soft.day6.Parsing.inputP
import com.pbh.soft.day6.Parsing.part2P
import mu.KLogging
object Day6Solver : Solver, KLogging() {
override fun solveP1(text: String): String = inputP.parse(text).onSuccess { races ->
// -t^2 + 7t - 9 = 0
// a=-1,b=49787980,c=-298118510661181
val answer = races.asSequence()
.map { race ->
(0..race.time).asSequence()
.map { t -> t * (race.time - t) }
.filter { it > race.recordDistance }
.count()
}
.fold(1) { a, b -> a * b }
return answer.toString()
}
override fun solveP2(text: String): String = part2P.parse(text).onSuccess { (time, recordDistance) ->
println(6961001L-42827000L)
val answer = (0..time).asSequence()
.map { t -> t * (time - t) }
.filter { it > recordDistance }
.count()
return answer.toString()
}
}
object Parsing {
val intP = integer.map(Long::toInt)
val inputP = parser {
string("Time:"); whitespace1();
val times = chain(intP, whitespace1).terms; whitespace1();
string("Distance:"); whitespace1();
val distances = chain(intP, whitespace1).terms;
times.zip(distances).map { (t, d) -> Race(t, d) }
}
val part2P = parser {
string("Time:"); whitespace1();
val time = chain(cc.ekblad.konbini.regex("[0-9]+"), whitespace1).terms.joinToString("").toLong(); whitespace1();
string("Distance:"); whitespace1();
val distance = chain(cc.ekblad.konbini.regex("[0-9]+"), whitespace1).terms.joinToString("").toLong();
Pair(time, distance)
}
}
data class Race(val time: Int, val recordDistance: Int) | 0 | Kotlin | 0 | 0 | 7fcc18f453145d10aa2603c64ace18df25e0bb1a | 1,763 | advent-of-code | MIT License |
generators/main/InterfaceAbstractClassSolver.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.generators.util
/*
* Assume that we have element `E` with parents `P1, P2`
*
* Introduce variables E, P1, P2. If variable `X` is true then `X` is class, otherwise it is interface
*
* Build 2SAT function for it: (E || !P1) && (E || !P2) && (!P1 || !P2)
* Simple explanation:
* if `P1` is a class then `E` also should be a class
* if `P1` is a class then `P2` can not be a class (because both of them a parents of E`
*/
interface Node {
val parents: List<Node>
val origin: Node
}
fun solveGraphForClassVsInterface(
elements: List<Node>, requiredInterfaces: Collection<Node>, requiredClasses: Collection<Node>,
): List<Boolean> {
val elementMapping = ElementMapping(elements)
val solution = solve2sat(elements, elementMapping)
processRequirementsFromConfig(solution, elementMapping, requiredInterfaces, requiredClasses)
return solution
}
private class ElementMapping(val elements: Collection<Node>) {
private val varToElements: Map<Int, Node> = elements.mapIndexed { index, element -> 2 * index to element.origin }.toMap() +
elements.mapIndexed { index, element -> 2 * index + 1 to element }.toMap()
private val elementsToVar: Map<Node, Int> = elements.mapIndexed { index, element -> element.origin to index }.toMap()
operator fun get(element: Node): Int = elementsToVar.getValue(element)
operator fun get(index: Int): Node = varToElements.getValue(index)
val size: Int = elements.size
}
private fun processRequirementsFromConfig(
solution: MutableList<Boolean>,
elementMapping: ElementMapping,
requiredInterfaces: Collection<Node>,
requiredClasses: Collection<Node>,
) {
fun forceParentsToBeInterfaces(element: Node) {
val origin = element.origin
val index = elementMapping[origin]
if (!solution[index]) return
solution[index] = false
origin.parents.forEach { forceParentsToBeInterfaces(it) }
}
fun forceInheritorsToBeClasses(element: Node) {
val queue = ArrayDeque<Node>()
queue.add(element)
while (queue.isNotEmpty()) {
val e = queue.removeFirst().origin
val index = elementMapping[e]
if (solution[index]) continue
solution[index] = true
for (inheritor in elementMapping.elements) {
if (e in inheritor.parents.map { it.origin }) {
queue.add(inheritor)
}
}
}
}
requiredInterfaces.forEach(::forceParentsToBeInterfaces)
requiredClasses.forEach(::forceInheritorsToBeClasses)
}
private fun solve2sat(elements: Collection<Node>, elementsToVar: ElementMapping): MutableList<Boolean> {
val (g, gt) = buildGraphs(elements, elementsToVar)
val used = g.indices.mapTo(mutableListOf()) { false }
val order = mutableListOf<Int>()
val comp = g.indices.mapTo(mutableListOf()) { -1 }
val n = g.size
fun dfs1(v: Int) {
used[v] = true
for (to in g[v]) {
if (!used[to]) {
dfs1(to)
}
}
order += v
}
fun dfs2(v: Int, cl: Int) {
comp[v] = cl
for (to in gt[v]) {
if (comp[to] == -1) {
dfs2(to, cl)
}
}
}
for (i in g.indices) {
if (!used[i]) {
dfs1(i)
}
}
var j = 0
for (i in g.indices) {
val v = order[n - i - 1]
if (comp[v] == -1) {
dfs2(v, j++)
}
}
val res = (1..elements.size).mapTo(mutableListOf()) { false }
for (i in 0 until n step 2) {
if (comp[i] == comp[i + 1]) {
throw IllegalStateException("Somehow there is no solution. Please contact with @dmitriy.novozhilov")
}
res[i / 2] = comp[i] > comp[i + 1]
}
return res
}
private fun buildGraphs(elements: Collection<Node>, elementMapping: ElementMapping): Pair<List<List<Int>>, List<List<Int>>> {
val g = (1..elementMapping.size * 2).map { mutableListOf<Int>() }
val gt = (1..elementMapping.size * 2).map { mutableListOf<Int>() }
fun Int.direct(): Int = this
fun Int.invert(): Int = this + 1
fun extractIndex(element: Node) = elementMapping[element] * 2
for (element in elements) {
val elementVar = extractIndex(element)
for (parent in element.parents) {
val parentVar = extractIndex(parent.origin)
// parent -> element
g[parentVar.direct()] += elementVar.direct()
g[elementVar.invert()] += parentVar.invert()
}
for (i in 0 until element.parents.size) {
for (j in i + 1 until element.parents.size) {
val firstParentVar = extractIndex(element.parents[i].origin)
val secondParentVar = extractIndex(element.parents[j].origin)
// firstParent -> !secondParent
g[firstParentVar.direct()] += secondParentVar.invert()
g[secondParentVar.direct()] += firstParentVar.invert()
}
}
}
for (from in g.indices) {
for (to in g[from]) {
gt[to] += from
}
}
return g to gt
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 5,425 | kotlin | Apache License 2.0 |
src/main/kotlin/org/ageseries/libage/space/Location.kt | age-series | 414,408,529 | false | {"Kotlin": 260020} | package org.ageseries.libage.space
import kotlin.math.abs
import kotlin.math.sign
import kotlin.math.sqrt
/**
* A vector in a two-dimensional space of integers.
*/
data class Vec2i(val x: Int, val y: Int) {
/**
* Gets the opposite vector.
*/
operator fun unaryMinus() = Vec2i(-x, -y)
/**
* Gets the sum of this vector and another vector.
*/
operator fun plus(other: Vec2i) = Vec2i(x + other.x, y + other.y)
/**
* Gets the sum of this vector and the opposite of another vector.
*/
operator fun minus(other: Vec2i) = this + (-other)
/**
* Gets the scalar multiple of this vector.
*/
operator fun times(scalar: Int) = Vec2i(x * scalar, y * scalar)
val isZero: Boolean get() = this == ZERO
companion object {
val ZERO = Vec2i(0, 0)
val XU = Vec2i(1, 0)
val YU = Vec2i(0, 1)
}
}
/**
* A vector in a three-dimensional space of integers.
*/
data class Vec3i(val x: Int, val y: Int, val z: Int) {
/**
* Gets the opposite vector.
*/
operator fun unaryMinus() = Vec3i(-x, -y, -z)
/**
* Gets the sum of this vector and another vector.
*/
operator fun plus(other: Vec3i) = Vec3i(x + other.x, y + other.y, z + other.z)
/**
* Gets the sum of this vector and the opposite of another vector.
*/
operator fun minus(other: Vec3i) = this + (-other)
/**
* Gets the scalar multiple of this vector.
*/
operator fun times(other: Int) = Vec3i(x * other, y * other, z * other)
val isZero: Boolean get() = (x == 0) && (y == 0) && (z == 0)
/**
* Calculates the L1 distance between two vectors.
* See https://en.wikipedia.org/wiki/Taxicab_geometry
*/
fun l1norm(v: Vec3i): Int = abs(v.x - x) + abs(v.y - y) + abs(v.z - z)
val vec3f: Vec3f get() = Vec3f(x.toDouble(), y.toDouble(), z.toDouble())
companion object {
val ZERO = Vec3i(0, 0, 0)
val XU = Vec3i(1, 0, 0)
val YU = Vec3i(0, 1, 0)
val ZU = Vec3i(0, 0, 1)
}
}
/**
* A vector in a three-dimensional real space.
*/
data class Vec3f(val x: Double, val y: Double, val z: Double) {
operator fun unaryMinus() = Vec3f(-x, -y, -z)
operator fun plus(other: Vec3f) = Vec3f(x + other.x, y + other.y, z + other.z)
operator fun minus(other: Vec3f) = this + (-other)
fun recip() = Vec3f(1.0/x, 1.0/y, 1.0/z)
operator fun times(other: Vec3f) = Vec3f(x * other.x, y * other.y, z * other.z)
operator fun div(other: Vec3f) = this * other.recip()
operator fun plus(other: Double) = this + diag(other)
operator fun minus(other: Double) = this - diag(other)
operator fun times(other: Double) = this * diag(other)
operator fun div(other: Double) = this / diag(other)
val isZero: Boolean
get() = x == 0.0 && y == 0.0 && z == 0.0
fun dot(other: Vec3f) = x * other.x + y * other.y + z * other.z
val magSquared: Double get() = dot(this)
val mag: Double get() = sqrt(magSquared)
val normalized: Vec3f
get() = if(isZero) { ZERO } else { this / mag }
fun cross(other: Vec3f) = Vec3f(
y * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x
)
// TODO: figure out this rounding mode and document it accordingly
// (Until then, don't rely on this!)
val vec3i: Vec3i get() = Vec3i(x.toInt(), y.toInt(), z.toInt())
companion object {
fun diag(v: Double) = Vec3f(v, v, v)
val ZERO = Vec3f(0.0, 0.0, 0.0)
val XU = Vec3f(1.0, 0.0, 0.0)
val YU = Vec3f(0.0, 1.0, 0.0)
val ZU = Vec3f(0.0, 0.0, 1.0)
}
}
/**
* A direction oriented in two-dimensional space.
*/
enum class PlanarDir(val int: Int) {
Up(0), Right(1), Down(2), Left(3);
companion object {
fun fromInt(i: Int) = when (i) {
0 -> Up
1 -> Right
2 -> Down
3 -> Left
else -> error("Not a PlanarDir: $i")
}
}
val rotated: PlanarDir get() = fromInt((int + 1) % 4)
val inverted: PlanarDir get() = fromInt((int + 2) % 4)
val rotated_left: PlanarDir get() = fromInt((int + 3) % 4)
}
/**
* A set of unit vectors that represents each direction in three-dimensional space.
*/
enum class Axis(val int: Int) {
X(0), Y(1), Z(2);
companion object {
fun fromInt(i: Int) = when (i) {
0 -> X
1 -> Y
2 -> Z
else -> null
}
/**
* Returns the axis in which a given vector is closest to. Perfect diagonals may return an axis that is nonsense.
*/
fun fromVecMajor(v: Vec3i): Axis {
var (x, y, z) = v
x = abs(x); y = abs(y); z = abs(z)
val max = arrayOf(x, y, z).maxOrNull()
return when (max) {
x -> X
y -> Y
else -> Z
}
}
/* Microoptimization: avoid the overhead from constructing these repeatedly */
val X_VEC = Vec3i.XU
val Y_VEC = Vec3i.YU
val Z_VEC = Vec3i.ZU
}
val vec3i: Vec3i
get() = when (this) {
X -> X_VEC
Y -> Y_VEC
Z -> Z_VEC
}
/**
* Returns the cross product of this axis and another.
*/
fun cross(other: Axis): Axis? = when (this) {
X -> when (other) {
X -> null
Y -> Z
Z -> Y
}
Y -> when (other) {
X -> Z
Y -> null
Z -> X
}
Z -> when (other) {
X -> Y
Y -> X
Z -> null
}
}
}
/**
* The six orthogonal vectors corresponding to the faces of a cube as seen from the center.
*/
enum class PlanarFace(val int: Int) {
PosX(0), PosY(1), PosZ(2), NegX(3), NegY(4), NegZ(5);
companion object {
/**
* Gets the face corresponding to a number.
*/
fun fromInt(i: Int) = when (i) {
0 -> PosX
1 -> PosY
2 -> PosZ
3 -> NegX
4 -> NegY
5 -> NegZ
else -> error("Invalid PlanarFace: $i")
}
/**
* Gets the plane that the axis is pointing to from the center.
*/
fun fromAxis(a: Axis, n: Boolean): PlanarFace = fromInt(a.int + if (n) 3 else 0)
/**
* Gets the plane that the vector is pointing to in respect to the center of the cube.
*/
fun fromVec(v: Vec3i): PlanarFace {
val axis = Axis.fromVecMajor(v)
return fromAxis(
axis, when (axis) {
Axis.X -> v.x < 0
Axis.Y -> v.y < 0
Axis.Z -> v.z < 0
}
)
}
/**
* Gets the plane that has the closest normal vector to the given vector.
*/
fun fromNormal(v: Vec3i): PlanarFace = fromVec(v).inverse
/* See the microopt in Axis above */
val PosX_VEC = Axis.X_VEC
val PosY_VEC = Axis.Y_VEC
val PosZ_VEC = Axis.Z_VEC
val NegX_VEC = -PosX_VEC
val NegY_VEC = -PosY_VEC
val NegZ_VEC = -PosZ_VEC
val ADJACENCIES = arrayOf(
arrayOf(PosY, PosZ, NegY, NegZ),
arrayOf(PosX, PosZ, NegX, NegZ),
arrayOf(PosX, PosY, NegX, NegY)
)
}
val neg: Boolean get() = int > 2
val axis: Axis
get() = when (this) {
PosX, NegX -> Axis.X
PosY, NegY -> Axis.Y
PosZ, NegZ -> Axis.Z
}
val inverse: PlanarFace
get() = when (this) {
PosX -> NegX
NegX -> PosX
PosY -> NegY
NegY -> PosY
PosZ -> NegZ
NegZ -> PosZ
}
/**
"Vector": the vec that points out of the block center toward this face.
*/
val vec3i: Vec3i
get() = if (neg) when (axis) {
Axis.X -> NegX_VEC
Axis.Y -> NegY_VEC
Axis.Z -> NegZ_VEC
} else axis.vec3i
/**
* "Normal": the vec that points, normal to this face, toward the block center.
*/
val normal: Vec3i
get() = if (neg) axis.vec3i else when (axis) {
Axis.X -> NegX_VEC
Axis.Y -> NegY_VEC
Axis.Z -> NegZ_VEC
}
val adjacencies: Array<PlanarFace> get() = ADJACENCIES[int % 3]
}
/**
* A generic location in a generic space. Also contains a method to check if something can connect with this and list
* of locatable objects that can connect with this.
*/
interface Locator {
val vec3i: Vec3i
/**
* A list of neighbors in which connections are possible with.
*/
fun neighbors(): List<Locator>
/**
* Returns true if it is possible for this node and another node to connect.
* When overriding this, make sure a specific test is implemented for the specific
* locator that extended this interface. Ensure that the coverage of the test is
* proportional to the size of the implementation.
*/
fun canConnect(other: Locator): Boolean = true
}
/**
* Locator support for "simple nodes" that take up an entire block in three-dimensional space.
*/
open class BlockPos(override val vec3i: Vec3i) : Locator {
companion object {
val CONNECTIVITY_DELTAS = PlanarFace.values().map { it.vec3i }
}
override fun toString() = "BlockPos($vec3i)"
override fun neighbors(): List<Locator> = CONNECTIVITY_DELTAS.map { translated(it) }
/**
* Offsets a vector based on the position of this node.
*/
fun translated(v: Vec3i) = BlockPos(vec3i + v)
}
/**
* Locator support for surface-mounted nodes the exist on a three-dimensional block. Up to six can exist per block,
* corresponding to each face.
*/
open class SurfacePos(override val vec3i: Vec3i, val face: PlanarFace) : Locator {
companion object {
// On the same plane:
val PLANAR_DELTAS = arrayListOf(
Vec3i(1, 0, 0), Vec3i(-1, 0, 0), Vec3i(0, 0, 1), Vec3i(0, 0, -1)
)
// On adjacent planes:
val ADJACENT_DELTAS = arrayListOf(
// SurfacePos locators can connect to adjacent planes on the same block:
Vec3i(0, 0, 0),
// One unit down (anti-normal) in cardinal directions ("wrapping around")
Vec3i(1, -1, 0), Vec3i(-1, -1, 0), Vec3i(0, -1, 1), Vec3i(0, -1, -1)
)
}
override fun toString() = "SurfacePos($vec3i, $face)"
// Preserve chirality: invert _two_ components, or none.
// There's very little thought in the permutation otherwise, however; if those need to be changed, they can be.
/**
* Orients a vector based on which plane of a cube this node is on. This preserves chirality.
*/
fun toGlobal(v: Vec3i): Vec3i = when (face) {
PlanarFace.NegX -> Vec3i(v.y, v.x, v.z)
PlanarFace.PosX -> Vec3i(-v.y, -v.x, v.z)
PlanarFace.PosY -> Vec3i(-v.x, -v.y, v.z)
PlanarFace.NegY -> v
PlanarFace.NegZ -> Vec3i(v.x, v.z, v.y)
PlanarFace.PosZ -> Vec3i(-v.x, v.z, -v.y)
}
/**
* Offsets a vector based on the position and orientation of this node.
*/
fun translated(v: Vec3i) = SurfacePos(vec3i + toGlobal(v), face)
override fun neighbors(): List<Locator> = (PLANAR_DELTAS.map { translated(it) } + // Other adjacent blocks on the same plane
face.adjacencies.map { SurfacePos(vec3i, it) } + // Connections within the same block
face.adjacencies.map { SurfacePos(vec3i + face.vec3i + it.normal, it) } // "Wrapping" (L1=2) connections
)
override fun canConnect(other: Locator): Boolean = when (other) {
is SurfacePos -> when (other.vec3i.l1norm(vec3i)) {
0 -> other.face != face && other.face != face.inverse
1 -> face == other.face
2 -> {
val delta = other.vec3i - vec3i
val otherNorm = delta + face.normal
println(
"SP.cC: L1=2: delta $delta other_norm $otherNorm face.normal ${face.normal} this.vec $vec3i other.vec ${other.vec3i} other.face ${other.face} PF.fN(on) ${
PlanarFace.fromNormal(
otherNorm
)
}"
)
other.face == PlanarFace.fromNormal(otherNorm)
}
else -> error("Illegal norm")
}
is BlockPos -> true
else -> true
}
}
object GPUtil {
fun gp(v: Vec3i): String = "${v.x},${v.z},${v.y}"
fun gp(v: Vec3f): String = "${v.x},${v.z},${v.y}"
data class FaceInfo(val offset: Vec3f, val ax1: Axis, val ax2: Axis)
fun faceInfo(face: PlanarFace): FaceInfo {
val axes = face.adjacencies.map { it.axis }
// Conjecture: there are two axes
val ax1 = axes[0]
val ax2 = axes[1]
var off = ax1.cross(ax2)!!.vec3i.vec3f
if(face.neg) off *= -1.0
return FaceInfo(off, ax1, ax2)
}
val signs = arrayOf(
Pair(-1.0, -1.0),
Pair(1.0, -1.0),
Pair(1.0, 1.0),
Pair(-1.0, 1.0),
)
fun plotFace(face: PlanarFace, origin: Vec3f = Vec3f.ZERO, style: String = "") {
val (off, ax1, ax2) = faceInfo(face)
val pts = mutableListOf<Vec3f>()
for ((sgn1, sgn2) in signs) {
val pt = origin + off + ax1.vec3i.vec3f * sgn1 + ax2.vec3i.vec3f * sgn2
pts.add(pt)
}
for ((idx, pt) in pts.withIndex()) {
val next = pts[(idx + 1) % pts.size]
println("set arrow from ${PlotSurfacePosRotations.gp(pt)} to ${PlotSurfacePosRotations.gp(next)} nohead $style")
}
}
fun plotCube(origin: Vec3f = Vec3f.ZERO, style: String = "") {
for(face in PlanarFace.values()) {
plotFace(face, origin, style)
}
}
val axisColors = arrayOf("#ff0000", "#00ff00", "#0000ff")
fun plotRose(origin: Vec3f = Vec3f.ZERO, scale: Double = 0.2, style: String = "") {
for(axis in Axis.values()) {
println("set arrow from ${gp(origin)} to ${gp(origin + axis.vec3i.vec3f * scale)} lc \"${axisColors[axis.int]}\" $style")
}
}
fun locatorSpace(pos: Vec3f) = pos * 2.0
fun locatorSpace(pos: Vec3i) = locatorSpace(pos.vec3f)
fun plotLocator(loc: Locator, style: String = "") {
when(loc) {
is BlockPos -> plotLocator(loc, style)
is SurfacePos -> plotLocator(loc, style)
}
}
fun plotLocator(loc: BlockPos, style: String = "") {
plotCube(locatorSpace(loc.vec3i), style)
}
fun plotLocator(loc: SurfacePos, style: String = "") {
plotFace(loc.face, locatorSpace(loc.vec3i), style)
}
}
class PlotSurfacePosRotations {
companion object {
val gp: (Vec3f) -> String = GPUtil::gp
val colors = GPUtil.axisColors
@JvmStatic
fun main(args: Array<String>) {
val units = with(Vec3i) { arrayOf(XU, YU, ZU) }
val faces = PlanarFace.values()
for(axis in arrayOf("x", "y", "z")) {
println("set ${axis}range [-1:1]")
}
for(face in faces) {
println("# Face: $face")
val off = GPUtil.faceInfo(face).offset
GPUtil.plotFace(face, style = "lc \"#007700\"")
println("set label \"$face\" at ${gp(off)} tc \"${colors[face.axis.int]}\"")
val sp = SurfacePos(Vec3i.ZERO, face)
for((idx, unit) in units.withIndex()) {
val color = colors[idx]
val mapped = sp.toGlobal(unit).vec3f / 5.0
println("set arrow from ${gp(off)} to ${gp(off + mapped)} lc \"$color\"")
}
println("")
}
}
}
}
class PlotBlockPosNeighbors {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val bp = BlockPos(Vec3i.ZERO)
for(neighbor in bp.neighbors()) {
GPUtil.plotLocator(neighbor, "lc \"#007700\"")
GPUtil.plotRose(GPUtil.locatorSpace(neighbor.vec3i))
}
GPUtil.plotLocator(bp, "lc \"#ff0000\"")
GPUtil.plotRose()
}
}
} | 5 | Kotlin | 1 | 1 | 0ce1c5a1d7eff41a0dbee389d50c6eaa10cac7c0 | 16,408 | libage | MIT License |
Lab4/src/main/kotlin/RegionTree.kt | knu-3-velychko | 276,473,844 | false | null | class RegionTree(private var points: List<Point>) {
val root: Node
init {
points.sortedBy { it.x }
root = build(0, points.size)
}
private fun build(left: Int, right: Int): Node {
val node = Node()
val m = left + (right - left) / 2
node.mid = points[m].x
if (points.size == right) {
node.to = Double.POSITIVE_INFINITY
} else {
node.to = points[right - 1].x
}
node.from = points[left].x
node.points = insertPoints(left, right)
if (m - left > 1)
node.left = build(left, m)
if (right - m > 1)
node.right = build(m, right)
return node
}
private fun insertPoints(left: Int, right: Int): List<Point> {
val list = mutableListOf<Point>()
for (i in left until right) {
list.add(points[i])
}
list.sortBy { it.y }
return list.toList()
}
fun searchPoints(from: Point, to: Point): List<Point> {
val nodes = searchPointsX(from, to, root)
val result = mutableListOf<Point>()
for (i in nodes) {
result.addAll(searchPointsY(from.y, to.y, i.points))
}
return result
}
private fun searchPointsX(from: Point, to: Point, node: Node?): List<Node> {
if (node == null || from.x > to.x || to.x < node.from) {
return emptyList()
}
if (from.x <= node.from && to.x >= node.to) {
return listOf(node)
}
if (from.x >= node.mid) {
return searchPointsX(from, to, node.right)
}
if (to.x < node.mid) {
return searchPointsX(from, to, node.left)
}
val result = mutableListOf<Node>()
result.addAll(searchPointsX(from, to, node.left))
result.addAll(searchPointsX(from, to, node.right))
return result
}
private fun searchPointsY(minY: Double, maxY: Double, list: List<Point>): List<Point> {
val right = less(maxY, list)
if (right == -1) {
return emptyList()
}
val left = greater(minY, list)
if (left == -1) {
return emptyList()
}
val result = mutableListOf<Point>()
for (i in left..right) {
result.add(list[i])
}
return result
}
private fun less(y: Double, list: List<Point>): Int {
var left = 0
var right = list.size - 1
var mid: Int
while (left < right) {
mid = left + (right - left) / 2
if (list[mid].y > y) {
right = mid
} else {
left = mid + 1
}
}
return if (list[left].y <= y) left else -1
}
private fun greater(y: Double, list: List<Point>): Int {
var left = 0
var right = list.size - 1
var mid: Int
while (left < right) {
mid = left + (right - left) / 2
if (list[mid].y < y) {
left = mid + 1
} else {
right = mid
}
}
return if (list[right].y >= y) left else -1
}
} | 0 | Kotlin | 0 | 0 | b16603d78bf44f927f4f6389754a5d015a25f7e2 | 3,197 | ComputerGraphics | MIT License |
src/main/kotlin/com/kishor/kotlin/algo/algorithms/tree/RootingATree.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.algo.algorithms.tree
import com.kishor.kotlin.algo.algorithms.graph.AdjacencyMatrixWeightedGraph
fun main() {
rootATree(AdjacencyMatrixWeightedGraph(0))
}
fun rootATree(graph: AdjacencyMatrixWeightedGraph, rootId: Int = 0): CustomTreeNode {
val root = CustomTreeNode(rootId, null, mutableListOf())
return buildTree(graph, root, null)
}
//fun buildTree(graph: AdjacencyMatrixWeightedGraph, nodeCustom: CustomTreeNode, parent: CustomTreeNode?): CustomTreeNode {
// for (childId in graph.matrix[nodeCustom.id]) {
// if (parent != null && childId == parent.id) {
// continue
// }
// val child = CustomTreeNode(childId, nodeCustom, arrayListOf()) // arraylist of ? // inline function
// nodeCustom.listOfChildren.add(child)
// buildTree(graph, child, nodeCustom)
// }
// return nodeCustom
//}
fun rootingATree(g: AdjacencyMatrixWeightedGraph, rootId: Int): CustomTreeNode {
val root = CustomTreeNode(rootId,null, mutableListOf<CustomTreeNode>())
return buildTree(g, null, root)
}
fun buildTree(g: AdjacencyMatrixWeightedGraph, parent: CustomTreeNode?, nodeCustom: CustomTreeNode?): CustomTreeNode {
for (childId in g.matrix[nodeCustom!!.id]) {
if (parent != null && childId == parent.id)
continue
val child = CustomTreeNode(childId, nodeCustom, mutableListOf<CustomTreeNode>())
nodeCustom.listOfChildren.add(child)
buildTree(g, nodeCustom, child)
}
return nodeCustom
}
| 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 1,536 | DS_Algo_Kotlin | MIT License |
Practice/Algorithms/implementation/DivisibleSumPairs.kts | kukaro | 352,032,273 | false | null | import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import kotlin.collections.*
import kotlin.comparisons.*
import kotlin.io.*
import kotlin.jvm.*
import kotlin.jvm.functions.*
import kotlin.jvm.internal.*
import kotlin.ranges.*
import kotlin.sequences.*
import kotlin.text.*
/*
* Complete the 'divisibleSumPairs' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER k
* 3. INTEGER_ARRAY ar
*/
fun divisibleSumPairs(n: Int, k: Int, ar: Array<Int>): Int {
var cnt = 0
for (i in ar.indices) {
for (j in i + 1 until ar.size) {
if ((ar[i] + ar[j]) % k == 0) {
// println("$i:$j")
cnt++
}
}
}
return cnt
}
fun main(args: Array<String>) {
val first_multiple_input = readLine()!!.trimEnd().split(" ")
val n = first_multiple_input[0].toInt()
val k = first_multiple_input[1].toInt()
val ar = readLine()!!.trimEnd().split(" ").map { it.toInt() }.toTypedArray()
val result = divisibleSumPairs(n, k, ar)
println(result)
}
| 0 | Kotlin | 0 | 0 | 4f04ff7b605536398aecc696f644f25ee6d56637 | 1,281 | hacker-rank-solved | MIT License |
app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateRanker.kt | kyjibo | 353,664,422 | true | {"Kotlin": 1925455, "Shell": 1179} | package eu.kanade.tachiyomi.data.library
import eu.kanade.tachiyomi.data.database.models.Manga
import kotlin.math.abs
/**
* This class will provide various functions to Rank mangas to efficiently schedule mangas to update.
*/
object LibraryUpdateRanker {
val rankingScheme = listOf(
(this::lexicographicRanking)(),
(this::latestFirstRanking)(),
(this::nextFirstRanking)()
)
/**
* Provides a total ordering over all the Mangas.
*
* Orders the manga based on the distance between the next expected update and now.
* The comparator is reversed, placing the smallest (and thus closest to updating now) first.
*/
fun nextFirstRanking(): Comparator<Manga> {
val time = System.currentTimeMillis()
return Comparator { mangaFirst: Manga,
mangaSecond: Manga ->
compareValues(abs(mangaSecond.next_update-time), abs(mangaFirst.next_update-time))
}.reversed()
}
/**
* Provides a total ordering over all the Mangas.
*
* Assumption: An active [Manga] mActive is expected to have been last updated after an
* inactive [Manga] mInactive.
*
* Using this insight, function returns a Comparator for which mActive appears before mInactive.
* @return a Comparator that ranks manga based on relevance.
*/
fun latestFirstRanking(): Comparator<Manga> {
return Comparator { mangaFirst: Manga,
mangaSecond: Manga ->
compareValues(mangaSecond.last_update, mangaFirst.last_update)
}
}
/**
* Provides a total ordering over all the Mangas.
*
* Order the manga lexicographically.
* @return a Comparator that ranks manga lexicographically based on the title.
*/
fun lexicographicRanking(): Comparator<Manga> {
return Comparator { mangaFirst: Manga,
mangaSecond: Manga ->
compareValues(mangaFirst.title, mangaSecond.title)
}
}
}
| 0 | Kotlin | 0 | 0 | f41b9b399c1b3cbe3e80d2f30b67cdc6ccee3308 | 2,005 | Neko | Apache License 2.0 |
app/src/main/kotlin/io/github/andrewfitzy/day08/Task02.kt | andrewfitzy | 747,793,365 | false | {"Kotlin": 60159, "Shell": 1211} | package io.github.andrewfitzy.day08
class Task02(rowsInput: Int, colsInput: Int, puzzleInput: List<String>) {
private val rows: Int = rowsInput
private val cols: Int = colsInput
private val input: List<String> = puzzleInput
fun solve(): Int {
val display: Array<CharArray> = Array(rows) { CharArray(cols) { '.' } }
for (line in input) {
if (line.startsWith("rect")) {
val rectangle = line.split(" ")[1]
val width = rectangle.split("x")[0].toInt()
val height = rectangle.split("x")[1].toInt()
illuminate(width, height, display)
}
if (line.startsWith("rotate column")) {
val rotation = line.split("=")[1]
val column = rotation.split(" by ")[0].toInt()
val pixels = rotation.split(" by ")[1].toInt()
rotateColumn(column, pixels, display)
}
if (line.startsWith("rotate row")) {
val rotation = line.split("=")[1]
val row = rotation.split(" by ")[0].toInt()
val pixels = rotation.split(" by ")[1].toInt()
rotateRow(row, pixels, display)
}
}
printDisplay(display)
return countIlluminated(display)
}
private fun printDisplay(display: Array<CharArray>) {
for (element in display) {
val builder = StringBuilder()
for (j in 0 until display[0].size) {
builder.append(element[j])
}
println(builder.toString())
}
}
private fun rotateRow(
row: Int,
pixels: Int,
display: Array<CharArray>,
) {
val rowList = display[row].toList()
val leftSplit = rowList.subList(0, rowList.size - pixels)
val rightSplit = rowList.subList(rowList.size - pixels, rowList.size)
val newRowList = rightSplit + leftSplit
for (i in newRowList.indices) {
display[row][i] = newRowList[i]
}
}
private fun rotateColumn(
column: Int,
pixels: Int,
display: Array<CharArray>,
) {
val colList: MutableList<Char> = mutableListOf()
for (element in display) {
colList.add(element[column])
}
val topSplit = colList.subList(0, colList.size - pixels)
val bottomSplit = colList.subList(colList.size - pixels, colList.size)
val newColList = bottomSplit + topSplit
for (i in newColList.indices) {
display[i][column] = newColList[i]
}
}
private fun illuminate(
width: Int,
height: Int,
display: Array<CharArray>,
) {
for (i in 0 until height) {
for (j in 0 until width) {
display[i][j] = '#'
}
}
}
private fun countIlluminated(display: Array<CharArray>): Int {
var count = 0
for (element in display) {
for (j in 0 until display[0].size) {
if (element[j] == '#') {
count++
}
}
}
return count
}
}
| 0 | Kotlin | 0 | 0 | 15ac072a14b83666da095b9ed66da2fd912f5e65 | 3,186 | 2016-advent-of-code | Creative Commons Zero v1.0 Universal |
src/net/sheltem/aoc/y2023/Day02.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2023
import kotlin.math.max
suspend fun main() {
Day02().run()
}
private val maxCubes = mapOf("red" to 12, "green" to 13, "blue" to 14)
class Day02 : Day<Long>(8, 2286) {
override suspend fun part1(input: List<String>): Long = input
.mapIndexed { index, s -> (index + 1) to s.toMinCubeMap() }
.filterNot { setToTest -> maxCubes.any { setToTest.second[it.key]!! > it.value } }
.sumOf { it.first }.toLong()
override suspend fun part2(input: List<String>): Long = input
.map{ it.toMinCubeMap() }
.sumOf {
it.values.reduce { accumulator, element ->
accumulator * element
}
}
}
private fun String.toMinCubeMap(): Map<String, Long> =
this.split(": ")
.last()
.split("; ")
.flatMap { cubeSet ->
cubeSet
.split(", ")
.map { cube ->
cube
.split(" ")
.let { it.component2() to it.component1().toLong() }
}
}//.also { println(it) }
.groupingBy { it.first }
.aggregate { _, accumulator: Long?, element, first ->
if (first) {
element.second
} else {
max(accumulator!!, element.second)
}
}//.also { println(it) }
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 1,387 | aoc | Apache License 2.0 |
src/main/kotlin/Day05.kt | attilaTorok | 573,174,988 | false | {"Kotlin": 26454} | import java.util.Stack
data class Instruction(
val count: Int,
val from: Int,
val to: Int,
)
fun main() {
fun readStacks(iterator: Iterator<String>): List<Stack<Char>> {
val stacks = mutableListOf<Stack<Char>>()
val lines = Stack<String>()
var numberOfStacks = 0
while (iterator.hasNext()) {
val line = iterator.next()
if (line.contains("1")) {
val split = line.split(" ")
numberOfStacks = Integer.valueOf(split[split.size - 1])
break
} else {
lines.add(line)
}
}
for (i in 0 until numberOfStacks) {
stacks.add(Stack<Char>())
}
while (lines.isNotEmpty()) {
val split = lines.pop().toCharArray()
for (i in 0 until numberOfStacks) {
val elementIndex = 1 + 4 * i
if (elementIndex < split.size) {
if (split[elementIndex].isLetter()) {
stacks[i].add(split[1 + 4 * i])
}
}
}
}
return stacks
}
fun createInstruction(line: String): Instruction {
val split = line.split(" ")
return Instruction(split[1].toInt(), split[3].toInt() - 1, split[5].toInt() - 1)
}
fun getTopCreates(fileName: String, movingStrategy: (List<Stack<Char>>, Instruction) -> Unit): String {
var result = ""
readInputWithStream(fileName).useLines {
val iterator = it.iterator()
val stacks = readStacks(iterator)
//empty line
iterator.next()
while (iterator.hasNext()) {
movingStrategy(stacks, createInstruction(iterator.next()))
}
for (stack in stacks) {
if (stack.isNotEmpty()) result += stack.pop()
}
}
return result
}
val lifo = { stacks: List<Stack<Char>>, instruction: Instruction ->
for (i in 0 until instruction.count) {
stacks[instruction.to].add(stacks[instruction.from].pop())
}
}
val fifo = { stacks: List<Stack<Char>>, instruction: Instruction ->
val list = mutableListOf<Char>()
for (i in 0 until instruction.count) {
list.add(stacks[instruction.from].pop())
}
for (i in list.size - 1 downTo 0) {
stacks[instruction.to].add(list[i])
}
}
println("Test")
println("Top elements after rearrangements should be CMZ! Answer: ${getTopCreates("Day05_test", lifo)}")
println("Top elements after rearrangements should be MCD! Answer: ${getTopCreates("Day05_test", fifo)}")
println()
println("Exercise")
println("Top elements after rearrangements should be PTWLTDSJV! Answer: ${getTopCreates("Day05", lifo)}")
println("Top elements after rearrangements should be WZMFVGGZP! Answer: ${getTopCreates("Day05", fifo)}")
} | 0 | Kotlin | 0 | 0 | 1799cf8c470d7f47f2fdd4b61a874adcc0de1e73 | 2,995 | AOC2022 | Apache License 2.0 |
grind-75-kotlin/src/main/kotlin/RansomNote.kt | Codextor | 484,602,390 | false | {"Kotlin": 27206} | /**
* Given two strings ransomNote and magazine,
* return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
*
* Each letter in magazine can only be used once in ransomNote.
*
*
*
* Example 1:
*
* Input: ransomNote = "a", magazine = "b"
* Output: false
* Example 2:
*
* Input: ransomNote = "aa", magazine = "ab"
* Output: false
* Example 3:
*
* Input: ransomNote = "aa", magazine = "aab"
* Output: true
*
*
* Constraints:
*
* 1 <= ransomNote.length, magazine.length <= 10^5
* ransomNote and magazine consist of lowercase English letters.
* @see <a href="https://leetcode.com/problems/ransom-note/">LeetCode</a>
*/
fun canConstruct(ransomNote: String, magazine: String): Boolean {
val memoryMap = HashMap<Char, Int>()
magazine.forEach { character ->
memoryMap.put(character, 1 + memoryMap.getOrDefault(character, 0))
}
ransomNote.forEach { character ->
if (memoryMap.getOrDefault(character, 0) == 0) {
return false
}
memoryMap.put(character, memoryMap.getOrDefault(character, 1) - 1)
}
return true
}
| 0 | Kotlin | 0 | 0 | 87aa60c2bf5f6a672de5a9e6800452321172b289 | 1,137 | grind-75 | Apache License 2.0 |
src/day4/Solution.kt | chipnesh | 572,700,723 | false | {"Kotlin": 48016} | package day4
import readInput
fun main() {
fun part1(input: List<String>): Int {
return input.count {
val (first, second) = RangePair(it)
first in second || second in first
}
}
fun part2(input: List<String>): Int {
return input.count {
val (first, second) = RangePair(it)
first intersect second || second intersect first
}
}
//val input = readInput("test")
val input = readInput("prod")
println(part1(input))
println(part2(input))
}
@JvmInline
value class RangePair(private val value: String) {
operator fun component1() = Range(value.substringBefore(","))
operator fun component2() = Range(value.substringAfter(","))
}
@JvmInline
value class Range(private val value: String) {
val start get() = value.substringBefore("-").toInt()
val end get() = value.substringAfter("-").toInt()
operator fun contains(value: Int) =
value in start..end
operator fun contains(other: Range) =
start in other && end in other
infix fun intersect(other: Range) =
start in other || end in other
}
| 0 | Kotlin | 0 | 1 | 2d0482102ccc3f0d8ec8e191adffcfe7475874f5 | 1,150 | AoC-2022 | Apache License 2.0 |
src/Day08.kt | arksap2002 | 576,679,233 | false | {"Kotlin": 31030} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
val arr = mutableListOf<MutableList<Boolean>>()
for (i in input.indices) {
val l = mutableListOf<Boolean>()
for (j in 0 until input[0].length) {
l.add(false)
}
arr.add(l)
}
var result = 0
result += 2 * input.size
result += 2 * input[0].length
result -= 4
for (i in 1 until input.size - 1) {
var max = input[i][0]
for (j in 1 until input[0].length - 1) {
if (input[i][j] > max) {
if (!arr[i][j]) {
result++
arr[i][j] = true
}
max = input[i][j]
}
}
max = input[i][input[0].length - 1]
for (k in 1 until input[0].length - 1) {
val j = input[0].length - k - 1
if (input[i][j] > max) {
if (!arr[i][j]) {
result++
arr[i][j] = true
}
max = input[i][j]
}
}
}
for (i in 1 until input[0].length - 1) {
var max = input[0][i]
for (j in 1 until input.size - 1) {
if (input[j][i] > max) {
if (!arr[j][i]) {
result++
arr[j][i] = true
}
max = input[j][i]
}
}
max = input[input.size - 1][i]
for (k in 1 until input.size - 1) {
val j = input.size - k - 1
if (input[j][i] > max) {
if (!arr[j][i]) {
result++
arr[j][i] = true
}
max = input[j][i]
}
}
}
return result
}
fun part2(input: List<String>): Int {
val n = input[0].length
val m = input.size
var result = 0
for (i in 1 until m - 1) {
for (j in 1 until n - 1) {
var current = 1
for (k in i + 1 until m) {
if (input[k][j] >= input[i][j]) {
current *= k - i
break
}
if (k == m - 1) {
current *= k - i
}
}
for (k in j + 1 until n) {
if (input[i][k] >= input[i][j]) {
current *= k - j
break
}
if (k == n - 1) {
current *= k - j
}
}
for (w in 0 until i) {
val k = i - w - 1
if (input[k][j] >= input[i][j]) {
current *= k - i
break
}
if (w == i - 1) {
current *= k - i
}
}
for (w in 0 until j) {
val k = j - w - 1
if (input[i][k] >= input[i][j]) {
current *= k - j
break
}
if (w == j - 1) {
current *= k - j
}
}
result = max(result, current)
}
}
return result
}
val input = readInput("Day08")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | a24a20be5bda37003ef52c84deb8246cdcdb3d07 | 3,752 | advent-of-code-kotlin | Apache License 2.0 |
Kotlin/binary_Search.kt | manan025 | 412,155,744 | false | null | package com.company
fun main(args: Array<String>) {
// please pass sorted array in input always because binary search will always run in sorted array
val i = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray()
val key = readLine()!!.trim().toInt()
val ans = binarySearch(i, key)
if(ans >= 0 ) {
println(ans)
} else {
println("Position not found")
}
}
fun binarySearch(input: IntArray, key: Int) : Int{
var i = 0
var j = input.size
var mid : Int
while(i < j) {
mid = (i +j) / 2
when {
key == input[mid] -> return mid
key >input[mid] -> i = mid+1
key < input[mid] -> j = mid-1;
}
}
return -1
}
// sample input 1 :
// 1, 2, 3, 4, 5, 6
// 3
// output : 2
// sample input 2 :
// 4 5 2 3 6
// 3
// output : position not found
// Time Complexity = O(log(n)) for worst case and would be O(1) in best case
// space complexity = O(1)
| 115 | Java | 89 | 26 | c185dcedc449c7e4f6aa5e0d8989589ef60b9565 | 978 | DS-Algo-Zone | MIT License |
src/day2/Day2.kt | crmitchelmore | 576,065,911 | false | {"Kotlin": 115199} | package day2
import helpers.ReadFile
class Day2 {
// val lines = listOf(
// "A X",
// "A Y",
// "A Z",
// "B X",
// "B Y",
// "B Z",
// "C X",
// "C Y",
// "C Z",
// )
// val lines = listOf(
// "A Y",
// "B X",
// "C Z"
// )
val lines = ReadFile.named("src/day2/input.txt")
var points = hashMapOf(
"X" to 0,
"Y" to 1,
"Z" to 2,
"A" to 0,
"B" to 1,
"C" to 2,
)
var reversePoints = hashMapOf(
0 to "X",
1 to "Y",
2 to "Z",
)
var names = hashMapOf(
"X" to "rock",
"Y" to "paper",
"Z" to "scissors",
"A" to "rock",
"B" to "paper",
"C" to "scissors",
)
var wld = hashMapOf(
0 to "lost",
3 to "draw",
6 to "won",
)
var winPoints: (String, String) -> Int = { a, b ->
if (points[a] == 2 && points[b] == 0) {
6;
} else if(points[a]==points[b]) {
3;
} else {
if (points[a]!! + 1 == points[b]!!) 6 else 0;
}}
fun result1(): String {
//
return lines.fold(0) { a: Int, b: String ->
var r = b.split(" ")
var p1 = r[0]
var p2 = r[1]
println("L A: ${names[p1]} B: ${names[p2]} score: ${points[p2]!!} res: ${wld[winPoints(p1, p2)]}")
a + points[p2]!! + 1 + winPoints(p1, p2)
}.toString()
}
fun result2(): String {
// x lose y darw z win
return lines.fold(0) { a: Int, b: String ->
var r = b.split(" ")
var p1 = r[0]
var p2 = r[1]
if (p2 == "Y") {
p2 = p1
} else if (p2 == "Z") {
p2 = reversePoints[(points[p1]!! + 1) % 3]!!
} else {
p2 = reversePoints[(points[p1]!! + 2) % 3]!!
}
println("L A: ${names[p1]}(${p1}) B: ${names[p2]}(${p2}) score: ${points[p2]!! + 1} res: ${wld[winPoints(p1, p2)]}(${winPoints(p1, p2)})")
a + points[p2]!! + 1 + winPoints(p1, p2)
}.toString()
}
} | 0 | Kotlin | 0 | 0 | fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470 | 2,234 | adventofcode2022 | MIT License |
src/main/kotlin/frc/kyberlib/math/Polynomial.kt | Kanishk-Pandey | 625,399,371 | false | null | package frc.kyberlib.math
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Representation and calculator of a polynomial
*/
class Polynomial(
vararg val coeffs: Double,
private val variableName: Char = 'x'
) {
companion object {
fun regress(args: DoubleArray, outputs: DoubleArray, order: Int = 1): Polynomial {
var n = order
val datasetSize = args.size
val X = DoubleArray(2 * n + 1)
for (i in 0 until 2 * n + 1) {
X[i] = 0.0
for (j in 0 until datasetSize) X[i] =
X[i] + args[j].pow(i.toDouble()) //consecutive positions of the array will store N,sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n)
}
val B = Array(n + 1) { DoubleArray(n + 2) }
val a =
DoubleArray(n + 1) //B is the Normal matrix(augmented) that will store the equations, 'a' is for value of the final coefficients
for (i in 0..n) for (j in 0..n) B[i][j] =
X[i + j] //Build the Normal matrix by storing the corresponding coefficients at the right positions except the last column of the matrix
val Y =
DoubleArray(n + 1) //Array to store the values of sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi)
for (i in 0 until n + 1) {
Y[i] = 0.0
for (j in 0 until datasetSize) Y[i] =
Y[i] + args[j].pow(i.toDouble()) * outputs[j] //consecutive positions will store sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi)
}
for (i in 0..n) B[i][n + 1] =
Y[i] //load the values of Y as the last column of B(Normal Matrix but augmented)
n += 1
for (i in 0 until n) //From now Gaussian Elimination starts(can be ignored) to solve the set of linear equations (Pivotisation)
for (k in i + 1 until n) if (B[i][i] < B[k][i]) for (j in 0..n) {
val temp = B[i][j]
B[i][j] = B[k][j]
B[k][j] = temp
}
for (i in 0 until n - 1) //loop to perform the gauss elimination
for (k in i + 1 until n) {
val t = B[k][i] / B[i][i]
for (j in 0..n) B[k][j] =
B[k][j] - t * B[i][j] //make the elements below the pivot elements equal to zero or elimnate the variables
}
for (i in n - 1 downTo 0) //back-substitution
{ //args is an array whose values correspond to the values of args,outputs,z..
a[i] = B[i][n] //make the variable to be calculated equal to the rhs of the last equation
for (j in 0 until n) if (j != i) //then subtract all the lhs values except the coefficient of the variable whose value is being calculated
a[i] = a[i] - B[i][j] * a[j]
a[i] = a[i] / B[i][i] //now finally divide the rhs by the coefficient of the variable to be calculated
}
a.reverse()
return Polynomial(*a)
}
}
val degree = coeffs.size
/**
* Solve the polynomial for the given value
*/
fun eval(x: Double): Double {
var total = 0.0
for (i in coeffs.indices) {
total += coeffs[i] * x.pow(coeffs.size - i - 1)
}
return total
}
operator fun get(x: Double) = eval(x)
fun r(data: DoubleArray, actualResults: DoubleArray): Double {
val n = data.size
return (n * (data.zip(actualResults).sumOf { it.first * it.second }) - data.sum() * actualResults.sum()) /
sqrt(n * (data.sumOf { it * it } - data.sum())) / n * (actualResults.sumOf { it * it } - actualResults.sum())
}
override fun toString(): String {
var s = ""
for (i in coeffs.indices) {
s += "${coeffs[i]}$variableName^${coeffs.size - i - 1}"
if (i < coeffs.size - 1 && coeffs[i + 1] >= 0.0) s += "+"
}
return s
}
}
| 0 | Kotlin | 0 | 0 | e5d6c96397e1b4ab703e638db2361418fd9d4939 | 4,139 | MyRoboticsCode | Apache License 2.0 |
combinatorics/src/main/kotlin/com/nickperov/stud/combinatorics/CombinatorialUtils.kt | nickperov | 327,780,009 | false | null | package com.nickperov.stud.combinatorics
import java.math.BigInteger
object CombinatorialUtils {
/**
* Number of ordered samples of size m, without replacement, from n objects.
*/
fun calculateNumberOfVariationsInt(n: Int, m: Int): Int {
val number = calculateNumberOfVariations(n, m)
if (number > BigInteger.valueOf(Int.MAX_VALUE.toLong())) {
throw IllegalArgumentException("Value is too big")
} else {
return number.toInt()
}
}
/**
* Number of ordered samples of size m, without replacement, from n objects.
*/
fun calculateNumberOfVariationsLong(n: Int, m: Int): Long {
val number = calculateNumberOfVariations(n, m)
if (number > BigInteger.valueOf(Long.MAX_VALUE)) {
throw IllegalArgumentException("Value is too big")
} else {
return number.toLong()
}
}
private fun calculateNumberOfVariations(n: Int, m: Int): BigInteger {
val numerator = factorial(n)
val denominator = factorial(n - m)
return numerator.divide(denominator)
}
fun calculateNumberOfPermutationsInt(n: Int): Int {
val f = factorial(n)
if (f > BigInteger.valueOf(Int.MAX_VALUE.toLong())) {
throw IllegalArgumentException("Value is too big")
} else {
return f.toInt()
}
}
fun calculateNumberOfPermutationsLong(n: Int): Long {
val f = factorial(n)
if (f > BigInteger.valueOf(Long.MAX_VALUE)) {
throw IllegalArgumentException("Value is too big")
} else {
return f.toLong()
}
}
private fun factorial(n: Int): BigInteger {
var result = BigInteger.ONE
for (i in 1..n) {
result = result.multiply(BigInteger.valueOf(i.toLong()))
}
return result
}
/**
* Provides all permutations of the elements in the given array.
* recursive implementation, uses list invariant
* returns array of arrays
*/
fun <T> getAllPermutations(elements: Array<T>): Array<List<T>> {
if (elements.isEmpty()) {
return arrayOf()
}
val result = MutableList(0) { listOf<T>() }
val used = BooleanArray(elements.size)
collectAllPermutations(result, used, elements, arrayListOf())
return result.toTypedArray()
}
private fun <T> collectAllPermutations(result: MutableList<List<T>>, used: BooleanArray, elements: Array<T>, selection: MutableList<T>) {
if (selection.size == elements.size) {
result.add(selection.toList())
} else {
for (i in used.indices) {
if (!used[i]) {
val usedCopy = used.clone()
usedCopy[i] = true
val selectionCopy = selection.toMutableList()
selectionCopy.add(elements[i])
collectAllPermutations(result, usedCopy, elements, selectionCopy)
}
}
}
}
data class CombinationsInvariant<T>(val value: Array<List<T>>, var index: Int) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CombinationsInvariant<*>
if (!value.contentEquals(other.value)) return false
if (index != other.index) return false
return true
}
override fun hashCode(): Int {
var result = value.contentHashCode()
result = 31 * result + index
return result
}
}
} | 0 | Kotlin | 0 | 0 | 6696f5d8bd73ce3a8dfd4200f902e2efe726cc5a | 3,683 | Algorithms | MIT License |
src/Day01.kt | tstellfe | 575,291,176 | false | {"Kotlin": 8536} | fun main() {
fun List<String>.toSummedList(): MutableList<Int> {
val summed: MutableList<Int> = mutableListOf()
var temp = 0
this.forEach {
if (it != "") temp += it.toInt()
else {
summed.add(temp)
temp = 0
}
}
summed.add(temp)
return summed
}
fun part1(input: List<String>): Int {
return input.toSummedList().max()
}
fun part2(input: List<String>): Int {
val mutableSummed = input.toSummedList().also { it.sortDescending() }
return mutableSummed[0] + mutableSummed[1] + mutableSummed[2]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
val input = readInput("Day01")
println(part2(testInput))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e100ba705c8e2b83646b172d6407475c27f02eff | 775 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/util/Pos.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.util
import kotlin.math.pow
data class Pos(val x: Int, val y: Int) : Comparable<Pos> {
override fun compareTo(other: Pos): Int {
val yCmp = y.compareTo(other.y)
return if (yCmp == 0) {
return x.compareTo(other.x)
} else {
yCmp
}
}
fun seq(startingVel: Pos) = generateSequence(this to startingVel) { (pos, velocity) ->
(pos + velocity) to velocity.copy(x = maxOf(0, velocity.x - 1), y = velocity.y - 1)
}
fun foldLeft(onPoint: Int): Pos {
return if (x > onPoint) {
val distance = x - onPoint
val delta = distance * 2
copy(x = x - delta)
} else {
this
}
}
fun foldUp(onPoint: Int): Pos {
return if (y > onPoint) {
val distance = y - onPoint
val delta = distance * 2
copy(y = y - delta)
} else {
this
}
}
fun next(move: Char?): Pos {
return when (move) {
null -> this
in "^N" -> north()
in "E>" -> east()
in "Sv" -> south()
in "W<" -> west()
else -> throw IllegalArgumentException("Don't know how to go $move")
}
}
fun manhattanDistanceTo(other: Pos): Int {
return Math.abs(other.x - x) + Math.abs(other.y - y)
}
fun directDistance(other: Pos): Double {
return Math.sqrt((other.x - x).toDouble().pow(2) + (other.y - y).toDouble().pow(2))
}
fun isInGrid(maxX: Int, maxY: Int) = isPositive() && x < maxX && y < maxY
fun isPositive(): Boolean = x >= 0 && y >= 0
fun north(): Pos = Pos(x, y - 1)
fun south(maxY: Int = Int.MAX_VALUE): Pos {
return if (y + 1 < maxY) {
Pos(x, y + 1)
} else {
Pos(x, 0)
}
}
fun west(): Pos = Pos(x - 1, y)
fun east(maxX: Int = Int.MAX_VALUE): Pos {
return if (x + 1 < maxX) {
Pos(x + 1, y)
} else {
Pos(0, y)
}
}
fun neighbours(includeSelf: Boolean = false): List<Pos> = listOf(
Pos(x - 1, y - 1), Pos(x, y - 1), Pos(x + 1, y - 1),
Pos(x - 1, y), Pos(x, y), Pos(x + 1, y),
Pos(x - 1, y + 1), Pos(x, y + 1), Pos(x + 1, y + 1)
).filter {
if (includeSelf) {
true
} else {
it != this
}
}
fun cardinalNeighbours(maxX: Int, maxY: Int): List<Pos> {
return listOf(north(), south(), west(), east()).filter { it.x >= 0 && it.y >= 0 && it.x < maxX && it.y < maxY }
}
fun toIndex(width: Int): Int = width * y + x
operator fun plus(other: Pos): Pos {
return Pos(this.x + other.x, this.y + other.y)
}
operator fun minus(other: Pos): Pos {
return Pos(this.x - other.x, this.y - other.y)
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,867 | adventofcode | MIT License |
src/main/kotlin/g0001_0100/s0047_permutations_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0047_permutations_ii
// #Medium #Array #Backtracking #Algorithm_II_Day_10_Recursion_Backtracking
// #2023_07_05_Time_199_ms_(100.00%)_Space_39.1_MB_(92.98%)
class Solution {
private var ans: MutableList<List<Int>>? = null
fun permuteUnique(nums: IntArray): List<List<Int>> {
ans = ArrayList()
permute(nums, 0)
return ans as ArrayList<List<Int>>
}
private fun permute(nums: IntArray, p: Int) {
if (p >= nums.size - 1) {
val t: MutableList<Int> = ArrayList(nums.size)
for (n in nums) {
t.add(n)
}
ans!!.add(t)
return
}
permute(nums, p + 1)
val used = BooleanArray(30)
for (i in p + 1 until nums.size) {
if (nums[i] != nums[p] && !used[10 + nums[i]]) {
used[10 + nums[i]] = true
swap(nums, p, i)
permute(nums, p + 1)
swap(nums, p, i)
}
}
}
private fun swap(nums: IntArray, i: Int, j: Int) {
val t = nums[i]
nums[i] = nums[j]
nums[j] = t
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,151 | LeetCode-in-Kotlin | MIT License |
kotlin/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | class Solution {
class DSU(val n: Int) {
val parent = IntArray(n + 1) {it}
val rank = IntArray(n + 1) {1}
var components = n
fun find(x: Int): Int {
if (parent[x] != x)
parent[x] = find(parent[x])
return parent[x]
}
fun union(x: Int, y: Int): Boolean {
val pX = find(x)
val pY = find(y)
if (pY == pX)
return false
if (rank[pX] > rank[pY]) {
rank[pX] += rank[pY]
parent[pY] = pX
} else {
rank[pY] += rank[pX]
parent[pX] = pY
}
components--
return true
}
fun connected() = components == 1
}
fun maxNumEdgesToRemove(n: Int, edges: Array<IntArray>): Int {
val a = DSU(n)
val b = DSU(n)
var edgeAdded = 0
for ((type, u, v) in edges) {
if (type == 3) {
if (a.union(u, v) or b.union(u, v))
edgeAdded++
}
}
for ((type, u, v) in edges) {
when (type) {
1 -> {
if (a.union(u, v))
edgeAdded++
}
2 -> {
if (b.union(u, v))
edgeAdded++
}
}
}
return if (a.connected() && b.connected()) edges.size - edgeAdded else -1
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,516 | leetcode | MIT License |
src/main/kotlin/day10/Day10.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package day10
import day10.OperationType.AFTER
import day10.OperationType.DURING
fun solveA(input: List<String>) = CycleTrackerB(listOf(20, 60, 100, 140, 180, 220))
.apply { parseOperations(input, type = DURING) }.strengths.sum()
fun solveB(input: List<String>) = CycleTrackerB(listOf(41, 81, 121, 161, 201, 241))
.apply { parseOperations(input, type = AFTER) }.message
enum class OperationType { DURING, AFTER }
data class CycleTrackerB(val relevantSignals: List<Int>) {
private var cycles = 1
private var register = 1
val strengths = mutableListOf<Int>()
var message = ""
fun parseOperations(operations: List<String>, type: OperationType) = operations.forEach { op ->
val amount = op.split(" ").last().toInt()
when (op) {
"noop" -> nextCycle()
else -> if (type == DURING) addDuring(amount) else addAfter(amount)
}
}
private fun addDuring(amount: Int) {
nextCycle()
addToRegister(amount)
nextCycle()
}
private fun addAfter(amount: Int) {
nextCycle()
nextCycle()
addToRegister(amount)
}
private fun addToRegister(amount: Int) {
register += amount
}
private fun nextCycle() {
message += if (isPixelInSprite()) "#" else "."
cycles++
if (cycles in relevantSignals) {
message += "\n"
strengths.add(cycles * register)
}
}
private fun isPixelInSprite() = ((cycles - 1) % crtWidth) in register - 1..register + 1
companion object {
private const val crtWidth = 40
}
}
//
////11m44s
//fun solveA(input: List<String>): Int {
//
// val strengths: MutableList<Int> = mutableListOf()
//
// val cycleTracker = CycleTracker(strengths)
//
// input.forEach {
// when {
// it == "noop" -> cycleTracker.nextCycle()
// else -> {
// cycleTracker.nextCycle()
// val add = it.split(" ").last().toInt()
// cycleTracker.addToRegister(add)
// cycleTracker.nextCycle()
// }
// }
// }
//
// return strengths.sum()
//}
//
//data class CycleTracker(val strengths: MutableList<Int>) {
// private var cycles = 1
// private var register = 1
//
// private val relevantSignals = listOf(20, 60, 100, 140, 180, 220)
//
//
// fun nextCycle() {
// cycles++
// if (cycles in relevantSignals) strengths.add(cycles * register)
// }
//
// fun addToRegister(amount: Int) {
// register += amount
// }
//}
//
//data class CycleTrackerB(val strengths: MutableList<Int>) {
// private var cycles = 1
// private var register = 1
//
// private val relevantSignals = listOf(41, 81, 121, 161, 201, 241)
//
//
// fun nextCycle() {
//// println("During Cycle $cycles")
//// println("CRT draws pixel in position ${cycles - 1} ")
//
// if (((cycles - 1) % 40) in register - 1..register + 1) print("#")
// else print(".")
//
// cycles++
//
// if (cycles in relevantSignals) {
// println()
// strengths.add(cycles * register)
// }
//// println("Sprite position ${listOf(register - 1, register, register + 1)} ")
// }
//
// fun addToRegister(amount: Int) {
// register += amount
// }
//}
//
////27m55s
//
//fun solveB(input: List<String>): Int {
// val strengths: MutableList<Int> = mutableListOf()
//
// val cycleTracker = CycleTrackerB(strengths)
//
// input.forEach {
// when {
// it == "noop" -> cycleTracker.nextCycle()
// else -> {
// cycleTracker.nextCycle()
// cycleTracker.nextCycle()
// val add = it.split(" ").last().toInt()
// cycleTracker.addToRegister(add)
// }
// }
// }
//
// return strengths.sum()
//}
| 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 3,910 | advent-of-code-2022 | Apache License 2.0 |
src/day12.kt | eldarbogdanov | 577,148,841 | false | {"Kotlin": 181188} | fun main() {
val test = ""
val di = listOf(-1, 0, 1, 0);
val dj = listOf(0, 1, 0, -1);
val mat = test.split("\n");
val n = mat.size;
val m = mat[0].length;
val best = Array(n) {Array(m) {n * m} };
val next: MutableList<Pair<Int, Int>> = mutableListOf();
for((i, s) in mat.withIndex()) {
for(j in 0 until s.length) {
// remove the 'a' clause for first subproblem
if (mat[i][j] == 'S' || mat[i][j] == 'a') {
next.add(Pair(i, j));
best[i][j] = 0;
}
}
}
var curInd = 0;
while(curInd < next.size) {
val cur = next[curInd++];
for(d in 0..3) {
val newPos = Pair(cur.first + di[d], cur.second + dj[d]);
if (newPos.first < 0 || newPos.first >= n || newPos.second < 0 || newPos.second >= m) continue;
val curHeight = if (mat[cur.first][cur.second] == 'S') 0 else mat[cur.first][cur.second] - 'a';
val newHeight = if (mat[newPos.first][newPos.second] == 'E') 25 else mat[newPos.first][newPos.second] - 'a';
if (curHeight + 1 >= newHeight &&
best[newPos.first][newPos.second] > best[cur.first][cur.second] + 1) {
best[newPos.first][newPos.second] = best[cur.first][cur.second] + 1;
next.add(newPos);
}
}
}
for((i, s) in mat.withIndex()) {
for(j in 0 until s.length) {
if (mat[i][j] == 'E') {
println(best[i][j]);
}
}
}
}
| 0 | Kotlin | 0 | 0 | bdac3ab6cea722465882a7ddede89e497ec0a80c | 1,555 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/leetcode/Problem2012.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
import kotlin.math.max
import kotlin.math.min
/**
* https://leetcode.com/problems/sum-of-beauty-in-the-array/
*/
class Problem2012 {
fun sumOfBeauties(nums: IntArray): Int {
val left = IntArray(nums.size)
for ((i, n) in nums.withIndex()) {
left[i] = if (i == 0) n else max(left[i - 1], n)
}
val right = IntArray(nums.size)
for (i in nums.size - 1 downTo 0) {
right[i] = if (i == nums.size - 1) nums[i] else min(right[i + 1], nums[i])
}
var answer = 0
for (i in 1..nums.size - 2) {
if (left[i - 1] < nums[i] && nums[i] < right[i + 1]) {
answer += 2
} else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) {
answer++
}
}
return answer
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 841 | leetcode | MIT License |
cinema_manager.kt | fufaevlad | 626,465,141 | false | null | var ifCount = 0
var elseCount = 0
const val cheapSeatCoast = 8
const val expSeatCoast = 10
fun main() {
val (rows,seats) = greeting()
val cinema = mutListCreator(rows)
boardFiller(cinema,rows,seats)
multipleChoise(cinema,rows,seats)
}
fun greeting(): Pair<Int,Int>{
println("Enter the number of rows:")
val rows = readln().toInt()
println("Enter the number of seats in each row:")
val seats = readln().toInt()
return Pair(rows,seats)
}
fun mutListCreator(rows:Int):MutableList<MutableList<String>>{
val outList = mutableListOf<MutableList<String>>()
for(i in 0 until rows){
val a = mutableListOf<String>()
outList.add(a)
}
return outList
}
fun boardFiller(list: MutableList<MutableList<String>>, rows:Int, columns:Int){
for(j in 0 until columns) {
for (i in 0 until rows) {
list[i].add("S ")
}
}
}
fun boardPrint(list:MutableList<MutableList<String>>,rows:Int,seats:Int){
println("Cinema:")
print(" ")
for(i in 1 until seats+1){
print("$i ")
}
println()
for(i in 0 until rows) {
println("${i+1} ${list[i].joinToString("")}")
}
}
fun seatChoise(list:MutableList<MutableList<String>>,rows:Int,seats:Int){
println("Enter a row number:")
val r = readln().toInt()
println("Enter a seat number in that row:")
val s = readln().toInt()
if(r>rows||s>seats) {
println("Wrong input!")
seatChoise(list, rows, seats)
} else if(list[r-1][s-1] == "B "){
println("That ticket has already been purchased!")
seatChoise(list,rows,seats)
} else {
if (rows * seats <= 60) {
println("Ticket price: $$expSeatCoast")
ifCount++
} else if (rows * seats > 60) {
if (r <= rows / 2) {
println("Ticket price: $$expSeatCoast")
ifCount++
} else if (r > rows / 2) {
println("Ticket price: $$cheapSeatCoast")
elseCount++
}
}
list[r - 1][s - 1] = "B "
}
}
fun statistics(rows:Int,seats:Int){
val allTicets = ifCount + elseCount
val allSeats = rows*seats
val percentage:Double = allTicets.toDouble()/allSeats.toDouble()*100
val formatPercentage = "%.2f".format(percentage)
val currentIncome = (ifCount * expSeatCoast) + (elseCount * cheapSeatCoast)
var totalIncome = 0
if(rows*seats <= 60) {
totalIncome = rows*seats*expSeatCoast
} else if(rows*seats > 60){
totalIncome = rows/2*expSeatCoast*seats + (rows - rows/2)*cheapSeatCoast*seats
}
println("Number of purchased tickets: $allTicets")
println("Percentage: $formatPercentage%")
println("Current income: $$currentIncome")
println("Total income: $$totalIncome")
}
fun multipleChoise(list:MutableList<MutableList<String>>,rows:Int,seats:Int){
println("1. Show the seats")
println("2. Buy a ticket")
println("3. Statistics")
println("0. Exit")
val num = readln().toInt()
when(num){
1 -> {
boardPrint(list, rows, seats)
multipleChoise(list, rows, seats)
}
2 -> {
seatChoise(list, rows, seats)
boardPrint(list, rows, seats)
multipleChoise(list, rows, seats)
}
3-> {
statistics(rows, seats)
multipleChoise(list, rows, seats)
}
}
}
| 0 | Kotlin | 0 | 0 | b81d03b6942e7c1cd10efa67864f3a021fe203b9 | 3,461 | hyperskill_test_cinema_room_manager | MIT License |
src/main/kotlin/abc/287-c.kt | kirimin | 197,707,422 | false | null | package abc
import utilities.debugLog
import java.util.*
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
val n = sc.nextInt()
val m = sc.nextInt()
val uv = (0 until m).map { sc.next().toInt() to sc.next().toInt() }
println(problem287c(n, m, uv))
}
fun problem287c(n: Int, m: Int, uv: List<Pair<Int, Int>>): String {
class UnionFind(n: Int) {
private val parent = IntArray(n) { -1 }
fun root(x: Int): Int {
if (parent[x] < 0) return x
parent[x] = root(parent[x])
return parent[x]
}
fun isSameRoot(x: Int, y: Int) = root(x) == root(y)
fun merge(x: Int, y: Int) {
var xRoot = root(x)
var yRoot = root(y)
if (xRoot == yRoot) return
if (parent[xRoot] > parent[yRoot]){
val tmp = xRoot
xRoot = yRoot
yRoot = tmp
}
parent[xRoot] += parent[yRoot]
parent[yRoot] = xRoot
}
fun groupSize(x: Int) = -parent[root(x)]
override fun toString(): String {
return parent.toString()
}
}
val unionFind = UnionFind(n)
// グループを生成
for (i in 0 until m) {
val (a, b) = uv[i]
if (unionFind.isSameRoot(a - 1, b - 1)) {
// 閉路がある
}
unionFind.merge(a - 1, b - 1)
}
var root = unionFind.root(0)
val routes = Array(n + 1) { mutableListOf<Int>() }
for (i in 0 until m) {
val (a, b) = uv[i]
routes[a - 1].add(b - 1)
routes[b - 1].add(a - 1)
}
val distances = IntArray(n) { -1 }
val queue = ArrayDeque<Int>()
queue.offer(root)
distances[root] = 0
while(!queue.isEmpty()) {
val current = queue.poll()
for (i in 0 until routes[current].size) {
val next = routes[current][i]
if (distances[next] != -1) {
continue
}
distances[next] = distances[current] + 1
queue.offer(next)
}
}
return if (distances.sorted() == (0 until n).toList()) "Yes" else "No"
} | 0 | Kotlin | 1 | 5 | 23c9b35da486d98ab80cc56fad9adf609c41a446 | 2,171 | AtCoderLog | The Unlicense |
src/main/kotlin/com/github/brpeterman/advent2022/KeepAway.kt | brpeterman | 573,059,778 | false | {"Kotlin": 53108} | package com.github.brpeterman.advent2022
import java.util.LinkedList
import java.util.SortedMap
typealias ArithmeticOperation = (Long, Long) -> Long
typealias MonkeyRule = (Long) -> KeepAway.ItemPass
class KeepAway(input: String, worryDecay: Int) {
data class Monkey(val holding: LinkedList<Long>, val rule: MonkeyRule, val divisor: Int, var inspectionCount: Int = 0)
data class ItemPass(val to: Int, val worryLevel: Long)
enum class Operation(val function: ArithmeticOperation) {
ADD({ a, b -> a + b }),
MULTIPLY({ a, b -> a * b })
}
val monkeys = parseInput(input, worryDecay)
val commonMultiple = calculateCommonMultiple(monkeys.values)
fun calculateMonkeyBusiness(): Long {
return monkeys.values.map { it.inspectionCount.toLong() }
.sorted()
.reversed()
.subList(0, 2)
.reduce { product, count -> product * count }
}
fun simulate(rounds: Int) {
(0 until rounds).forEach {
monkeys.values
.forEach { monkey -> takeTurn(monkey) }
}
}
fun takeTurn(monkey: Monkey) {
while (monkey.holding.isNotEmpty()) {
val item = monkey.holding.pop()
val result = monkey.rule.invoke(item)
monkeys[result.to]!!.holding.add(result.worryLevel)
monkey.inspectionCount++
}
}
fun parseInput(input: String, worryDecay: Int): SortedMap<Int, Monkey> {
return input.split("\n\n")
.withIndex()
.map { (index, monkeyDef) ->
val lines = monkeyDef.split("\n")
val startingItems = parseStartingItems(lines[1])
val (divisorStr) = """divisible by (\d+)""".toRegex()
.find(lines[3])!!
.destructured
val divisor = divisorStr.toInt()
val rule = parseRule(divisor, lines[2], lines[4], lines[5], worryDecay)
index to Monkey(startingItems, rule, divisor)
}
.toMap()
.toSortedMap()
}
fun parseStartingItems(line: String): LinkedList<Long> {
return LinkedList(""" (\d+),?""".toRegex().findAll(line)
.map {
val (num) = it.destructured
num.toLong()
}
.toList())
}
fun calculateCommonMultiple(monkeys: Collection<Monkey>): Long {
return monkeys.fold(1, { product, m -> product * m.divisor.toLong() })
}
fun parseRule(divisor: Int, operationLine: String, trueLine: String, falseLine: String, worryDecay: Int): MonkeyRule {
val (operator, operandStr) = """new = old ([+*]) (\d+|old)""".toRegex()
.find(operationLine)!!
.destructured
val operatorFunction = when (operator) {
"+" -> Operation.ADD
"*" -> Operation.MULTIPLY
else -> throw IllegalStateException("Unexpected operator: ${operator}")
}
val (trueMonkeyStr) = """monkey (\d+)""".toRegex()
.find(trueLine)!!
.destructured
val (falseMonkeyStr) = """monkey (\d+)""".toRegex()
.find(falseLine)!!
.destructured
val trueMonkey = trueMonkeyStr.toInt()
val falseMonkey = falseMonkeyStr.toInt()
return constructRuleFunction(operatorFunction, operandStr, divisor, trueMonkey, falseMonkey, worryDecay)
}
fun constructRuleFunction(operatorFunction: Operation, operandStr: String, divisor: Int, trueMonkey: Int, falseMonkey: Int, worryDecay: Int): MonkeyRule {
return { old ->
val operand = if (operandStr == "old") {
old
} else {
operandStr.toLong()
}
var new = operatorFunction.function.invoke(old, operand)
new = if (worryDecay > 1) {
new / worryDecay
} else {
new % commonMultiple
}
if (new % divisor == 0L) {
ItemPass(trueMonkey, new)
} else {
ItemPass(falseMonkey, new)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 1407ca85490366645ae3ec86cfeeab25cbb4c585 | 4,165 | advent2022 | MIT License |
src/main/kotlin/me/peckb/aoc/_2023/calendar/day11/Day11.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2023.calendar.day11
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Day11 @Inject constructor(
private val generatorFactory: InputGeneratorFactory
) {
fun partOne(filename: String) = generatorFactory.forFile(filename).read { input ->
val spaceSize = 2L
findSum(input, spaceSize)
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input ->
val spaceSize = 1_000_000L
findSum(input, spaceSize)
}
private fun findSum(input: Sequence<String>, spaceSize: Long): Long {
val area = input.map { line ->
mutableListOf<Char>().apply {
line.forEach { c -> this.add(c) }
}
}.toMutableList()
val (emptyRows, emptyColumns) = findEmpties(area)
val stars = mutableListOf<Location>()
area.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, c ->
if (c == '#') stars.add(Location(rowIndex, colIndex))
}
}
var distanceSum = 0L
stars.indices.forEach { firstStarIndex ->
((firstStarIndex + 1) until stars.size).forEach { secondStarIndex ->
val s1 = stars[firstStarIndex]
val s2 = stars[secondStarIndex]
val minRow = min(s1.row, s2.row)
val maxRow = max(s1.row, s2.row)
val minCol = min(s1.col, s2.col)
val maxCol = max(s1.col, s2.col)
val extraRows = emptyRows.count { ((minRow + 1) until maxRow).contains(it) }
val extraColumns = emptyColumns.count { ((minCol + 1) until maxCol).contains(it) }
distanceSum += s1.distanceFrom(s2) + ((spaceSize - 1) * (extraColumns + extraRows))
}
}
return distanceSum
}
private fun findEmpties(initialArea: MutableList<MutableList<Char>>): Pair<List<Int>, List<Int>> {
val emptyRows = mutableListOf<Int>()
val emptyColumns = mutableListOf<Int>()
initialArea.forEachIndexed { rowIndex, row ->
if (row.none { it == '#' }) emptyRows.add(rowIndex)
}
initialArea[0].indices.forEach { columnIndex ->
if (initialArea.indices.none { initialArea[it][columnIndex] == '#' }) emptyColumns.add(columnIndex)
}
return emptyRows to emptyColumns
}
data class Location(val row: Int, val col: Int) {
fun distanceFrom(s2: Location): Long {
return (abs(row - s2.row) + abs(col -s2.col)).toLong()
}
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 2,451 | advent-of-code | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.