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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
WorldviewGenerator/src/shmp/generator/culture/worldview/reasoning/Reasonings.kt | ShMPMat | 212,499,539 | false | null | package shmp.generator.culture.worldview.reasoning
import shmp.generator.culture.worldview.reasoning.concept.ActionConcept
import shmp.generator.culture.worldview.reasoning.concept.ObjectConcept
import shmp.generator.culture.worldview.reasoning.concept.ReasonConcept
import shmp.generator.culture.worldview.Meme
open class BaseReasoning(
override val meme: Meme,
override val additionalMemes: List<Meme>,
override val conclusions: List<ReasonConclusion>
) : AbstractReasoning()
class AssociationReasoning(val firstAssociation: ReasonConcept, val secondAssociation: ReasonConcept) : BaseReasoning(
Meme("$firstAssociation associates with $secondAssociation"),
listOf(firstAssociation.meme, secondAssociation.meme),
listOf()
) {
val isOppositions = any { it in firstAssociation.oppositeConcepts || it in secondAssociation.oppositeConcepts }
fun toList() = listOf(firstAssociation, secondAssociation)
fun any(predicate: (ReasonConcept) -> Boolean) = predicate(firstAssociation) || predicate(secondAssociation)
fun all(predicate: (ReasonConcept) -> Boolean) = predicate(firstAssociation) && predicate(secondAssociation)
fun <T> applyToBoth(action: (ReasonConcept, ReasonConcept) -> T?): List<T> {
return listOf(action(firstAssociation, secondAssociation), action(secondAssociation, firstAssociation)).mapNotNull { it }
}
}
class EqualityReasoning(val objectConcept: ReasonConcept, val subjectConcept: ReasonConcept) : BaseReasoning(
Meme("$objectConcept represents $subjectConcept"),
listOf(objectConcept.meme, subjectConcept.meme),
listOf()
) {
val isOppositions = any { it in subjectConcept.oppositeConcepts || it in objectConcept.oppositeConcepts }
fun toList() = listOf(objectConcept, subjectConcept)
fun any(predicate: (ReasonConcept) -> Boolean) = predicate(objectConcept) || predicate(subjectConcept)
fun all(predicate: (ReasonConcept) -> Boolean) = predicate(objectConcept) && predicate(subjectConcept)
fun <T> applyToBoth(action: (ReasonConcept, ReasonConcept) -> T?): List<T> {
return listOfNotNull(action(objectConcept, subjectConcept), action(subjectConcept, objectConcept))
}
}
class OppositionReasoning(val objectConcept: ReasonConcept, val subjectConcept: ReasonConcept) : BaseReasoning(
Meme("$objectConcept opposes $subjectConcept"),
listOf(objectConcept.meme, subjectConcept.meme),
listOf()
)
class ActionReasoning(val objectConcept: ReasonConcept, val actionConcept: ActionConcept) : BaseReasoning(
Meme("$objectConcept needs $actionConcept"),
listOf(objectConcept.meme, actionConcept.meme),
listOf()
)
class ExistenceInReasoning(val subjectConcept: ObjectConcept, val surroundingConcept: ReasonConcept) : BaseReasoning(
Meme("$subjectConcept live in $surroundingConcept"),
listOf(subjectConcept.meme, surroundingConcept.meme),
listOf()
)
class ConceptBoxReasoning(val concept: ReasonConcept) : AbstractReasoning() {
override val meme = concept.meme
override val additionalMemes = listOf<Meme>()
override val conclusions = listOf<ReasonConclusion>()
}
| 0 | Kotlin | 0 | 0 | 9fc6faafa1dbd9737dac71dc8a77960accdae81f | 3,202 | CulturesSim | MIT License |
leetcode/src/linkedlist/Q21.kt | zhangweizhe | 387,808,774 | false | null | package linkedlist
import linkedlist.kt.ListNode
fun main() {
// https://leetcode-cn.com/problems/merge-two-sorted-lists/
val l1 = LinkedListUtil.createList(intArrayOf(1, 2, 4))
val l2 = LinkedListUtil.createList(intArrayOf(1, 3, 4))
LinkedListUtil.printLinkedList(mergeTwoLists(l1, l2))
}
/**
* 递归
*/
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
when {
l1 == null -> {
return l2
}
l2 == null -> {
return l1
}
l1.`val` < l2.`val` -> {
l1.next = mergeTwoLists(l1.next, l2)
return l1
}
else -> {
l2.next = mergeTwoLists(l1, l2.next)
return l2
}
}
}
/**
* 双指针
*/
fun mergeTwoLists1(l1: ListNode?, l2: ListNode?): ListNode? {
if (l1 == null && l2 == null) {
return null
}
if (l1 == null) {
return l2
}
if (l2 == null) {
return l1
}
var head = ListNode(0)
var cur = head
var p1 = l1
var p2 = l2
while (p1 != null && p2 != null) {
if (p1.`val` > p2.`val`) {
cur.next = ListNode(p2.`val`)
p2 = p2.next
}else {
cur.next = ListNode(p1.`val`)
p1 = p1.next
}
cur = cur.next!!
}
if (p1 != null) {
cur.next = p1
}
if (p2 != null) {
cur.next = p2
}
return head.next
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,438 | kotlin-study | MIT License |
2023/src/main/kotlin/net/daams/solutions/3a.kt | Michiel-Daams | 573,040,288 | false | {"Kotlin": 39925, "Nim": 34690} | package net.daams.solutions
import net.daams.Solution
class `3a`(input: String): Solution(input) {
private val allNumbers: MutableList<List<Pair<String, Int>>> = mutableListOf()
private val allSymbols: MutableList<List<Int>> = mutableListOf()
private val adjacentNumbers: MutableList<Int> = mutableListOf()
private var currentNumber = ""
private var currentIndex = -1
override fun run() {
val splitInput = input.split("\n")
// find numbers + starting index per number
splitInput.forEach{
val numbers : MutableList<Pair<String, Int>> = mutableListOf()
it.forEachIndexed { index, s ->
if (!s.isDigit() && currentNumber != "") {
numbers.add(Pair(currentNumber, currentIndex))
}
if (currentNumber.equals("")) currentIndex = index
if (s.isDigit()) currentNumber += s else currentNumber = ""
if (index + 1 == it.length && currentNumber != "") numbers.add(Pair(currentNumber, currentIndex))
}
currentNumber = ""
currentIndex = -1
allNumbers.add(numbers.toList())
}
splitInput.forEach{
val indices: MutableList<Int> = mutableListOf()
it.forEachIndexed{ index, s ->
if (!s.isDigit() && s != '.') indices.add(index)
}
allSymbols.add(indices.toList())
}
allNumbers.forEachIndexed{ indexY, pairList ->
pairList.forEach {
if (isInRange(it, indexY)) adjacentNumbers.add(it.first.toInt())
}
}
println(adjacentNumbers.sum())
}
fun isInRange(xs: Pair<String, Int>, y: Int): Boolean {
for(x: Int in xs.second - 1 .. xs.second + xs.first.length) {
if (x < 0 || x > 139) continue
for (yy: Int in y - 1 .. y + 1) {
if (yy < 0 || yy > 139) continue
if (allSymbols[yy].contains(x)) return true
}
}
return false
}
} | 0 | Kotlin | 0 | 0 | f7b2e020f23ec0e5ecaeb97885f6521f7a903238 | 2,074 | advent-of-code | MIT License |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D18.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2020
import io.github.pshegger.aoc.common.BaseSolver
@ExperimentalStdlibApi
class Y2020D18 : BaseSolver() {
override val year = 2020
override val day = 18
override fun part1(): Long =
parseInput(false).fold(0L) { acc, expression ->
acc + expression.apply()
}
override fun part2(): Long =
parseInput(true).fold(0L) { acc, expression ->
acc + expression.apply()
}
private fun parseInput(plusPrecedence: Boolean) = readInput {
readLines().map { parseAsExpression(it.trim(), plusPrecedence) }
}
private fun parseAsExpression(str: String, plusPrecedence: Boolean): Expression {
if (str.startsWith("(") && str.endsWith(")")) {
var ctr = 1
var i = 0
while (ctr > 0) {
i++
if (str[i] == '(') ctr++
if (str[i] == ')') ctr--
}
if (i == str.length - 1) {
return parseAsExpression(str.drop(1).dropLast(1), plusPrecedence)
}
}
val parts = buildList<String> {
val parts = str.split(" ")
var i = 0
while (i < parts.size) {
if (parts[i].startsWith("(")) {
val startI = i
var ctr = parts[i].count { it == '(' }
while (ctr > 0) {
i++
ctr += parts[i].takeWhile { it == '(' }.count()
ctr -= parts[i].takeLastWhile { it == ')' }.count()
}
add(parts.drop(startI).take(i - startI + 1).joinToString(" "))
} else {
add(parts[i])
}
i++
}
}
if (parts.size == 1) return Expression.Number(parts[0].toLong())
if (plusPrecedence && parts.size > 3) {
val plusIndex = parts.indexOfFirst { it == "+" }
if (plusIndex > 0) {
val newParts = parts.take(plusIndex - 1) +
"(${parts[plusIndex - 1]} + ${parts[plusIndex + 1]})" +
parts.drop(plusIndex + 2)
return parseAsExpression(newParts.joinToString(" "), plusPrecedence)
}
}
val lastOperatorIndex = parts.indexOfLast { it == "*" || it == "+" }
val op1 = parts.take(lastOperatorIndex).joinToString(" ")
val op2 = parts.drop(lastOperatorIndex + 1).joinToString(" ")
return when (parts[lastOperatorIndex]) {
"+" -> Expression.OpPlus(parseAsExpression(op1, plusPrecedence), parseAsExpression(op2, plusPrecedence))
"*" -> Expression.OpTimes(parseAsExpression(op1, plusPrecedence), parseAsExpression(op2, plusPrecedence))
else -> error("WTF: $str")
}
}
private sealed class Expression {
data class OpTimes(val op1: Expression, val op2: Expression) : Expression()
data class OpPlus(val op1: Expression, val op2: Expression) : Expression()
data class Number(val value: Long) : Expression()
fun apply(): Long = when (this) {
is OpTimes -> op1.apply() * op2.apply()
is OpPlus -> op1.apply() + op2.apply()
is Number -> value
}
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 3,345 | advent-of-code | MIT License |
src/Day10.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | fun main() {
fun part1(input: List<String>): Int {
var nextCycle = 20
var curCycle = 0
var x = 1
var res = 0
for (line in input) {
if (line == "noop") {
curCycle++
if (curCycle == nextCycle) {
res += nextCycle * x
nextCycle += 40
}
} else {
val v = line.split(" ")[1].toInt()
x += v
curCycle += 2
if (curCycle >= nextCycle) {
res += nextCycle * (x - v)
nextCycle += 40
}
}
}
return res
}
fun part2(input: List<String>): Int {
val a: MutableList<Int> = mutableListOf()
var curCycle = 0
var x = 1
for (line in input) {
a.add(x)
if (line == "noop") {
curCycle++
} else {
a.add(x)
val v = line.split(" ")[1].toInt()
x += v
curCycle += 2
}
}
for (i in 1 until 241) {
if (((i - 1) % 40) in a[i - 1] - 1..a[i - 1] + 1) {
print("#")
} else {
print(".")
}
if (i % 40 == 0) {
println()
}
}
return a.size
}
part1(readInput("input")).println()
part2(readInput("input"))
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 1,492 | advent-of-code-2022 | Apache License 2.0 |
kotlinP/src/main/java/com/jadyn/kotlinp/leetcode/linknode/LinkNode-0.kt | JadynAi | 136,196,478 | false | null | package com.jadyn.kotlinp.leetcode.linknode
import org.w3c.dom.Node
import kotlin.random.Random
/**
*JadynAi since 4/5/21
*/
fun main() {
val first = ListNode(1)
val random = Random(3)
var next = first
val set = hashSetOf<Int>()
for (i in 0..6) {
var v = random.nextInt(0, 66)
while (set.contains(v)) {
v = random.nextInt(0, 66)
}
set.add(v)
val node = ListNode(v)
next.next = node
next = node
}
printNode(first)
// printNode(reverseNode1(first))
// printNode(reverseBetween(first, 1, 4))
println("find mid ${findMidNode(first).vv}")
}
/**
* 快慢指针找中心
* */
fun findMidNode(head: ListNode?): ListNode? {
var fast = head
var slow = head
while (fast?.next != null && fast.next?.next != null) {
println("fast ${fast.vv} slow ${slow.vv}")
fast = fast.next?.next
slow = slow?.next
}
return slow
}
/**
* 反转部分链表
* 这个关键思想是 首先添加一个虚假的头链表,这个是为了防止越界
*
* 先找到left的前一个节点
* 保留left的节点
* 然后反转left -> end 的链表
* 然后拿到pre
* 将left的前一个节点的next指向pre
* 然后用之前保留的left的节点指向最后一个end的节点
* */
fun reverseBetween(head: ListNode?, left: Int, right: Int): ListNode? {
val fake = ListNode(-1)
fake.next = head
var startNode: ListNode? = fake
var index = 1
while (startNode != null && index < left) {
startNode = startNode.next
index++
}
var cur = startNode?.next
val last = cur
var next = cur
var pre: ListNode? = null
var starIndex = left
while (cur != null && starIndex <= right) {
next = cur.next
cur.next = pre
pre = cur
cur = next
starIndex++
}
startNode?.next = pre
last?.next = next
return fake.next
}
// 反转链表
fun reverseNode(f: ListNode?): ListNode? {
if (f?.next == null) return f
val last = reverseNode(f.next)
f.next?.next = f
f.next = null
return last
}
// 迭代思想解决链表反转问题
fun reverseNode1(f: ListNode?): ListNode? {
var pre: ListNode? = null
var cur = f
var nxt = f
while (cur != null) {
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
}
return pre
}
fun reverseNode2(head: ListNode?): ListNode? {
val fakeHead = ListNode(-1)
fakeHead.next = head
return fakeHead.next
}
//--------------base function-----------------------
val ListNode?.vv: Int
get() = this?.v ?: -1
fun printNode(f: ListNode?) {
var n: ListNode? = f
val s = StringBuilder()
while (n != null) {
s.append("${",".takeIf { s.isNotBlank() } ?: ""}${n.v}")
n = n.next
}
println(s)
}
class ListNode(val v: Int) {
var next: ListNode? = null
}
| 0 | Kotlin | 6 | 17 | 9c5efa0da4346d9f3712333ca02356fa4616a904 | 2,926 | Kotlin-D | Apache License 2.0 |
src/main/kotlin/g1301_1400/s1326_minimum_number_of_taps_to_open_to_water_a_garden/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1301_1400.s1326_minimum_number_of_taps_to_open_to_water_a_garden
// #Hard #Array #Dynamic_Programming #Greedy
// #2023_06_06_Time_189_ms_(100.00%)_Space_38.5_MB_(42.86%)
class Solution {
fun minTaps(n: Int, ranges: IntArray): Int {
if (n == 0 || ranges.size == 0) {
return if (n == 0) 0 else -1
}
val dp = IntArray(n + 1)
var nxtLargest = 0
var current = 0
var amount = 0
for (i in ranges.indices) {
if (ranges[i] > 0) {
val ind = Math.max(0, i - ranges[i])
dp[ind] = Math.max(dp[ind], i + ranges[i])
}
}
for (i in 0..n) {
nxtLargest = Math.max(nxtLargest, dp[i])
if (i == current && i < n) {
current = nxtLargest
amount++
}
if (current < i) {
return -1
}
}
return amount
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 959 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/info/jukov/adventofcode/y2022/Day13.kt | jukov | 572,271,165 | false | {"Kotlin": 78755} | package info.jukov.adventofcode.y2022
import info.jukov.adventofcode.Day
import org.json.JSONArray
import java.io.BufferedReader
/**
* Thanks to some dude from vas3k whiteboard chat who point me that
* puzzle input is valid json arrays.
*/
object Day13 : Day() {
override val year: Int = 2022
override val day: Int = 13
override fun part1(reader: BufferedReader): String {
val pairs = parse(reader)
return pairs
.windowed(2, 2)
.withIndex()
.map { (index, pair) ->
val first = pair.component1()
val second = pair.component2()
index + 1 to compare(first, second)
}
.filter { (_, value) -> value == -1 }
.sumOf { (index, _) -> index }
.toString()
}
override fun part2(reader: BufferedReader): String {
val pairs = parse(reader)
val divider1 = JSONArray(listOf(2))
val divider2 = JSONArray(listOf(6))
val sorted = pairs
.toMutableList()
.apply {
add(divider1)
add(divider2)
}
.sortedWith(::compare)
return ((sorted.indexOf(divider1) + 1) * (sorted.indexOf(divider2) + 1)).toString()
}
private fun parse(reader: BufferedReader): List<JSONArray> =
reader
.lineSequence()
.mapNotNull { line ->
if (line.isNotEmpty()) {
JSONArray(line)
} else {
null
}
}
.toList()
private fun compare(first: Any, second: Any): Int {
when {
first is Int && second is Int && first != second -> {
return if (first < second) -1 else 1
}
first is JSONArray && second is JSONArray -> {
for (i in 0 until first.length()) {
val firstVal = first[i]
val secondVal = second.opt(i)
return if (secondVal == null) {
1
} else {
val comparison = compare(firstVal, secondVal)
if (comparison == 0) {
continue
} else {
return comparison
}
}
}
if (second.length() == first.length()) {
return 0
}
if (second.length() > first.length()) {
return -1
}
}
first is JSONArray && second is Int -> {
return compare(first, JSONArray(listOf(second)))
}
first is Int && second is JSONArray -> {
return compare(JSONArray(listOf(first)), second)
}
}
return 0
}
}
| 0 | Kotlin | 1 | 0 | 5fbdaf39a508dec80e0aa0b87035984cfd8af1bb | 2,952 | AdventOfCode | The Unlicense |
src/main/kotlin/co/csadev/advent2021/Day25.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2021 by <NAME>
* Advent of Code 2021, Day 25
* Problem Description: http://adventofcode.com/2021/day/25
*/
package co.csadev.advent2021
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Point2D
import co.csadev.adventOfCode.Resources.resourceAsList
class Day25(override val input: List<String> = resourceAsList("21day25.txt")) :
BaseDay<List<String>, Int, Int> {
private val height = input.size
private val width = input.first().length
private val state = input.flatMapIndexed { y, l ->
l.mapIndexedNotNull { x, c ->
if (c == '.') {
null
} else {
Point2D(x, y) to c
}
}
}.toMap().toMutableMap()
override fun solvePart1(): Int {
var runState = state.toMap()
var lastState: String
var count = 0
do {
count++
lastState = runState.toSortedMap().toString()
runState = runState.mapKeys { (p, c) ->
if (c != '>') return@mapKeys p
val movePoint = p.copy(x = (p.x + 1) % width)
if (runState.containsKey(movePoint)) p else movePoint
}
runState = runState.mapKeys { (p, c) ->
if (c != 'v') return@mapKeys p
val movePoint = p.copy(y = (p.y + 1) % height)
if (runState.containsKey(movePoint)) p else movePoint
}
} while (runState.toSortedMap().toString() != lastState)
return count
}
@Suppress("unused")
private fun Map<Point2D, Char>.printState() {
(0..keys.maxOf { it.y }).forEach { y ->
val line = (0..keys.maxOf { it.x }).fold("") { acc, x ->
val p = Point2D(x, y)
acc + getOrDefault(p, '.')
}
println(line)
}
println()
}
override fun solvePart2() = 0
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 1,938 | advent-of-kotlin | Apache License 2.0 |
src/main/kotlin/g2101_2200/s2122_recover_the_original_array/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2101_2200.s2122_recover_the_original_array
// #Hard #Array #Hash_Table #Sorting #Enumeration
// #2023_06_25_Time_299_ms_(100.00%)_Space_40.1_MB_(100.00%)
class Solution {
private lateinit var res: IntArray
fun recoverArray(nums: IntArray): IntArray {
val n = nums.size
nums.sort()
val diffs = ArrayList<Int>()
val smallest = nums[0]
for (i in 1 until n) {
val k = (nums[i] - smallest) / 2
if ((nums[i] - smallest) % 2 == 0 && k != 0) {
diffs.add(k)
}
}
for (k in diffs) {
if (check(n, k, nums)) {
break
}
}
return res
}
private fun check(n: Int, k: Int, nums: IntArray): Boolean {
res = IntArray(n / 2)
val visited = BooleanArray(n)
var lower = 0
var higher = 1
var count = 0
while (lower < n) {
if (visited[lower]) {
lower++
continue
}
val lowerVal = nums[lower]
val higherVal = lowerVal + 2 * k
while (higher < n) {
if (nums[higher] == higherVal && !visited[higher]) {
break
}
higher++
}
if (higher == n) {
return false
}
visited[lower] = true
visited[higher] = true
res[count] = lowerVal + k
count++
if (count == n / 2) {
return true
}
lower++
higher++
}
return false
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,660 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/be/inniger/euler/problems01to10/Problem06.kt | bram-inniger | 135,620,989 | false | {"Kotlin": 20003} | package be.inniger.euler.problems01to10
private const val MAX_VALUE = 100
/**
* Sum square difference
*
* The sum of the squares of the first ten natural numbers is,
* 1^2 + 2^2 + ... + 10^2 = 385
* The square of the sum of the first ten natural numbers is,
* (1 + 2 + ... + 10)^2 = 55^2 = 3025
* Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
* Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
*/
fun solve06() = (1..MAX_VALUE).sum().let { it * it } -
(1..MAX_VALUE).map { it * it }.sum()
| 0 | Kotlin | 0 | 0 | 8fea594f1b5081a824d829d795ae53ef5531088c | 663 | euler-kotlin | MIT License |
csp-framework/src/main/kotlin/com/tsovedenski/csp/Job.kt | RedShuhart | 152,120,429 | false | null | package com.tsovedenski.csp
import com.tsovedenski.csp.heuristics.ordering.comparators.VariableComparator
import com.tsovedenski.csp.heuristics.pruning.PruneSchema
import com.tsovedenski.csp.heuristics.pruning.Slice
/**
* Created by <NAME> on 14/10/2018.
*/
/**
* Represents a problem being solved.
*
* @param V the type of variable identifiers.
* @param D the type of domain values.
* @param assignment initial assignment.
* @param constraints constraints of the problem.
*/
data class Job <V, D> (val assignment: Assignment<V, D>, val constraints: List<Constraint<V, D>>) {
var counter: Long = 0
private set
/**
* Returns true if all [constraints] are satisfied for the current [assignment].
*/
fun isValid(): Boolean
= constraints.all { it(assignment) }
/**
* Returns true if no domain is [Empty] and all [constraints] that can be checked are satisfied.
*/
fun isPartiallyValid(): Boolean = assignment.all { it.value !is Empty } &&
constraints.asSequence().filter { it.canCheck(assignment) }.all { it(assignment) }
/**
* Returns true if all domains are [Selected].
*/
fun isComplete() = assignment.isComplete()
/**
* Assigns [value] to [key].
*/
fun assignVariable(key: V, value: Domain<D>)
= apply { assignment[key] = value }
// TODO: REMOVE THAT OR NOT THIS IS THE QUESTION
fun selectUnassignedVariable(): Map.Entry<V, Choice<D>>?
= assignment.filterIsInstance<V, Choice<D>>().entries.firstOrNull()
/**
* @return a [Slice] with current and future variables.
*/
fun sliceAtCurrent(ordering: VariableComparator<V, D>): Slice<V> {
val nextVariables = selectUnassignedVariables(ordering)
return Slice (
current = nextVariables.firstOrNull(),
next = nextVariables.drop(1).toMutableSet(),
previous = selectAssignedVariables().toMutableSet()
)
}
/**
* Prunes variables with the given pruning schema.
*/
fun prune(slice: Slice<V>, pruningSchema: PruneSchema<V, D>): Assignment<V, D> {
slice.current ?: return mutableMapOf()
val mergedConstraints = constraints
.filterIsInstance<AsBinaryConstraints<V, D>>()
.flatMap(AsBinaryConstraints<V, D>::asBinaryConstraints)
val sortedConstraints = pruningSchema(slice, mergedConstraints)
return assignment.consistentWith(sortedConstraints, pruningSchema.direction)
}
/**
* Merges assignments.
*/
fun mergeAssignments(prunedAssignment: Assignment<V, D>) = assignment.putAll(prunedAssignment)
fun step() = counter ++
private fun selectAssignedVariables() =
assignment.filterIsInstance<V, Selected<D>>().entries.map { it.key }
private fun selectUnassignedVariables(ordering: VariableComparator<V, D>) =
assignment.filterIsInstance<V, Choice<D>>().entries.asSequence().toSortedSet(Comparator { o1, o2 ->
ordering(o1.key to o1.value, o2.key to o2.value, constraints).asInt
}).map { it.key }
}
| 0 | Kotlin | 1 | 4 | 29d59ec7ff4f0893c0d1ec895118f961dd221c7f | 3,164 | csp-framework | MIT License |
src/2021/Day14_2.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
val inputs = File("input/2021/day14").readLines()
val polymerTemplate = inputs[0]
val pairInsertionMap = hashMapOf<String, String>()
for (index in 2 until inputs.size) {
val (first, second) = inputs[index].split("->")
pairInsertionMap[first.trim()] = second.trim()
}
val polymerMap = mutableMapOf<String, Long>()
for (index in 0 until polymerTemplate.length - 1) {
val pair = polymerTemplate.slice(index..index + 1)
polymerMap[pair] = polymerMap.getOrDefault(pair, 0) + 1
}
val steps = 40
repeat(steps) {
val newPolymerMap = mutableMapOf<String, Long>()
for (polymer in polymerMap.keys) {
val itemToInsert = pairInsertionMap[polymer]
val (first, second) = polymer.mapIndexed { index, c ->
if (index == 0) "$c$itemToInsert"
else "$itemToInsert$c"
}
newPolymerMap[first] = newPolymerMap.getOrDefault(first, 0) + polymerMap.getOrDefault(polymer,0)
newPolymerMap[second] = newPolymerMap.getOrDefault(second, 0) + polymerMap.getOrDefault(polymer,0)
}
polymerMap.clear()
polymerMap.putAll(newPolymerMap)
}
val mapOfCharAndCount = mutableMapOf<Char, Long>()
polymerMap.forEach { (key, value) -> mapOfCharAndCount[key[1]] = mapOfCharAndCount.getOrDefault(key[1], 0) + value }
mapOfCharAndCount[polymerMap.keys.first()[0]] = mapOfCharAndCount.getOrDefault(polymerMap.keys.first()[0], 0) + polymerMap.values.first()
val result = mapOfCharAndCount.values.maxOf { it } - mapOfCharAndCount.values.minOf { it }
println(result) | 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 1,538 | adventofcode | MIT License |
src/main/kotlin/advent/of/code/day14/Solution.kt | brunorene | 160,263,437 | false | null | package advent.of.code.day14
fun processUntil10(e1: Byte, e2: Byte, created: Int): String {
val recipes = mutableListOf(e1, e2)
var elf1 = 0
var elf2 = 1
while (recipes.size < created + 10) {
val combine = recipes[elf1] + recipes[elf2]
val recipe1 = if (combine > 9) 1.toByte() else null
val recipe2 = (combine % 10.toByte()).toByte()
if (recipe1 != null) recipes += recipe1
recipes += recipe2
elf1 = (elf1 + recipes[elf1].toInt() + 1) % recipes.size
elf2 = (elf2 + recipes[elf2].toInt() + 1) % recipes.size
}
return recipes.takeLast(10).joinToString("")
}
fun findSize(e1: Byte, e2: Byte, search: List<Byte>): Int {
val recipes = mutableListOf(e1, e2)
var elf1 = 0
var elf2 = 1
while (true) {
val combine = recipes[elf1] + recipes[elf2]
val recipe1 = if (combine > 9) 1.toByte() else null
val recipe2 = (combine % 10.toByte()).toByte()
if (recipe1 != null) {
recipes += recipe1
if (recipes.takeLast(search.size) == search)
return recipes.size - search.size
}
recipes += recipe2
if (recipes.takeLast(search.size) == search)
return recipes.size - search.size
elf1 = (elf1 + recipes[elf1].toInt() + 1) % recipes.size
elf2 = (elf2 + recipes[elf2].toInt() + 1) % recipes.size
}
}
fun part1() = processUntil10(3, 7, 920831)
fun part2() = findSize(3, 7, listOf(9, 2, 0, 8, 3, 1)) | 0 | Kotlin | 0 | 0 | 0cb6814b91038a1ab99c276a33bf248157a88939 | 1,501 | advent_of_code_2018 | The Unlicense |
src/questions/Sqrtx.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* Given a non-negative integer x, compute and return the square root of x.
* [Source](https://leetcode.com/problems/sqrtx/)
*/
@UseCommentAsDocumentation
private fun mySqrt(x: Int): Int {
if (x == 1) return x
val xLong = x.toLong() // squaring x can't fit in Int it goes beyond Integer.MAX_VALUE
var num: Long = xLong.shr(1)
var prev: Long = xLong
// Find the range of possible answers by dividing by 2
// Given 40: 20 (20x20) -> 10 (10x10=100) -> 5 (5x5=25)
// So answer must lie between 5 & 10
while (num * num > x) {
prev = num // prev is used to compensate for float to int conversions eg. sqrt(6)
num = num.shr(1)
}
// Check if the answer is 5
if (num * num == x.toLong()) {
return num.toInt()
}
// else traverse from 5 to 10
var low = num
val high = prev
// OR do binary search here
while (low <= high) {
val lowSq = low * low
if (lowSq == xLong) {
return low.toInt()
} else if (lowSq < x) {
low++
} else if (lowSq > x) {
return (low - 1).toInt()
}
}
return num.toInt()
}
fun main() {
mySqrt(2147395599) shouldBe 46339
mySqrt(6) shouldBe 2
mySqrt(100) shouldBe 10
mySqrt(50) shouldBe 7
mySqrt(40) shouldBe 6
mySqrt(25) shouldBe 5
mySqrt(1) shouldBe 1
mySqrt(64) shouldBe 8
mySqrt(8) shouldBe 2
mySqrt(4) shouldBe 2
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 1,529 | algorithms | MIT License |
src/main/kotlin/g0101_0200/s0139_word_break/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0101_0200.s0139_word_break
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table
// #Dynamic_Programming #Trie #Memoization #Algorithm_II_Day_15_Dynamic_Programming
// #Dynamic_Programming_I_Day_9 #Udemy_Dynamic_Programming #Big_O_Time_O(M+max*N)_Space_O(M+N+max)
// #2022_09_03_Time_197_ms_(87.17%)_Space_34.4_MB_(99.25%)
import java.util.HashSet
class Solution {
fun wordBreak(s: String, wordDict: List<String>): Boolean {
val set: MutableSet<String> = HashSet()
var max = 0
val flag = BooleanArray(s.length + 1)
for (st in wordDict) {
set.add(st)
if (max < st.length) {
max = st.length
}
}
for (i in 1..max) {
if (dfs(s, 0, i, max, set, flag)) {
return true
}
}
return false
}
private fun dfs(s: String, start: Int, end: Int, max: Int, set: Set<String>, flag: BooleanArray): Boolean {
if (!flag[end] && set.contains(s.substring(start, end))) {
flag[end] = true
if (end == s.length) {
return true
}
for (i in 1..max) {
if (end + i <= s.length && dfs(s, end, end + i, max, set, flag)) {
return true
}
}
}
return false
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,387 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/solutions/year2022/Day1.kt | neewrobert | 573,028,531 | false | {"Kotlin": 7605} | package solutions.year2022
import readInputText
fun main() {
fun sumCalories(input: String): List<Int> {
return input.split("\n\n").map { it.lines().sumOf { cal -> cal.toInt() } }
}
fun part1(input: String): Int {
return sumCalories(input).sortedDescending().take(1).sum()
}
fun part2(input: String): Int {
return sumCalories(input).sortedDescending().take(3).sum()
}
val testInput = readInputText("Day1_test", "2022")
check(part1(testInput) != 0)
check(part1(testInput) == 4)
check(part2(testInput) != 0)
check(part2(testInput) == 9)
val input = readInputText("Day1", "2022")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7ecf680845af9d22ef1b9038c05d72724e3914f1 | 710 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/zachjones/languageclassifier/entities/MultiLanguageDecision.kt | zachtjones | 184,465,284 | false | {"Kotlin": 73431} | package com.zachjones.languageclassifier.entities
import com.zachjones.languageclassifier.model.types.Language
/***
* Represents a language decision where there's multiple languages or multiple weighted
* parts in each decision.
*/
data class MultiLanguageDecision(
val weights: Map<Language, Double>
) : LanguageDecision() {
/**
* Normalizes the weights so that the sum is 1.0
*/
fun normalized(): MultiLanguageDecision {
val totalWeight = weights.values.sum()
return MultiLanguageDecision(weights = weights.mapValues { (_, value) ->
value / totalWeight
})
}
override fun confidences(): Map<Language, Double> = weights
companion object {
fun of(decisions: List<LanguageDecision>): MultiLanguageDecision {
val map = mutableMapOf<Language, Double>()
Language.values().forEach {
map[it] = 0.0
}
decisions.forEach { decision ->
decision.confidences().map { (language, confidence) ->
map[language] = map[language]!! + confidence
}
}
// remove all the "votes" for other, and let the majority language win
map[Language.OTHER] = 0.0
return MultiLanguageDecision(map).normalized()
}
}
}
| 0 | Kotlin | 0 | 1 | dfe8710fcf8daa1bc57ad90f7fa3c07a228b819f | 1,342 | Multi-Language-Classifier | Apache License 2.0 |
Others/kt_misc/SortInclude.kt | duangsuse-valid-projects | 163,751,200 | false | {"HTML": 426651, "JavaScript": 355495, "Kotlin": 240112, "TypeScript": 129004, "Python": 115314, "C": 88823, "C++": 54980, "Makefile": 39662, "TeX": 35614, "Assembly": 32921, "CSS": 15035, "Java": 8098, "Shell": 3838, "Haskell": 3542, "Visual Basic .NET": 3227, "Lua": 3220, "Ruby": 2185, "QMake": 508} | typealias CategoryMap<K, V> = Set<Map<K, V>>
typealias IncludePath = String
/** Descending level */
typealias Level = /*Comparable*/ Int
class DescendAllocator(private var max: Int = Int.MAX_VALUE) {
fun less() = max--
}
val kmap: CategoryMap<IncludePath, Level> = DescendAllocator().run { setOf(
mapOf(
"QObject" to less(),
"QScopedPointer" to less(),
"QByteArray" to less()
),
mapOf(
"QIODevice" to less(),
"QTimer" to less(),
"QAudioOutput" to less()
),
mapOf(
"QMainWindow" to less(),
"QLabel" to less(),
"QComboBox" to less(),
"QPushButton" to less(),
"QSlider" to less()
)
)
}
fun <T, K> Iterable<T>.histogram(key: (T) -> K): Map<K, List<T>> {
val hist: MutableMap<K, MutableList<T>> = mutableMapOf()
for (item in this) { hist.getOrPut(key(item), ::mutableListOf).add(item) }
return hist
}
object SortInclude {
@JvmStatic
fun main(vararg arg: String) {
val code = readText()
val includes = parse(code)
println(includes)
println(dump(organize(includes)))
}
fun dump(includes: Set<List<IncludePath>>): String {
return includes.map { it.joinToString("\n") }.joinToString("\n\n")
}
private fun parse(includeCode: String): List<IncludePath>
= includeCode.lines().map { includeRegex.matchEntire(it)
?.groupValues?.get(1) ?: error(it) }
private val includeRegex = Regex("#include <(.*)>")
fun organize(includes: List<IncludePath>): Set<List<IncludePath>> {
val parted = includes.histogram { kmap.find { m -> it in m } ?: homeless }
val sorted = parted.map { val (m, inz) = it;
inz.sortedByDescending(m::getValue) }
return sorted.toSet()
}
private val homeless: Map<IncludePath, Level> = emptyMap()
}
fun readText(): String {
val text = StringBuilder()
while (true) {
val line = readLine()
if (line == ".") break
else text.append(line).append("\n")
}
text.delete(text.lastIndex, text.lastIndex.inc()) //"\n"
return text.toString()
}
| 4 | HTML | 0 | 4 | e89301b326713bf949bcf9fbaa3992e83c2cba88 | 1,993 | Share | MIT License |
src/main/kotlin/com/colinodell/advent2022/Day11.kt | colinodell | 572,710,708 | false | {"Kotlin": 105421} | package com.colinodell.advent2022
class Day11(private val allMonkeys: List<Monkey>) {
private val lcm = allMonkeys.map { it.divisorTest }.fold(1L, Long::times)
fun solvePart1() = solve(20) { it.floorDiv(3) }
fun solvePart2() = solve(10000) { it.mod(lcm) }
private fun solve(times: Int, modifier: (Long) -> Long) =
repeat(times) {
allMonkeys.forEach { m -> m.inspectItems(allMonkeys, modifier) }
}
.let { allMonkeys }
.map { m -> m.itemsInspected }
.sortedDescending()
.take(2)
.let { it[0] * it[1] }
data class Monkey(
val items: MutableList<Long>,
private val operation: (Long) -> Long,
val divisorTest: Long,
private val nextMonkeyIfTrue: Int,
private val nextMonkeyIfFalse: Int
) {
var itemsInspected: Long = 0
fun inspectItems(otherMonkeys: List<Monkey>, modifier: (Long) -> Long) {
items
.map { modifier(operation(it)) }
.forEach { item ->
val nextMonkey = if (item % divisorTest == 0L) nextMonkeyIfTrue else nextMonkeyIfFalse
otherMonkeys[nextMonkey].items.add(item)
itemsInspected++
}
items.clear()
}
}
}
| 0 | Kotlin | 0 | 1 | 32da24a888ddb8e8da122fa3e3a08fc2d4829180 | 1,329 | advent-2022 | MIT License |
src/main/kotlin/leetcode/kotlin/binarysearch/1341. The K Weakest Rows in a Matrix.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.binarysearch
import java.util.PriorityQueue
private fun kWeakestRows(mat: Array<IntArray>, k: Int): IntArray {
fun findSoldiers(arr: IntArray): Int {
var l = 0
var r = arr.size - 1
while (l < r) {
var m = l + (r - l + 1) / 2
if (arr[m] >= 1) {
l = m
} else {
r = m - 1
}
}
return if (arr[l] == 1) l + 1 else 0
}
var soldiersPairs: MutableList<Pair<Int, Int>> = mutableListOf<Pair<Int, Int>>()
var i = 0
for (row in mat) {
var s = findSoldiers(row)
soldiersPairs.add(Pair(s, i++))
}
soldiersPairs.sortBy { it.first }
var weakRow = 0
var ans = mutableListOf<Int>()
for (pair in soldiersPairs) {
if (weakRow == k) break
ans.add(pair.second)
weakRow++
}
return ans.toIntArray()
}
private fun kWeakestRows2(mat: Array<IntArray>, k: Int): IntArray {
fun findSoldiers(arr: IntArray): Int {
var l = 0
var r = arr.size - 1
while (l < r) {
var m = l + (r - l + 1) / 2
if (arr[m] >= 1) {
l = m
} else {
r = m - 1
}
}
return if (arr[l] == 1) l + 1 else 0
}
var pq = PriorityQueue<Pair<Int, Int>>(k) { p1, p2 -> if (p1.first == p2.first) p2.second - p1.second else p2.first - p1.first }
var i = 0
for (row in mat) {
var s = findSoldiers(row)
pq.offer(Pair(s, i++))
if (pq.size > k) pq.poll()
}
var ans = IntArray(k)
i = k - 1
while (i >= 0) ans[i--] = pq.poll().second
return ans
}
private fun kWeakestRows3(mat: Array<IntArray>, k: Int): IntArray {
var pq = PriorityQueue<Pair<Int, Int>>(k) { p1, p2 -> if (p1.first == p2.first) p2.second - p1.second else p2.first - p1.first }
var r = 0
var c = 0
var s = 0
while (r < mat.size && c < mat[0].size) {
while (mat[r][c] == 1 && c + 1 < mat[0].size && mat[r][c + 1] == 1) c++
while (mat[r][c] == 0 && c - 1 >= 0) c--
s = if (mat[r][c] == 1) c + 1 else 0
pq.offer(Pair(s, r))
if (pq.size > k) pq.poll()
r++
}
var ans = IntArray(k)
var i = k - 1
while (i >= 0) ans[i--] = pq.poll().second
return ans
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 2,346 | kotlinmaster | Apache License 2.0 |
src/main/kotlin/day24.kt | Gitvert | 433,947,508 | false | {"Kotlin": 82286} | fun day24() {
val lines: List<String> = readFile("day24.txt")
day24part1(lines)
day24part2(lines)
}
var w = 0
var x = 0
var y = 0
var z = 0
fun day24part1(lines: List<String>) {
val blocks = getBlocks(lines)
var serialNumber = 99999999999999
var solved = false
var tries = 0L
while (!solved) {
val numberString = serialNumber.toString()
if (numberString.contains('0')) {
serialNumber--
continue
}
x = 0
y = 0
z = 0
blocks.forEachIndexed { index, it ->
parseBlock(it, Integer.valueOf(numberString[index].toString()))
}
if (z == 0) {
solved = true
} else {
serialNumber--
tries++
}
}
val answer = serialNumber
println("24a: $answer")
}
fun day24part2(lines: List<String>) {
val answer = "TBD"
println("24b: $answer")
}
fun parseBlock(lines: List<String>, numberToTry: Int) {
w = numberToTry
lines.filter { !it.startsWith('i') }.forEach {
parseLine(it)
}
}
fun parseLine(line: String) {
val parts = line.split(" ")
when (parts[0]) {
"add" -> add(parts[1], parts[2])
"mul" -> mul(parts[1], parts[2])
"div" -> div(parts[1], parts[2])
"mod" -> mod(parts[1], parts[2])
"eql" -> eql(parts[1], parts[2])
}
}
fun getBlocks(lines: List<String>): Array<MutableList<String>> {
val blocks = Array(14) { mutableListOf<String>() }
var index = -1
lines.forEach {
if (it.startsWith('i')) {
index++
}
blocks[index].add(it)
}
return blocks
}
fun add(a: String, b: String) {
when (a) {
"w" -> w += getActualNumber(b)
"x" -> x += getActualNumber(b)
"y" -> y += getActualNumber(b)
"z" -> z += getActualNumber(b)
}
}
fun mul(a: String, b: String) {
when (a) {
"w" -> w *= getActualNumber(b)
"x" -> x *= getActualNumber(b)
"y" -> y *= getActualNumber(b)
"z" -> z *= getActualNumber(b)
}
}
fun div(a: String, b: String) {
val divisor = getActualNumber(b)
if (divisor == 0) {
return
}
when (a) {
"w" -> w /= getActualNumber(b)
"x" -> x /= getActualNumber(b)
"y" -> y /= getActualNumber(b)
"z" -> z /= getActualNumber(b)
}
}
fun mod(a: String, b: String) {
val mod1 = when (a) {
"w" -> w
"x" -> x
"y" -> y
"z" -> z
else -> 0
}
val mod2 = getActualNumber(b)
if (mod1 < 0 || mod2 <= 0) {
return
}
when (a) {
"w" -> w %= mod2
"x" -> x %= mod2
"y" -> y %= mod2
"z" -> z %= mod2
}
}
fun eql(a: String, b: String) {
when (a) {
"x" -> x = if (x == getActualNumber(b)) { 1 } else { 0 }
"y" -> y = if (y == getActualNumber(b)) { 1 } else { 0 }
"z" -> z = if (z == getActualNumber(b)) { 1 } else { 0 }
}
}
fun getActualNumber(b: String): Int {
return when (b) {
"w" -> w
"x" -> x
"y" -> y
"z" -> z
else -> Integer.valueOf(b)
}
} | 0 | Kotlin | 0 | 0 | 02484bd3bcb921094bc83368843773f7912fe757 | 3,189 | advent_of_code_2021 | MIT License |
src/chapter3/section3/ex3.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter3.section3
import chapter3.section2.fullArray
/**
* 使用什么顺序插入键 S E A C H X M 能够得到一颗高度为1的2-3树?
*
* 解:先添加一个计算红黑树的高度的方法(只统计黑色结点),再根据练习3.2.9中的方法生成所有可能的排序,
* 统计所有让树高度为1的插入顺序(我实现的方法树高度从1开始,所以应该统计让height()方法返回2的树)
*/
fun ex3() {
val list = ArrayList<Array<Char>>()
fullArray("SEACHXM".toCharArray().toTypedArray(), 0, list)
var count = 0
list.forEach { array ->
val bst = RedBlackBST<Char, Int>()
array.forEach {
bst.put(it, 0)
}
if (bst.blackHeight() == 2) {
println(array.joinToString())
count++
}
}
println("list.size=${list.size} count=$count")
}
/**
* 红黑树的黑色结点高度,等同于2-3树的高度
*/
fun <K : Comparable<K>> RedBlackBST<K, *>.blackHeight(): Int {
var blackCount = 0
var node = root
while (node != null) {
if (!node.isRed()) {
blackCount++
}
//红黑树完美黑色平衡,所以所有路径上的黑色结点数量相等
node = node.left
}
return blackCount
}
/**
* 红黑树的实际高度
*/
fun <K : Comparable<K>> RedBlackBST<K, *>.height(): Int {
if (isEmpty()) return 0
return height(root!!)
}
fun <K : Comparable<K>, V : Any> height(node: RedBlackBST.Node<K, V>): Int {
var leftHeight = 0
var rightHeight = 0
if (node.left != null) {
leftHeight = height(node.left!!)
}
if (node.right != null) {
rightHeight = height(node.right!!)
}
return maxOf(leftHeight, rightHeight) + 1
}
fun main() {
ex3()
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,800 | Algorithms-4th-Edition-in-Kotlin | MIT License |
parcial-1-Juan/AsignarCupo.kt | lmisea | 640,071,913 | false | null | fun swapDual(A: Array<Int>, B: Array<Int>, i: Int, j: Int): Unit {
val aux: Int = A[i]
A[i] = A[j]
A[j] = aux
val temp: Int = B[i]
B[i] = B[j]
B[j] = temp
}
fun compararEstudiantes(A: Array<Int>, B: Array<Int>, i: Int, j: Int): Boolean{
return A[i] < A[j] || (A[i] == A[j] && B[i] <= B[j])
}
fun parent(i: Int): Int {
return i / 2
}
fun left(i: Int): Int {
return 2 * i
}
fun right(i: Int): Int {
return 2 * i + 1
}
fun maxHeapify(A: Array<Int>, B: Array<Int>, i: Int, heapSize: Int): Unit {
val l: Int = left(i)
val r: Int = right(i)
var largest: Int = i
if (l <= heapSize && compararEstudiantes(A, B, i, l)) {
largest = l
}
if (r <= heapSize && compararEstudiantes(A, B, largest, r)) {
largest = r
}
if (largest != i) {
swapDual(A, B, i, largest)
maxHeapify(A, B, largest, heapSize)
}
}
fun buildMaxHeap(A: Array<Int>, B: Array<Int>, heapSize: Int): Unit {
for (i in heapSize / 2 downTo 0) {
maxHeapify(A, B, i, heapSize)
}
}
fun heapSort(A: Array<Int>, B: Array<Int>): Unit {
val heapSize: Int = A.size - 1
buildMaxHeap(A, B, heapSize)
for (i in heapSize downTo 1) {
swapDual(A, B, 0, i)
maxHeapify(A, B, 0, i - 1)
}
}
fun main(args: Array<String>) {
val cupos = args[0].toInt()
if (cupos < 0){
throw Exception("El número de cupos debe ser positivo")
}
else if (cupos == 0){
println("NO HAY CUPOS")
return
}
if ((args.size)%2 != 1){
throw Exception("Falta un estudiante por NFC o carnet")
}
val numeroEstudiantes = (args.size - 1)/2
if (cupos >= numeroEstudiantes){
println("TODOS FUERON ADMITIDOS")
return
}
val carnets: Array<Int> = Array(numeroEstudiantes){0}
val NCFs: Array<Int> = Array(numeroEstudiantes){0}
for (i in 0 until numeroEstudiantes){
carnets[i] = args[i*2 + 1].toInt()
NCFs[i] = args[i*2 + 2].toInt()
}
heapSort(NCFs, carnets)
for (i in 0 until cupos){
println(carnets[i])
}
} | 0 | Kotlin | 1 | 0 | 948a9e52d0760a82a163d01c4361e07a021444cb | 2,102 | lab-algos-2 | MIT License |
kotlin/src/katas/kotlin/knapsack/Knapsack0.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.knapsack
import datsok.*
import org.junit.*
import java.util.*
import kotlin.collections.HashSet
class Knapsack0Tests {
@Test fun `single item`() {
checkPacking(
Bag(width = 1, height = 1),
items = setOf(Item(Cell(0, 0))),
output = "0"
)
checkPacking(
Bag(width = 2, height = 2),
items = setOf(Item(Cell(0, 0))),
output = """
|0.
|..
"""
)
}
@Test fun `single item which doesn't fit`() {
checkPacking(
Bag(width = 1, height = 1),
items = setOf(Item(Cell(0, 0), Cell(0, 1))),
output = "."
)
}
@Test fun `two items`() {
checkPacking(
Bag(width = 2, height = 2),
items = setOf(
Item(Cell(0, 0), Cell(0, 1), Cell(1, 0)),
Item(Cell(0, 0))
),
output = """
|00
|01
"""
)
checkPacking(
Bag(width = 2, height = 2),
items = setOf(
Item(Cell(0, 0)),
Item(Cell(0, 0), Cell(0, 1), Cell(1, 0))
),
output = """
|00
|01
"""
)
}
@Ignore
@Test fun `conflicting items`() {
checkPacking(
Bag(width = 2, height = 2),
items = setOf(
Item(Cell(0, 0), Cell(0, 1)),
Item(Cell(0, 0), Cell(0, 1), Cell(1, 0)),
Item(Cell(0, 0))
),
output = """
|00
|01
"""
)
}
private fun checkPacking(bag: Bag, items: Set<Item>, output: String) {
pack(bag, items).toPrettyString() shouldEqual output.trimMargin()
}
}
private data class Solution(
val bag: Bag,
val items: List<Item>,
val itemIndex: Int = 0,
val column: Int = 0,
val row: Int = 0
) {
fun isComplete() = bag.originalItems.containsAll(items)
fun skip(): Solution? =
when {
itemIndex < items.size - 1 -> copy(itemIndex = itemIndex + 1)
column < bag.width - 1 -> copy(column = column + 1, itemIndex = 0)
row < bag.height - 1 -> copy(row = row + 1, column = 0, itemIndex = 0)
else -> null
}
fun next(): Solution? {
val item = items[itemIndex]
val updatedBag = bag.add(item, at = Cell(column, row)) ?: return null
return copy(bag = updatedBag)
}
}
private fun pack(bag: Bag, items: Set<Item>): Bag {
return backtrack(Solution(bag, items.toList())).firstOrNull()?.bag ?: bag
}
private fun backtrack(solution: Solution): List<Solution> {
val result = ArrayList<Solution>()
val queue = LinkedList<Solution?>()
queue.addLast(solution)
while (queue.isNotEmpty()) {
val s = queue.removeFirst()
if (s == null) continue
else if (s.isComplete()) result.add(s)
else {
queue.add(s.next())
queue.add(s.skip())
}
}
return result
}
@Suppress("unused")
private fun backtrack_(solution: Solution?): List<Solution> {
if (solution == null) return emptyList()
if (solution.isComplete()) return listOf(solution)
return backtrack_(solution.next()) + backtrack_(solution.skip())
}
private data class Bag(
val width: Int,
val height: Int,
val items: Set<Item> = emptySet(),
val originalItems: Set<Item> = emptySet()
) {
fun add(item: Item, at: Cell): Bag? {
val movedItem = item.moveTo(cell = at)
if (items.any { it.cells.any { cell -> movedItem.cells.contains(cell) } }) return null
if (movedItem.cells.any { it.x !in 0.until(width) || it.y !in 0.until(height) }) return null
return copy(items = items + movedItem, originalItems = originalItems + item)
}
}
private fun Bag.toPrettyString(): String {
val charByItem = items.zip(items.indices).associate { it.copy(second = it.second % 10) }
return 0.until(width).joinToString("\n") { column ->
0.until(height).joinToString("") { row ->
val item = items.find { it.cells.contains(Cell(row, column)) }
if (item == null) "." else charByItem[item].toString()
}
}
}
private data class Item(val cells: Set<Cell>) {
constructor(vararg cells: Cell): this(cells.toSet())
fun moveTo(cell: Cell) =
copy(cells = cells.mapTo(HashSet()) {
Cell(it.x + cell.x, it.y + cell.y)
})
}
private data class Cell(val x: Int, val y: Int)
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 4,702 | katas | The Unlicense |
src/main/kotlin/com/manerfan/althorithm/sort/MergeSort.kt | manerfan | 122,578,493 | false | null | /*
* ManerFan(http://manerfan.com). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.manerfan.althorithm.sort
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.RecursiveTask
/**
* 归并排序
* @author manerfan
* @date 2018/2/23
*/
internal fun <T : Comparable<T>> Array<T>.merge(lo: Int, mid: Int, hi: Int): Array<T> {
val aux = this.clone()
var p = lo
var q = mid + 1
(lo..hi).forEach { i ->
when {
q > hi -> this[i] = aux[p++] // 右侧归并完
p > mid -> this[i] = aux[q++] // 左侧归并完
aux[p] < aux[q] -> this[i] = aux[p++] // 左侧小
else -> this[i] = aux[q++] // 右侧小
}
}
return this
}
internal fun <T : Comparable<T>> mergeSort(array: Array<T>, lo: Int, hi: Int): Array<T> {
return when {
hi - lo < 10 -> array.shellSort() // 小范围使用希尔排序
hi > lo -> {
val mid = lo + (hi - lo) / 2
mergeSort(array, lo, mid)
mergeSort(array, mid + 1, hi)
array.merge(lo, mid, hi)
array
}
else -> array
}
}
class MergeSortTask<T : Comparable<T>>(
private var array: Array<T>,
private val lo: Int, private val hi: Int
) : RecursiveTask<Array<T>>() {
override fun compute() = when {
hi - lo < 10 -> array.shellSort()
hi > lo -> {
val mid = lo + (hi - lo) / 2
val left = MergeSortTask(array, lo, mid)
val right = MergeSortTask(array, mid + 1, hi)
left.fork(); right.fork()
left.join(); right.join()
array.merge(lo, mid, hi)
}
else -> array
}
}
internal val mergePool = ForkJoinPool()
fun <T : Comparable<T>> Array<T>.mergeSort(parallel: Boolean = false) = when (parallel) {
true -> mergeSort(this, 0, this.size - 1)
else -> mergePool.submit(MergeSortTask(this, 0, this.size - 1)).get()
}!!
| 0 | Kotlin | 0 | 0 | 9210934e15acefd1b5bafc7f11b2078643ded239 | 2,515 | algorithm-with-kotlin | Apache License 2.0 |
contest1907/src/main/kotlin/C.kt | austin226 | 729,634,548 | false | {"Kotlin": 23837} | import kotlin.math.min
// https://codeforces.com/contest/1907/problem/C
private fun readInt(): Int = readln().toInt()
private fun solve(n: Int, s: String): Int {
var min = n
val checked = mutableSetOf(s)
val q = ArrayDeque<String>()
q.addFirst(s)
while (q.isNotEmpty()) {
val str = q.removeFirst()
for (i in 0..<str.length - 1) {
if (str[i] == str[i + 1]) {
continue
}
// Remove i and i+1
val newStrBuilder = StringBuilder()
for (j in str.indices) {
if (i != j && i + 1 != j) {
newStrBuilder.append(str[j])
}
}
val newStr = newStrBuilder.toString()
if (checked.contains(newStr)) {
continue
}
min = min(newStr.length, min)
if (min == 0) {
break
}
q.addLast(newStr)
checked.add(newStr)
println("Check $newStr")
}
}
return min
}
private fun testcase() {
val n = readInt()
val s = readln()
val min = solve(n, s)
println(min)
}
fun main() {
// val min = solve(20000, "abacd".repeat(20000 / 5))
val min = solve(2000, "abacd".repeat(2000 / 5))
println(min)
return
val t = readInt()
for (i in 0..<t) {
testcase()
}
} | 0 | Kotlin | 0 | 0 | 4377021827ffcf8e920343adf61a93c88c56d8aa | 1,399 | codeforces-kt | MIT License |
2k23/aoc2k23/src/main/kotlin/16.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d16
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
fun main() {
println("Part 1: ${part1(input.read("16.txt"))}")
println("Part 2: ${part2(input.read("16.txt"))}")
}
fun part1(input: List<String>): Int = Maze(input).simulate(Maze.Point(0, 0), Maze.Direction.East)
fun part2(input: List<String>): Int = Maze(input).findMostEnergized()
class Maze(input: List<String>) {
class Point(val x: Int, val y: Int) {
fun move(delta: Point): Point = Point(x + delta.x, y + delta.y)
override fun hashCode(): Int {
var result = x
result = 32 * result + y
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Point
if (x != other.x) return false
if (y != other.y) return false
return true
}
}
enum class Direction(val point: Point) {
North(Point(0, -1)),
South(Point(0, 1)),
East(Point(1, 0)),
West(Point(-1, 0)),
}
private val grid = input.map { it.toCharArray() }
private val xMax = input[0].length
private val yMax = input.size
private val moves = mapOf(
'/' to Direction.North to listOf(Direction.East),
'/' to Direction.West to listOf(Direction.South),
'/' to Direction.South to listOf(Direction.West),
'/' to Direction.East to listOf(Direction.North),
'|' to Direction.East to listOf(Direction.North, Direction.South),
'|' to Direction.West to listOf(Direction.North, Direction.South),
'-' to Direction.North to listOf(Direction.East, Direction.West),
'-' to Direction.South to listOf(Direction.East, Direction.West),
'\\' to Direction.North to listOf(Direction.West),
'\\' to Direction.West to listOf(Direction.North),
'\\' to Direction.South to listOf(Direction.East),
'\\' to Direction.East to listOf(Direction.South)
)
fun get(point: Point): Char = grid[point.y][point.x]
fun simulate(position: Point, direction: Direction): Int {
val visited = mutableSetOf(position to direction)
val toVisit = LinkedList<Pair<Point, Direction>>()
toVisit.add(position to direction)
while (toVisit.isNotEmpty()) {
val (pos, dir) = toVisit.pop()
(moves[get(pos) to dir] ?: listOf(dir)).forEach { nextDir ->
val nextPos = pos.move(nextDir.point)
val next = nextPos to nextDir
if (next !in visited && inBound(nextPos)) {
toVisit.add(nextPos to nextDir)
visited.add(next)
}
}
}
return visited.map { it.first }.toSet().size
}
fun findMostEnergized(): Int {
val executor: ExecutorService = Executors.newFixedThreadPool(5)
val tasks = listOf(
Callable { grid.first().indices.map { Point(it, 0) to Direction.South } },
Callable { grid.last().indices.map { Point(it, yMax - 1) to Direction.North } },
Callable { grid.indices.map { Point(0, it) to Direction.East } },
Callable { grid.indices.map { Point(xMax - 1, it) to Direction.West } }
)
val futures = executor.invokeAll(tasks)
val results = futures.map { it.get() }.flatten().map { simulate(it.first, it.second) }
executor.shutdown()
return results.maxOrNull() ?: 0
}
private fun inBound(point: Point): Boolean = (point.x in 0..<xMax) && (point.y in 0..<yMax)
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 3,746 | aoc | The Unlicense |
challenges/hacker-rank/kotlin/src/main/kotlin/com/raphaelnegrisoli/hackerrank/trees/HeightOfABinaryTree.kt | rbatista | 36,197,840 | false | {"Scala": 34929, "Kotlin": 23388} | /**
* https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem
*/
package com.raphaelnegrisoli.hackerrank.trees
import kotlin.math.max
data class Node(
val data: Int,
var left: Node? = null,
var right: Node? = null
) {
fun insert(data: Int) {
if (data < this.data) {
if (left == null ) left = Node(data)
else left?.insert(data)
} else if (data > this.data) {
if (right == null) right = Node(data)
else right?.insert(data)
}
}
fun height(current: Int = 0): Int {
val leftHeight = left?.height(current + 1) ?: current
val rightHeight = right?.height(current + 1) ?: current
return max(leftHeight, rightHeight)
}
}
fun main() {
readLine()
val data = readLine()
?.split(" ")
?.map { it.toInt() }
?: emptyList()
val root = Node(data.first())
data.drop(1).forEach { root.insert(it) }
println(root.height())
}
| 2 | Scala | 0 | 0 | f1267e5d9da0bd5f6538b9c88aca652d9eb2b96c | 1,025 | algorithms | MIT License |
collections/src/main/kotlin/com/lillicoder/algorithms/collections/Heap.kt | lillicoder | 754,271,079 | false | {"Kotlin": 16213} | package com.lillicoder.algorithms.collections
/**
* Implementation of a [Heap](https://en.wikipedia.org/wiki/Heap_(data_structure)).
*/
class Heap<T : Comparable<T>>(
collection: Collection<T>,
private val buffer: MutableList<T> = collection.toMutableList(),
) {
init {
heapify(buffer)
}
/**
* Sorts this heap in place in the natural order of elements.
*/
fun sort() {
for (end in buffer.size - 1 downTo 1) {
buffer.swap(end, 0)
siftDown(buffer, 0, end)
}
}
/**
* Gets a heap of all elements stable sorted according to their natural sort order.
* @return Sorted heap.
*/
fun sorted(): Heap<T> {
if (buffer.size < 1) return toHeap()
return toHeap().apply { sort() }
}
/**
* Gets a list containing all elements of this heap.
* @return List of all elements.
*/
fun toList() = buffer.toList()
/**
* Gets a heap containing all elements of this heap
* @return Heap of all elements.
*/
private fun toHeap() = Heap(buffer.toList())
/**
* Sorts elements of the given buffer in heap order.
* @param buffer Buffer to sort.
*/
private fun heapify(buffer: MutableList<T>) {
if (buffer.size < 1) return
for (start in parent(buffer.size - 1) downTo 0) {
siftDown(buffer, start, buffer.size)
}
}
/**
* Gets the index of the left child node for the given index.
* @param index Index to get the left child of.
* @return Left child index.
*/
private fun leftChild(index: Int) = (2 * index) + 1
/**
* Gets the index of the right child node for the given index.
* @param index Index to get the right child of.
* @return Right child index.
*/
private fun rightChild(index: Int) = (2 * index) + 2
/**
* Gets the index of the parent node for the given index.
* @param index Index to get parent of.
* @return Parent node index.
*/
private fun parent(index: Int) = index - 1 ushr 1
/**
* Moves the element at the given start position to its proper heap position.
* @param buffer Heap.
* @param start Starting node index.
* @param end Ending node index.
*/
private fun siftDown(
buffer: MutableList<T>,
start: Int,
end: Int,
) {
var root = start
while (leftChild(root) < end) {
var child = leftChild(root)
if (child + 1 < end && buffer[child] < buffer[child + 1]) {
child++
}
if (buffer[root] < buffer[child]) {
buffer.swap(root, child)
root = child
} else {
return
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8f96def65d07f646facaa3007cee6c8c99e71320 | 2,912 | algorithms-kotlin | Apache License 2.0 |
atcoder/arc154/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package atcoder.arc154
import kotlin.random.Random
fun main() {
val n = readInt()
val random = Random(566)
val shuffle = (0 until n).shuffled(random)
val memo = mutableMapOf<Triple<Int, Int, Int>, Boolean>()
// p[i] + p[j] > p[k]
fun ask(i: Int, j: Int, k: Int): Boolean {
if (i > j) return ask(j, i, k)
return memo.getOrPut(Triple(i, j, k)) {
println("? ${shuffle[i] + 1} ${shuffle[j] + 1} ${shuffle[k] + 1}")
readLn()[0] == 'Y'
}
}
var one = 0
// 2p[i] <= p[one]
for (i in 1 until n) if (!ask(i, i, one)) one = i
val a = IntArray(n) { it }
a[0] = one; a[one] = 0
val mergeSortTemp = IntArray(n)
fun sort(from: Int, to: Int) {
val partSize = to - from
if (partSize <= 1) return
val mid = (from + to) / 2
sort(from, mid); sort(mid, to)
var i = from; var j = mid
for (k in 0 until partSize) mergeSortTemp[k] = a[
if (i < mid && (j == to || !ask(a[i], one, a[j]))) i++ else j++
]
System.arraycopy(mergeSortTemp, 0, a, from, partSize)
}
sort(1, n)
val ans = IntArray(n)
for (i in a.indices) {
ans[shuffle[a[i]]] = i + 1
}
println("! ${ans.joinToString(" ")}")
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,195 | competitions | The Unlicense |
src/year2021/day07/Day07.kt | fadi426 | 433,496,346 | false | {"Kotlin": 44622} | package year2021.day01.day07
import util.assertTrue
import util.read2021DayInput
import kotlin.math.absoluteValue
fun main() {
fun task01(input: List<Int>): Int {
var cheapestOutcome = Int.MAX_VALUE
for (i in 0..input.maxOrNull()!!) {
var maxValue = 0
for (j in input.indices) maxValue += (input[j] - i).absoluteValue
if (maxValue < cheapestOutcome) cheapestOutcome = maxValue.absoluteValue
}
return cheapestOutcome
}
fun task02(input: List<Int>): Int {
var cheapestOutcome = Int.MAX_VALUE
for (i in 0..input.maxOrNull()!!) {
var maxValue = 0
for (j in input.indices) maxValue += (input[j] - i).absoluteValue * ((input[j] - i).absoluteValue + 1) / 2
if (maxValue < cheapestOutcome) cheapestOutcome = maxValue.absoluteValue
}
return cheapestOutcome
}
val input = read2021DayInput("Day07").first().split(",").map { it.toInt() }
assertTrue(task01(input) == 356992)
assertTrue(task02(input) == 101268110)
}
| 0 | Kotlin | 0 | 0 | acf8b6db03edd5ff72ee8cbde0372113824833b6 | 1,072 | advent-of-code-kotlin-template | Apache License 2.0 |
src/main/kotlin/suicideburn.kt | rasmusbergpalm | 278,299,208 | false | null | import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Compute the time to wait before applying constant throttle*engineForce force such that altitude will be zero when velocity is zero.
* Takes into account changing mass and gravitational pull.
*
* Note: not used at the moment
*/
fun suicideBurn(
altitude: Double,
velocity: Double,
engineForce: Double,
startMass: Double,
fuelConsumptionRate: Double,
gravitationalParameter: Double,
bodyRadius: Double,
desiredAltitude: Double,
throttle: Double
): Pair<Double, List<State>> {
fun trajectory(waitTime: Double): List<State> {
val waitTrajectory = simulateTrajectory(
altitude,
velocity,
0.0,
startMass,
0.0,
gravitationalParameter,
bodyRadius,
{ it.time < waitTime }
)
val waitEnd = waitTrajectory.last()
val burnTrajectory = simulateTrajectory(
waitEnd.altitude,
waitEnd.velocity,
engineForce * throttle,
startMass,
fuelConsumptionRate * throttle,
gravitationalParameter,
bodyRadius,
{ it.velocity < 0.0 }
)
return waitTrajectory + burnTrajectory.map { it.copy(time = it.time + waitEnd.time) }
}
val error = fun(waitTime: Double): Double {
return trajectory(waitTime).last().altitude - desiredAltitude
}
val (init, _) = suicideBurnConstantAcceleration(
-gravitationalParameter / (bodyRadius + altitude).pow(2),
engineForce * throttle / startMass,
velocity,
altitude
)
val waitTime = newton(error, finiteDifference(error, 1.0 / 25), 1.0, 200, init)
return Pair(waitTime, trajectory(waitTime))
}
/**
* Compute the constant acceleration such that altitude will be zero when velocity is zero. Assumes everything is constant except altitude and velocity.
*/
fun constantAcceleration(
gravity: Double,
velocity: Double,
altitude: Double
): Double {
assert(gravity < 0) { "gravity must be negative" }
return (velocity.pow(2)) / (2 * altitude) - gravity
}
/**
* Compute the time to wait before accelerating with a constant acceleration such that altitude will be zero when velocity is zero. Assumes everything is constant except altitude and velocity.
*/
fun suicideBurnConstantAcceleration(
gravity: Double,
acceleration: Double,
velocity: Double,
altitude: Double
): Pair<Double, Double> {
assert(gravity < 0) { "gravity must be negative" }
val totalAcceleration = acceleration + gravity
val qa = 1.0 / 2.0 * gravity * (1 - gravity / totalAcceleration)
val qb = velocity * (1 - gravity / totalAcceleration)
val qc = altitude - velocity.pow(2) / (2 * totalAcceleration)
val twp = (-qb + sqrt(qb.pow(2) - 4 * qa * qc)) / (2 * qa)
val twm = (-qb - sqrt(qb.pow(2) - 4 * qa * qc)) / (2 * qa)
val tw = max(twp, twm)
val vb = velocity + gravity * tw
val tb = -vb / totalAcceleration
return Pair(tw, tb)
}
| 3 | Kotlin | 0 | 0 | 19e718714a29e81e452b43181f6fe71e531cbd92 | 3,119 | ksp | MIT License |
src/test/kotlin/dev/shtanko/algorithms/leetcode/PermutationInStringTest.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 java.util.stream.Stream
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
abstract class PermutationInStringStrategyTest<out T : StringPermutationStrategy>(private val strategy: T) {
@ParameterizedTest
@ArgumentsSource(InputArgumentsProvider::class)
fun `simple test`(str1: String, str2: String, expected: Boolean) {
val actual = strategy.invoke(str1, str2)
assertEquals(expected, actual)
}
private class InputArgumentsProvider : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of(
Arguments.of(
"ab",
"eidbaooo",
true,
),
Arguments.of(
"ab",
"eidboaoo",
false,
),
Arguments.of(
"",
"",
true,
),
)
}
}
class PermutationBruteForceTest :
PermutationInStringStrategyTest<PermutationBruteForce>(PermutationBruteForce())
class PermutationSortingTest : PermutationInStringStrategyTest<PermutationSorting>(PermutationSorting())
class PermutationHashmapTest : PermutationInStringStrategyTest<PermutationHashmap>(PermutationHashmap())
class PermutationArrayTest : PermutationInStringStrategyTest<PermutationArray>(PermutationArray())
class PermutationSlidingWindowTest :
PermutationInStringStrategyTest<PermutationSlidingWindow>(PermutationSlidingWindow())
class PermutationOptimizedSlidingWindowTest :
PermutationInStringStrategyTest<PermutationOptimizedSlidingWindow>(PermutationOptimizedSlidingWindow())
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,578 | kotlab | Apache License 2.0 |
src/Day06.kt | SebastianHelzer | 573,026,636 | false | {"Kotlin": 27111} |
fun main() {
fun getSecretIndex(size: Int, input: String) : Int {
return input.windowed(size, 1, false).indexOfFirst { it.toSet().size == size } + size
}
fun part1(input: String): Int = getSecretIndex(4, input)
fun part2(input: String): Int = getSecretIndex(14, input)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
val (test1, test2, test3, test4, test5) = testInput
checkEquals(7, part1(test1))
checkEquals(5, part1(test2))
checkEquals(6, part1(test3))
checkEquals(10, part1(test4))
checkEquals(11, part1(test5))
checkEquals(19, part2(test1))
checkEquals(23, part2(test2))
checkEquals(23, part2(test3))
checkEquals(29, part2(test4))
checkEquals(26, part2(test5))
val input = readInput("Day06")
println(part1(input.first()))
println(part2(input.first()))
}
| 0 | Kotlin | 0 | 0 | e48757626eb2fb5286fa1c59960acd4582432700 | 914 | advent-of-code-2022 | Apache License 2.0 |
Explore/Learn/Introduction to Data Structure/Arrays 101/Squares of A Sorted Array/SquaresSorted.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution1 {
fun sortedSquares(A: IntArray): IntArray {
val B = IntArray(A.size)
for (id in B.indices) {
B[id] = A[id] * A[id]
}
return B.sortedArray()
}
}
class Solution2 {
fun sortedSquares(A: IntArray): IntArray {
val N = A.size
var B = IntArray(N)
var j = 0
while (j < N && A[j] < 0) {
j++
}
var i = j-1
var k = 0
while (i >= 0 && j < N) {
if (A[i] * A[i] < A[j] * A[j]) {
B[k++] = A[i] * A[i]
i--
} else {
B[k++] = A[j] * A[j]
j++
}
}
while (i >= 0) {
B[k++] = A[i] * A[i]
i--
}
while (j < N) {
B[k++] = A[j] * A[j]
j++
}
return B
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 916 | leet-code | MIT License |
kotlin/MutableCategoricalMap.kt | danftang | 193,937,824 | false | null | import java.util.*
import kotlin.NoSuchElementException
import kotlin.collections.HashMap
import kotlin.random.Random
open class MutableCategoricalMap<T> : AbstractMutableMap<T, Double> {
private var sumTreeRoot: SumTreeNode<T>? = null
private val leafNodes: MutableMap<T, LeafNode<T>>
enum class MapType {
HASHMAP,
TREEMAP
}
override val entries: MutableSet<MutableMap.MutableEntry<T, Double>>
get() = MutableEntrySet()
override val size: Int
get() = leafNodes.size
constructor(underlyingMapType: MapType = MapType.HASHMAP) {
leafNodes = when(underlyingMapType) {
MapType.HASHMAP -> HashMap()
MapType.TREEMAP -> TreeMap()
}
}
constructor(initialHashCapacity: Int) {
leafNodes = HashMap(initialHashCapacity)
}
// Sets this to be the Huffman tree of the given categories with the given probabilities
// This creates an optimally efficient tree but runs in O(n log(n)) time as the entries
// need to be sorted
fun createHuffmanTree(categories: Iterable<T>, probabilities: Iterable<Double>, initialCapacity: Int = -1) {
val heapComparator = Comparator<SumTreeNode<T>> { i, j -> i.value.compareTo(j.value) }
if (initialCapacity > 0)
createTree(categories, probabilities, PriorityQueue(initialCapacity, heapComparator))
else
createTree(categories, probabilities, PriorityQueue(calcCapacity(categories, probabilities), heapComparator))
HashMap(leafNodes)
}
// Sets this to be a binary tree of the given categories with the given probabilities
// This creates a tree with minimal total depth and runs in O(n) time
fun createBinaryTree(categories: Iterable<T>, probabilities: Iterable<Double>, initialCapacity: Int = -1) {
if (initialCapacity > 0)
createTree(categories, probabilities, ArrayDeque(initialCapacity))
else
createTree(categories, probabilities, ArrayDeque(calcCapacity(categories, probabilities)))
}
override operator fun get(key: T): Double {
return leafNodes.get(key)?.value ?: 0.0
}
override fun put(item: T, probability: Double): Double? {
if (probability == 0.0) return remove(item)
val existingNode = leafNodes[item]
if (existingNode == null) {
val newNode = createLeaf(null, item, probability)
sumTreeRoot = sumTreeRoot?.add(newNode) ?: newNode
leafNodes[item] = newNode
return null
}
val newRoot = existingNode.remove()
val oldProb = existingNode.value
existingNode.value = probability
sumTreeRoot = newRoot?.add(existingNode) ?: existingNode
return oldProb
}
operator fun set(item: T, probability: Double) = put(item, probability)
override fun remove(item: T): Double? {
val node = leafNodes.remove(item) ?: return null
sumTreeRoot = node.remove()
return node.value
}
fun sample(sum: Double): T? {
return sumTreeRoot?.find(sum)?.key
}
fun sample(): T {
val root = sumTreeRoot ?: throw(NoSuchElementException())
return sample(Random.nextDouble() * root.value)!!
}
fun sum() = sumTreeRoot?.value ?: 0.0
override fun clear() {
leafNodes.clear()
sumTreeRoot = null
}
fun calcHuffmanLength(): Double {
return (sumTreeRoot?.calcHuffmanLength() ?: 0.0) / (sumTreeRoot?.value ?: 1.0)
}
private fun <Q : Queue<SumTreeNode<T>>> createTree(categories: Iterable<T>, probabilities: Iterable<Double>, heap: Q) {
val category = categories.iterator()
val probability = probabilities.iterator()
clear()
while (category.hasNext() && probability.hasNext()) {
val prob = probability.next()
val cat = category.next()
if (prob > 0.0) {
val newNode = createLeaf(null, cat, prob)
heap.add(newNode)
leafNodes[newNode.key] = newNode
}
}
while (heap.size > 1) {
val first = heap.poll()
val second = heap.poll()
val parent = createNode(null, first, second)
heap.add(parent)
}
sumTreeRoot = heap.poll()
}
private fun calcCapacity(categories: Iterable<T>, probabilities: Iterable<Double>): Int {
return when {
categories is Collection<T> -> categories.size
probabilities is Collection<Double> -> probabilities.size
else -> 1024
}
}
open fun createLeaf(parent : InternalNode<T>?, category : T, probability : Double) : LeafNode<T> =
LeafNode(parent, category, probability)
open fun createNode(parent : InternalNode<T>?, child1: SumTreeNode<T>, child2: SumTreeNode<T>) =
InternalNode(parent, child1, child2)
open class InternalNode<T> : SumTreeNode<T> {
var leftChild: SumTreeNode<T>
var rightChild: SumTreeNode<T>
constructor(parent: InternalNode<T>?, child1: SumTreeNode<T>, child2: SumTreeNode<T>) : super(parent, child1.value + child2.value) {
if (child1.value > child2.value) {
this.leftChild = child1
this.rightChild = child2
} else {
this.leftChild = child2
this.rightChild = child1
}
child1.parent = this
child2.parent = this
}
constructor(parent: InternalNode<T>?, lChild: SumTreeNode<T>, rChild: SumTreeNode<T>, sum : Double) : super(parent, sum) {
leftChild = lChild
rightChild = rChild
}
override fun find(sum: Double): LeafNode<T> {
if (sum <= leftChild.value) return leftChild.find(sum)
return rightChild.find(sum - leftChild.value)
}
override fun updateSum() {
value = leftChild.value + rightChild.value
if (leftChild.value < rightChild.value) {
val tmp = rightChild
rightChild = leftChild
leftChild = tmp
}
}
override fun add(newNode: LeafNode<T>): InternalNode<T> {
if (value <= newNode.value) { // add right here
return newNode.growNewParentAndInsertAbove(this)
}
rightChild.add(newNode)
return this
}
fun swapChild(oldChild: SumTreeNode<T>, newChild: SumTreeNode<T>) {
if (oldChild == leftChild) {
leftChild = newChild
return
} else if (oldChild == rightChild) {
rightChild = newChild
return
}
throw(IllegalStateException("trying to swap a child that isn't a child"))
}
fun otherChild(firstChild: SumTreeNode<T>): SumTreeNode<T> {
return when (firstChild) {
leftChild -> rightChild
rightChild -> leftChild
else -> throw(NoSuchElementException())
}
}
// returns the root node
fun removeSelfAnd(child : SumTreeNode<T>) : SumTreeNode<T> {
val keepChild = otherChild(child)
parent?.swapChild(this, keepChild)
keepChild.parent = parent
return keepChild.parent?.updateSumsToRoot() ?: keepChild
}
override fun calcHuffmanLength() = value + leftChild.calcHuffmanLength() + rightChild.calcHuffmanLength()
}
open class LeafNode<T> : SumTreeNode<T>, Map.Entry<T, Double> {
override val key: T
constructor(parent: InternalNode<T>?, item: T, probability: Double) : super(parent, probability) {
this.key = item
}
override fun find(sum: Double): LeafNode<T> {
return this
}
override fun add(newNode: LeafNode<T>) = newNode.growNewParentAndInsertAbove(this)
fun growNewParentAndInsertAbove(insertPoint: SumTreeNode<T>): InternalNode<T> {
val oldParent = insertPoint.parent
val newParent = createInternalNode(insertPoint.parent, this, insertPoint)
oldParent?.swapChild(insertPoint, newParent)
newParent.parent?.updateSumsToRoot()
return newParent
}
open fun createInternalNode(parent : InternalNode<T>?, child1: SumTreeNode<T>, child2: SumTreeNode<T>) =
InternalNode(parent, child1, child2)
// removes this and returns the root node
fun remove(): SumTreeNode<T>? {
val p = parent ?: return null
return p.removeSelfAnd(this)
}
}
abstract class SumTreeNode<T>(var parent: InternalNode<T>?, var value: Double) {
// returns the root node
fun updateSumsToRoot(): SumTreeNode<T> {
updateSum()
return parent?.updateSumsToRoot() ?: this
}
abstract fun add(newNode: LeafNode<T>): SumTreeNode<T>
abstract fun find(sum: Double): LeafNode<T>
open fun updateSum() {}
open fun calcHuffmanLength() : Double = 0.0
}
inner class MutableEntrySet : AbstractMutableSet<MutableMap.MutableEntry<T, Double>>() {
override fun add(element: MutableMap.MutableEntry<T, Double>): Boolean {
this@MutableCategoricalMap[element.key] = element.value
return true
}
override val size: Int
get() = [email protected]
override fun iterator(): MutableIterator<MutableMap.MutableEntry<T, Double>> =
MutableEntryIterator([email protected]())
}
inner class MutableEntry(val leafNodeEntry: MutableMap.MutableEntry<T, LeafNode<T>>) :
MutableMap.MutableEntry<T, Double> {
override val key: T
get() = leafNodeEntry.key
override val value: Double
get() = leafNodeEntry.value.value
override fun setValue(newValue: Double): Double {
val existingNode = leafNodeEntry.value
val oldVal = existingNode.value
val newRoot = existingNode.remove()
existingNode.value = newValue
sumTreeRoot = newRoot?.add(existingNode) ?: existingNode
return oldVal
}
override fun hashCode(): Int {
return key.hashCode() xor value.hashCode()
}
}
inner class MutableEntryIterator(val leafNodesIterator: MutableIterator<MutableMap.MutableEntry<T, LeafNode<T>>>) :
MutableIterator<MutableMap.MutableEntry<T, Double>> {
var lastReturned: MutableMap.MutableEntry<T, LeafNode<T>>? = null
override fun hasNext() = leafNodesIterator.hasNext()
override fun next(): MutableMap.MutableEntry<T, Double> {
val next = leafNodesIterator.next()
lastReturned = next
return MutableEntry(next)
}
override fun remove() {
leafNodesIterator.remove()
lastReturned?.value?.remove()
}
}
override fun toString(): String {
var s = "( "
for (item in entries) {
s += "${item.key}->${item.value} "
}
s += ")"
return s
}
}
fun <T> mutableCategoricalOf(vararg categories: Pair<T, Double>): MutableCategoricalMap<T> {
val d = MutableCategoricalMap<T>(categories.size)
d.createBinaryTree(
categories.asSequence().map { it.first }.asIterable(),
categories.asSequence().map { it.second }.asIterable(),
categories.size
)
return d
}
| 0 | C++ | 1 | 2 | ac84d5b255d9f09ea5de21bb08f96072af2e32e7 | 11,706 | MutableCategoricalDistribution | MIT License |
00-code(源代码)/src/com/hi/dhl/algorithms/offer/_13/kotlin/Solution.kt | hi-dhl | 256,677,224 | false | null | package com.hi.dhl.algorithms.offer._13.kotlin
import java.util.*
/**
* <pre>
* author: dhl
* desc :
* </pre>
*/
class Solution {
fun movingCount(m: Int, n: Int, k: Int): Int {
val robot = Array(m, { IntArray(n) })
return dfs(robot, 0, 0, m, n, k)
}
fun dfs(robot: Array<IntArray>, x: Int, y: Int, m: Int, n: Int, k: Int): Int {
if (x > m - 1 || y > n - 1 || robot[x][y] == -1 || count(x) + count(y) > k) {
return 0
}
robot[x][y] = -1
return dfs(robot, x + 1, y, m, n, k) + dfs(robot, x, y + 1, m, n, k) + 1
}
fun bfs(m: Int, n: Int, k: Int): Int {
val robot = Array(m, { IntArray(n) })
val queue = LinkedList<IntArray>()
var res = 0
queue.offer(intArrayOf(0, 0))
while (!queue.isEmpty()) {
val (x, y) = queue.poll()
if (x > m - 1 || y > n - 1 || robot[x][y] == -1 || count(x) + count(y) > k) {
continue;
}
robot[x][y] = -1
res += 1
queue.offer(intArrayOf(x + 1, y))
queue.offer(intArrayOf(x, y + 1))
}
return res
}
fun count(x: Int): Int {
var sx = x
var count = 0
while (sx > 0) {
count += sx % 10
sx = sx / 10
}
return count
}
}
fun main() {
val solution = Solution()
println(solution.bfs(38, 15, 9))
} | 0 | Kotlin | 48 | 396 | b5e34ac9d1da60adcd9fad61da4ec82e2cefc044 | 1,446 | Leetcode-Solutions-with-Java-And-Kotlin | Apache License 2.0 |
aqua/app/src/main/java/com/garmin/android/aquamarine/Basic.kt | catalintira | 244,655,458 | false | null | package com.garmin.android.aquamarine
// Exercise 1
open class Account(var balance: Float) {
open fun withdraw(sumToWithdraw: Float) {
balance -= sumToWithdraw
}
fun deposit(sumToDeposit: Float) {
balance += sumToDeposit
}
}
class SavingAccount(balance: Float) : Account(balance) {
override fun withdraw(sumToWithdraw: Float) {
if (sumToWithdraw > balance) {
throw IllegalArgumentException()
}
super.withdraw(sumToWithdraw)
}
}
// Exercise 2
// N
// W E
// S
fun getCardinalDirections(angle: Int): String {
return when (angle) {
in 45..134 -> "E"
in 135..224 -> "S"
in 225..314 -> "W"
else -> "N"
}
}
// Exercise 3
val vocals = listOf('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
fun getVocalsCount(input: String): Int = input.count { vocals.contains(it) }
// Exercise 4 A
class RectangularShape(var x: Int, var y: Int, var with: Int, var height: Int, var color: Int) {
fun measure() {}
fun render() {}
}
fun validateShape(shape: RectangularShape): Boolean {
return when {
shape.x < 0 || shape.y < 0 -> {
print("invalid position"); false
}
shape.with > 1024 || shape.height > 1024 -> {
print("shape too big"); false
}
shape.color < 0 || shape.color > 0xFFFFFF -> {
print("invalid color"); false
}
else -> true
}
}
// Exercise 4 B
fun initShape(shape: RectangularShape?) {
shape?.apply {
x = 10
y = 20
with = 100
height = 200
color = 0xFF0066
} ?: throw IllegalArgumentException()
}
// Exercise 4 C
fun drawShape(shape: RectangularShape?) {
shape?.also {
validateShape(it)
it.measure()
it.render()
}
}
// Exercise 5
val data = listOf(4, 6, 34, 9, 2, 4, 7)
fun solveExercise5() {
// A
print(data)
// B
print(data.reversed())
// C
print(data.distinct())
// D
print(data.subList(0, 3))
// E
val min: Int? = data.min()
if (min != null && min >= 0) print(data)
// F
print(data.map { it * it })
// G
print(data.filter { it % 2 == 0 })
// H
data.forEachIndexed { i, v -> if (v % 2 == 0) print(i) }
// I
fun isPrime(number: Int): Boolean {
when (number) {
in 0..1 -> return false
2 -> return true
else -> {
if(number % 2 == 0) return false
for (i in 3 until number step 2) {
if(number % i == 0)
return false
}
}
}
return true
}
print( data.filter { isPrime(it) } )
// J
data.last { isPrime(it) }
}
// Exercise 6
data class Student(val name: String, val address: String, val grade: Int)
val students = listOf(
Student("John", "Boston", 6), Student("Jacob", "Baltimore", 2),
Student("Edward", "New York", 7), Student("William", "Providence", 6),
Student("Alice", "Philadelphia", 4), Student("Robert", "Boston", 7),
Student("Richard", "Boston", 10), Student("Steven", "New York", 3)
)
fun solveExercise6() {
// A
print(students)
// B
print(students.sortedBy { it.name })
// C
students.map { it.name }
.sortedBy { it }
.forEach { print(it) }
// D
students.sortedWith(compareBy({ it.grade }, { it.name }))
.forEach { print(it) }
// E
print(students.groupBy { it.address })
}
fun vineri6() {
val str = "abcdef"
str[0]
str.subSequence(0, 2)
for(l in str) print("$l ")
fun isEven(input : Int): Boolean {
return input % 2 == 0
}
isEven(300)
fun filterC(text : String) = text.filter { it !in "aeiouAEIOU" }
filterC(str)
fun String.consonants() = filter { it !in "aeiouAEIOU" }
str.consonants()
}
| 2 | Kotlin | 0 | 0 | a55bb2a74344249ded557ef760609caaaf89bebd | 3,984 | aquamarine | Apache License 2.0 |
kotlin/backtracking/Coloring.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package backtracking
import java.util.Random
class Coloring {
var minColors = 0
var bestColoring: IntArray
fun minColors(graph: Array<BooleanArray>): Int {
val n = graph.size
bestColoring = IntArray(n)
val id = IntArray(n + 1)
val deg = IntArray(n + 1)
for (i in 0..n) id[i] = i
bestColoring = IntArray(n)
var res = 1
var from = 0
var to = 1
while (to <= n) {
var best = to
for (i in to until n) {
if (graph[id[to - 1]][id[i]]) ++deg[id[i]]
if (deg[id[best]] < deg[id[i]]) best = i
}
val t = id[to]
id[to] = id[best]
id[best] = t
if (deg[id[to]] == 0) {
minColors = n + 1
dfs(graph, id, IntArray(n), from, to, from, 0)
from = to
res = Math.max(res, minColors)
}
to++
}
return res
}
fun dfs(
graph: Array<BooleanArray>,
id: IntArray,
coloring: IntArray,
from: Int,
to: Int,
cur: Int,
usedColors: Int
) {
if (usedColors >= minColors) return
if (cur == to) {
for (i in from until to) bestColoring[id[i]] = coloring[i]
minColors = usedColors
return
}
val used = BooleanArray(usedColors + 1)
for (i in 0 until cur) if (graph[id[cur]][id[i]]) used[coloring[i]] = true
for (i in 0..usedColors) {
if (!used[i]) {
val tmp = coloring[cur]
coloring[cur] = i
dfs(graph, id, coloring, from, to, cur + 1, Math.max(usedColors, i + 1))
coloring[cur] = tmp
}
}
}
companion object {
// random test
fun main(args: Array<String?>?) {
val rnd = Random(1)
for (step in 0..999) {
val n: Int = rnd.nextInt(10) + 1
val g = Array(n) { BooleanArray(n) }
for (i in 0 until n) for (j in 0 until i) if (rnd.nextBoolean()) {
g[i][j] = true
g[j][i] = true
}
val res1 = Coloring().minColors(g)
val res2 = colorSlow(g)
if (res1 != res2) throw RuntimeException()
}
}
fun colorSlow(g: Array<BooleanArray>): Int {
val n = g.size
var allowedColors = 1
while (true) {
var colors: Long = 1
for (i in 0 until n) colors *= allowedColors.toLong()
m1@ for (c in 0 until colors) {
val col = IntArray(n)
var cur: Long = c
for (i in 0 until n) {
col[i] = (cur % allowedColors).toInt()
cur /= allowedColors.toLong()
}
for (i in 0 until n) for (j in 0 until i) if (g[i][j] && col[i] == col[j]) continue@m1
return allowedColors
}
allowedColors++
}
}
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 3,205 | codelibrary | The Unlicense |
model/src/main/java/com/kentvu/csproblems/Playground.kt | KentVu | 210,312,595 | false | null | package com.kentvu.csproblems
import kotlin.reflect.full.hasAnnotation
import kotlin.reflect.full.memberFunctions
class Playground {
@Target(AnnotationTarget.FUNCTION)
annotation class AlgoFunction
@OptIn(ExperimentalStdlibApi::class)
val algos: List<String> get() {
return Playground::class.memberFunctions.filter {
it.hasAnnotation<AlgoFunction>()
}.map { it.name }.toList()
}
// https://www.hackerrank.com/challenges/insertion-sort/problem
@AlgoFunction
fun insertionSortDec(arr: IntArray): Int {
val max = arr.max()!!
val bit = BIT(max)
bit.update(arr[0], 1)
var swaps = 0
for (i in 1 until arr.size) {
// Get count of elements smaller than arr[i]
swaps += bit.sum(arr[i])
bit.update(arr[i], 1)
}
return swaps
}
@AlgoFunction
fun insertionSortAsc(arr: IntArray): Long {
val max = arr.max()!!
val bit = BIT(max)
bit.update(arr[arr.lastIndex], 1)
var swaps = 0L
for (i in arr.lastIndex - 1 downTo 0) {
swaps += bit.sum(arr[i] - 1) // Get count of elements smaller than arr[i]
bit.update(arr[i], 1)
}
return swaps
}
fun invoke(algo: String, vararg args: Any?): Any? {
return Playground::class.memberFunctions.first { it.name == algo }.run {
call(this@Playground, *args)
}
}
}
class BIT(max: Int) {
private val bit: Array<Int>
init {
//val max = arr.max()!!
// build
bit = Array(max + 1) { i -> 0 }
// for (v in arr) {
// bit[v]++
// }
}
fun update(v: Int, inc: Int) {
var index = v
// Traverse all ancestors and add 'val'
while (index <= bit.size - 1) {
// Add 'val' to current node of BI Tree
bit[index] += inc
// Update index to that of parent in update View
index += index and -index
}
}
fun sum(v: Int): Int {
var sum = 0 // Initialize result
// Traverse ancestors of BITree[index]
var index = v
while (index > 0) {
// Add current element of BITree to sum
sum += bit[index]
// Move index to parent node in getSum View
index -= index and -index
}
return sum
}
fun mark(v: Int) {
if (bit[v] == 0) {
update(v, 1)
}
}
}
| 0 | Kotlin | 0 | 0 | 52cb15d5a5d70336617f56e3961fdaff7b94ca84 | 2,508 | CSProblems | Apache License 2.0 |
src/main/kotlin/days/aoc2023/Day16.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2023
import days.Day
import util.CharArray2d
import util.Point2d
import kotlin.math.max
class Day16 : Day(2023, 16) {
override fun partOne(): Any {
return calculatePartOne(inputList)
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
fun calculatePartOne(input: List<String>): Int {
val tiles = CharArray2d(input)
return calculateEnergizedTilesFromBeam(tiles, Point2d(0, 0) to Point2d.Direction.East)
}
fun calculatePartTwo(input: List<String>): Int {
val tiles = CharArray2d(input)
var max = 0
for (x in tiles.columnIndices) {
max = max(max, calculateEnergizedTilesFromBeam(tiles, startingBeam = Point2d(x, 0) to Point2d.Direction.South))
max = max(max, calculateEnergizedTilesFromBeam(tiles, startingBeam = Point2d(x, tiles.maxRowIndex) to Point2d.Direction.North))
}
for (y in tiles.rowIndices) {
max = max(max, calculateEnergizedTilesFromBeam(tiles, startingBeam = Point2d(0, y) to Point2d.Direction.East))
max = max(max, calculateEnergizedTilesFromBeam(tiles, startingBeam = Point2d(tiles.maxColumnIndex, y) to Point2d.Direction.West))
}
return max
}
private fun calculateEnergizedTilesFromBeam(tiles: CharArray2d, startingBeam: Pair<Point2d, Point2d.Direction>): Int {
val energizedTiles = mutableSetOf<Point2d>()
val activeBeams = mutableListOf(startingBeam)
val seenBeams = mutableSetOf<Pair<Point2d, Point2d.Direction>>()
fun nextTileLocation(current: Point2d, direction: Point2d.Direction): Point2d? {
return if ((current + direction.delta).isWithin(tiles)) {
current + direction.delta
} else {
null
}
}
fun splitBeam(beam: Pair<Point2d, Point2d.Direction>, newDirections: Set<Point2d.Direction>) {
if (beam.second in newDirections) {
nextTileLocation(beam.first, beam.second)?.let {
activeBeams.add(it to beam.second)
}
} else {
newDirections.forEach { direction ->
nextTileLocation(beam.first, direction)?.let {
activeBeams.add(it to direction)
}
}
}
}
val rightSlant = mapOf(
Point2d.Direction.North to Point2d.Direction.East,
Point2d.Direction.East to Point2d.Direction.North,
Point2d.Direction.South to Point2d.Direction.West,
Point2d.Direction.West to Point2d.Direction.South
)
val leftSlant = mapOf(
Point2d.Direction.North to Point2d.Direction.West,
Point2d.Direction.West to Point2d.Direction.North,
Point2d.Direction.South to Point2d.Direction.East,
Point2d.Direction.East to Point2d.Direction.South
)
fun turnBeam(beam: Pair<Point2d, Point2d.Direction>, map: Map<Point2d.Direction,Point2d.Direction>) {
map[beam.second]?.let { newDirection ->
nextTileLocation(beam.first, newDirection)?.let {
activeBeams.add(it to newDirection)
}
}
}
while (activeBeams.isNotEmpty()) {
val beam = activeBeams.removeFirst()
if (seenBeams.contains(beam)) {
continue
} else {
seenBeams.add(beam)
}
energizedTiles.add(beam.first)
when (tiles[beam.first]) {
'.' -> nextTileLocation(beam.first, beam.second)?.let {
activeBeams.add(it to beam.second)
}
'/' -> turnBeam(beam, rightSlant)
'\\' -> turnBeam(beam, leftSlant)
'|' -> splitBeam(beam, setOf(Point2d.Direction.North, Point2d.Direction.South))
'-' -> splitBeam(beam, setOf(Point2d.Direction.East, Point2d.Direction.West))
}
}
return energizedTiles.count()
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 4,123 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
Chapter_7/src/main/kotlin/exercises/7.15 Enhanced GradeBook.kt | Cursos-Livros | 667,537,024 | false | {"Kotlin": 104564} | package exercises
fun main() {
println("Enter with the number of students:")
val inputNumberStudents = readlnOrNull()?.toInt() ?: 0
println("Enter with the number of exams:")
val inputNumberExams = readlnOrNull()?.toInt() ?: 0
// Create a GradeBook object
val myGradeBook = GradeBook("CS101 Introduction to Java Programming", inputNumberStudents, inputNumberExams)
// Set grades
for (student in 1..inputNumberStudents) {
for (exam in 1..inputNumberExams) {
println("Enter grade for student $student on exam $exam:")
val inputGrade = readlnOrNull()?.toInt() ?: 0
myGradeBook.setGrade(student, exam, inputGrade)
}
}
// Print a welcome message
println("Welcome to the grade book for")
println(myGradeBook.courseName)
println()
// Process grades
myGradeBook.processGrade()
}
class GradeBook(val initialCourseName: String, numberStudents: Int, numberExams: Int) {
var courseName: String = initialCourseName
private set
private val grades: MutableList<MutableList<Int>> = MutableList(numberStudents) { MutableList(numberExams) { -1 } }
// Set a grade of particular students exams
fun setGrade(student: Int, exam: Int, grade: Int) {
if (student in 1..grades.size && exam in 1..grades[0].size) {
grades[student - 1][exam - 1] = grade
} else {
println("Invalid student or exam index.")
}
}
// Process Data
fun processGrade() {
outputGrades()
println("Lowest grade in the grade book is ${getMinimum()} Highest grade in the grade book is ${getMaximum()}")
outputBarChart()
}
fun outputGrades() {
println("The grades are:%n%n")
print(" ") // align column heads
// create a column heading for each of the tests
for (test in grades[0].indices) {
print("Test ${test + 1} ")
}
println("Average") // student average column heading
// create rows/columns of text representing array grades
for (student in grades.indices) {
print("Student ${student + 1}")
for (test in grades[student]) { // output student's grades
print("%8d".format(test))
}
// call method getAverage to calculate student's average grade;
// pass row of grades as the argument to getAverage
val average = getAverage(grades[student])
print("%9.2f%n".format(average))
}
}
// Find minimum grade
fun getMinimum(): Int {
var lowGrade = grades[0][0]
for (row in grades.indices) {
for (element in grades[row].indices) {
if (lowGrade > grades[row][element]) {
lowGrade = grades[row][element]
}
}
}
return lowGrade
}
// Find maximum grade
fun getMaximum(): Int {
var maximumGrade = grades[0][0]
for (row in grades.indices) {
for (element in grades[row].indices) {
if (maximumGrade < grades[row][element]) {
maximumGrade = grades[row][element]
}
}
}
return maximumGrade
}
// Array to store the grade for a particular grade
fun getAverage(setOfGrades: MutableList<Int>): Double {
var total = 0
// sum grades for one student
for (grade in setOfGrades) {
total += grade
}
// return average of grades
return total.toDouble() / setOfGrades.size
}
// Output bar chart
fun outputBarChart() {
println("Overall grade distribution:")
val frequency = IntArray(11)
for (studentGrades in grades) {
for (grade in studentGrades) {
++frequency[grade / 10]
}
}
for (count in frequency.indices) {
// output bar label ("00-09: ", ..., "90-99: ", "100: ")
if (count == 10) {
println("%5d: ".format(100))
} else {
print("%02d-%02d: ".format(count * 10, count * 10 + 9))
}
// print bar of asterisks
repeat(frequency[count]) {
print("*")
}
println()
}
}
} | 0 | Kotlin | 0 | 0 | f2e005135a62b15360c2a26fb6bc2cbad18812dd | 4,373 | Kotlin-Como-Programar | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year23/Day20.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year23
import com.grappenmaker.aoc.*
fun PuzzleSet.day20() = puzzle(day = 20) {
data class Module(val op: Char, val name: String, val to: List<String>)
val m = inputLines.associate { l ->
val (a, b) = l.split(" -> ")
val n = if (a == "broadcaster") a else a.drop(1)
n to Module(a.first(), n, b.split(", "))
}
val allModules = m.values.toList()
val parents = buildMap<String, List<String>> {
allModules.forEach { m -> m.to.forEach { put(it, (get(it) ?: emptyList()) + m.name) } }
}
val (mFlop, mConf) = m.toList().partition { (_, b) -> b.op == '%' || b.name == "broadcaster" }
val flops = mFlop.associate { it.first to false }.toMutableMap()
val conj = mConf.associate { (a) -> a to parents.getValue(a).associateWith { false }.toMutableMap() }.toMutableMap()
var lo = 0L
var hi = 0L
var n = 0L
val lastSeen = hashMapOf<String, Long>()
val seenBefore = hashMapOf<String, Int>()
val search = parents.getValue(parents.getValue("rx").single()).toSet()
val cycles = mutableListOf<Long>()
data class Pulse(val s: String, val high: Boolean, val from: String = "")
a@ while (true) {
n++
val queue = queueOf(Pulse("broadcaster", false))
while (queue.isNotEmpty()) {
val (s, high, from) = queue.removeFirst()
if (s == "rx" && !high) break@a
if (high) hi++ else lo++
if (!high) {
if (s in search && s in lastSeen && seenBefore.getValue(s) > 1) cycles += n - lastSeen.getValue(s)
seenBefore[s] = (seenBefore[s] ?: 0) + 1
lastSeen[s] = n
}
if (search.size == cycles.size) {
partTwo = cycles.lcm().s()
break@a
}
val curr = m[s] ?: continue
if (s == "broadcaster") {
curr.to.forEach { queue.addLast(Pulse(it, high, s)) }
continue
}
when (curr.op) {
'%' -> if (!high) {
val cv = flops.getValue(s)
flops[s] = !cv
curr.to.forEach { queue.addLast(Pulse(it, !cv, s)) }
}
'&' -> {
conj.getValue(s)[from] = high
val cv = !conj.getValue(s).all { it.value }
curr.to.forEach { queue.addLast(Pulse(it, cv, s)) }
}
else -> error("Invalid ${curr.op}")
}
}
if (n == 1000L) partOne = (lo * hi).s()
}
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,618 | advent-of-code | The Unlicense |
2021/02/main.kt | chylex | 433,239,393 | false | null | import java.io.File
fun main() {
val lines = File("input.txt").readLines()
val directions = lines.map { line -> line.split(' ', limit = 2).let { it[0] to it[1].toInt() } }
println("Part 1:")
part1(directions)
println()
println("Part 2:")
part2(directions)
}
private fun part1(directions: List<Pair<String, Int>>) {
var position = 0
var depth = 0
for ((direction, distance) in directions) {
when (direction) {
"forward" -> position += distance
"up" -> depth -= distance
"down" -> depth += distance
}
}
println("Position: $position")
println("Depth: $depth")
println("Multiplied: ${position * depth}")
}
private fun part2(directions: List<Pair<String, Int>>) {
var position = 0
var depth = 0
var aim = 0
for ((direction, distance) in directions) {
when (direction) {
"forward" -> {
position += distance
depth += aim * distance
}
"up" -> aim -= distance
"down" -> aim += distance
}
}
println("Position: $position")
println("Depth: $depth")
println("Multiplied: ${position * depth}")
}
| 0 | Rust | 0 | 0 | 04e2c35138f59bee0a3edcb7acb31f66e8aa350f | 1,074 | Advent-of-Code | The Unlicense |
src/day1/solution.kt | 0pilatos0 | 572,642,222 | false | {"Kotlin": 4586} | fun main(){
fun part1(input:List<String>): Int{
var mostCalories = 0
var currentCalories = 0
for (calorie in input){
try{
currentCalories += calorie.toInt()
if (currentCalories > mostCalories){
mostCalories = currentCalories
}
} catch (e: NumberFormatException){
currentCalories = 0
}
}
return mostCalories
}
fun part2(input: List<String>) : Int{
var mostCalories = arrayOf(0, 0, 0)
var currentCalories = 0
for (calorie in input + ""){
try{
currentCalories += calorie.toInt()
} catch (e: NumberFormatException){
var lowest = mostCalories.indexOf(mostCalories.min())
if (currentCalories > mostCalories[lowest]) {
mostCalories[lowest] = currentCalories
}
currentCalories = 0
}
}
var sum = 0
for (i in mostCalories){
sum += i
}
return sum
}
// val input = readInput("day1/input") //SUBMITTING
val input = readInput("day1/testInput") //TESTING
println("Part 1 result " + part1(input))
println("Part 2 result " + part2(input))
} | 0 | Kotlin | 0 | 0 | 424653e1ec515bacc9423d4b1f1e221ac53b7659 | 1,339 | adventofcodekotlin | Apache License 2.0 |
src/commonMain/kotlin/edu/unito/probability/bayes/AssignmentProposition.kt | lamba92 | 150,039,952 | false | null | package edu.unito.probability.bayes
import edu.unito.probability.RandomVariable
class AssignmentProposition(forVariable: RandomVariable, val value: Any):
AbstractTermProposition(forVariable) {
override fun holds(possibleWorld: Map<RandomVariable, Any>) = value == possibleWorld[termVariable]
}
abstract class AbstractTermProposition(val termVariable: RandomVariable):
AbstractProposition(), TermProposition{
override fun getTermVariable() = termVariable
}
abstract class AbstractProposition: Proposition {
private val scope = LinkedHashSet<RandomVariable>()
private val unboundScope = LinkedHashSet<RandomVariable>()
override fun getScope() = scope
override fun getUnboundScope() = unboundScope
protected fun addScope(rv: RandomVariable) = scope.add(rv)
protected fun addScope(vars: Collection<RandomVariable>) = scope.addAll(vars)
protected fun addUnboundScope(rv: RandomVariable) = unboundScope.add(rv)
protected fun addUnboundScope(vars: Collection<RandomVariable>) = unboundScope.addAll(vars)
}
interface Proposition {
/**
*
* @return the Set of RandomVariables in the World (sample space) that this
* Proposition is applicable to.
*/
fun getScope(): Set<RandomVariable>
/**
*
* @return the Set of RandomVariables from this propositions scope that are
* not constrained to any particular set of values (e.g. bound =
* P(Total = 11), while unbound = P(Total)). If a variable is
* unbound it implies the distributions associated with the variable
* is being sought.
*/
fun getUnboundScope(): Set<RandomVariable>
/**
* Determine whether or not the proposition holds in a particular possible
* world.
*
* @param possibleWorld
* A possible world is defined to be an assignment of values to
* all of the random variables under consideration.
* @return true if the proposition holds in the given possible world, false
* otherwise.
*/
fun holds(possibleWorld: Map<RandomVariable, Any>): Boolean
}
interface TermProposition {
fun getTermVariable(): RandomVariable
}
| 0 | Kotlin | 0 | 0 | acbae0d12d9501ca531b8e619b49ce38793a7697 | 2,151 | bayes-net-project-multiplatform | MIT License |
Lab 7/src/main/kotlin/DoubleArrayUnilities.kt | knu-3-tochanenko | 273,870,242 | false | null | operator fun DoubleArray.plus(array: DoubleArray): DoubleArray {
val size = Math.max(this.size, array.size)
val result = DoubleArray(size) { 0.0 }
for (i in 1..this.size)
result[size - i] += this[this.size - i]
for (i in 1..array.size)
result[size - i] += array[array.size - i]
return result
}
operator fun DoubleArray.times(value: Double): DoubleArray {
val result = DoubleArray(this.size) { 0.0 }
for (i in this.indices)
result[i] = this[i] * value
return result
}
operator fun DoubleArray.times(array: DoubleArray): DoubleArray {
val result = DoubleArray(this.size + array.size - 1) { 0.0 }
for (i in this.indices)
for (j in array.indices)
result[i + j] += this[i] * array[j]
return result
}
infix fun ClosedRange<Double>.step(step: Double): Iterable<Double> {
require(start.isFinite())
require(endInclusive.isFinite())
require(step > 0.0) { "Step must be positive, was: $step." }
val sequence = generateSequence(start) { previous ->
if (previous == Double.POSITIVE_INFINITY) return@generateSequence null
val next = previous + step
if (next > endInclusive) null else next
}
return sequence.asIterable()
}
fun fillArray(range: Iterable<Double>, f: (Double) -> Double): MutableList<Dot> {
val array = mutableListOf<Dot>()
for (i in range) {
array.add(Dot(i, f(i)))
}
return array
}
fun fillArrayPolynomial(range: Iterable<Double>, coef: DoubleArray): MutableList<Double> {
val result = mutableListOf<Double>()
for (i in range) {
result.add(getPolynomialRoot(i, coef))
}
return result
}
fun getPolynomialRoot(x: Double, coef: DoubleArray): Double {
var pow = coef.size - 1
var result = 0.0
for (i in coef.indices) {
result += power(x, pow) * coef[i]
pow--
}
return result
}
fun power(x: Double, pow: Int): Double {
var res = 1.0
for (i in 0 until pow)
res *= x
return res
} | 0 | Kotlin | 0 | 0 | 84818b225f1aa4812cc5515d6fdda31d9d373e86 | 2,022 | NumericalMethods | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/JumpGame5.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 java.util.LinkedList
fun interface JumpGame5Strategy {
operator fun invoke(arr: IntArray): Int
fun checkNeighbors(visited: MutableSet<Int>, node: Int, n: Int, nex: MutableList<Int>) {
if (node + 1 < n && !visited.contains(node + 1)) {
val value = node + 1
visited.add(value)
nex.add(value)
}
if (node - 1 >= 0 && !visited.contains(node - 1)) {
val value = node - 1
visited.add(value)
nex.add(value)
}
}
}
class JP5BreadthFirstSearch : JumpGame5Strategy {
override operator fun invoke(arr: IntArray): Int {
val n: Int = arr.size
if (n <= 1) {
return 0
}
val graph: MutableMap<Int, MutableList<Int>> = HashMap()
for (i in 0 until n) {
graph.computeIfAbsent(arr[i]) {
LinkedList()
}.add(i)
}
var curs: MutableList<Int> = LinkedList() // store current layer
curs.add(0)
val visited: MutableSet<Int> = HashSet()
var step = 0
// when current layer exists
while (curs.isNotEmpty()) {
val nex: MutableList<Int> = LinkedList()
// iterate the layer
for (node in curs) {
// check if reached end
if (node == n - 1) {
return step
}
for (child in graph[arr[node]]!!) {
checkSameValue(visited, child, nex)
}
// clear the list to prevent redundant search
graph[arr[node]]?.clear()
checkNeighbors(visited, node, n, nex)
}
curs = nex
step++
}
return -1
}
private fun checkSameValue(visited: MutableSet<Int>, child: Int, nex: MutableList<Int>) {
if (!visited.contains(child)) {
visited.add(child)
nex.add(child)
}
}
}
class JP5BidirectionalBFS : JumpGame5Strategy {
private var curs: MutableList<Int> = LinkedList() // store layers from start
private val graph: MutableMap<Int, MutableList<Int>> = HashMap()
private val visited: MutableSet<Int> = HashSet()
var other: MutableList<Int> = LinkedList() // store layers from end
init {
curs.add(0)
visited.add(0)
}
override operator fun invoke(arr: IntArray): Int {
val n: Int = arr.size
if (n <= 1) {
return 0
}
for (i in 0 until n) {
graph.computeIfAbsent(arr[i]) {
LinkedList()
}.add(i)
}
visited.add(n - 1)
var step = 0
other.add(n - 1)
// when current layer exists
while (curs.isNotEmpty()) {
searchFewerNodes()
val nex: MutableList<Int> = LinkedList()
// iterate the layer
for (node in curs) {
// check same value
for (child in graph[arr[node]]!!) {
if (other.contains(child)) {
return step + 1
}
checkNotVisited(child, nex)
}
// clear the list to prevent redundant search
graph[arr[node]]?.clear()
if (isOtherContains(other, node)) {
return step + 1
}
checkNeighbors(visited, node, n, nex)
}
curs = nex
step++
}
return -1
}
// search from the side with fewer nodes
private fun searchFewerNodes() {
if (curs.size > other.size) {
val tmp = curs
curs = other
other = tmp
}
}
private fun checkNotVisited(child: Int, nex: MutableList<Int>) {
if (!visited.contains(child)) {
visited.add(child)
nex.add(child)
}
}
private fun isOtherContains(other: List<Int>, node: Int): Boolean {
return other.contains(node + 1) || other.contains(node - 1)
}
}
@Suppress("ComplexMethod")
class JP5BidirectionalBFS2 : JumpGame5Strategy {
private var head: MutableSet<Int> = HashSet()
private var tail: MutableSet<Int> = HashSet()
private val idxMap: MutableMap<Int, MutableList<Int>> = HashMap()
init {
head.add(0)
}
override operator fun invoke(arr: IntArray): Int {
val totalNums = arr.size
if (totalNums <= 1) return 0
for (idx in totalNums - 1 downTo 0) {
idxMap.getOrPut(arr[idx]) { arrayListOf() }.add(idx)
}
val visited = getVisitedArray(totalNums)
tail.add(totalNums - 1)
if (totalNums > 1) {
visited[totalNums - 1] = true
}
var steps = 0
while (head.isNotEmpty() && tail.isNotEmpty()) {
swapTwoSets()
val next = HashSet<Int>()
for (idx in head) {
val hiNext = idx + 1
if (tail.contains(hiNext)) return steps + 1
if (hiNext in 0 until totalNums && !visited[hiNext]) {
next.add(hiNext)
}
val loNext = idx - 1
if (tail.contains(loNext)) return steps + 1
if (loNext in 0 until totalNums && !visited[loNext]) {
next.add(loNext)
}
idxMap[arr[idx]]?.let {
for (equalValueNext in it) {
if (tail.contains(equalValueNext)) return steps + 1
if (visited[equalValueNext]) continue
next.add(equalValueNext)
visited[equalValueNext] = true
}
// to save time
// there is no need to check visited/seen at all later on
it.clear()
}
}
head = next
++steps
}
return -1
}
private fun swapTwoSets() {
if (head.size > tail.size) {
head = tail.also { tail = head }
}
}
private fun getVisitedArray(totalNums: Int): BooleanArray {
val visited = BooleanArray(totalNums) { false }
if (totalNums != 0) {
visited[0] = true
}
return visited
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 7,048 | kotlab | Apache License 2.0 |
app/src/main/kotlin/kotlinadventofcode/2023/2023-15.kt | pragmaticpandy | 356,481,847 | false | {"Kotlin": 1003522, "Shell": 219} | // Originally generated by the template in CodeDAO
package kotlinadventofcode.`2023`
import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.*
import com.github.h0tk3y.betterParse.lexer.*
import kotlinadventofcode.Day
class `2023-15` : Day {
override fun runPartOneNoUI(input: String): String {
return input.toInitSequence().sumOf { it.hash }.toString()
}
override fun runPartTwoNoUI(input: String): String {
val boxes: Map<Int, Box> = (0..255).associateWith { Box(it) }
input.toSteps().forEach {
val box = boxes[it.hash]!!
when (it) {
is SetStep -> box.set(it.label, it.focalLength)
is RemoveStep -> box.remove(it.label)
}
}
return boxes.values.sumOf { it.power }.toString()
}
companion object {
sealed class Step(val label: String) {
val hash = label.hash
}
class SetStep(label: String, val focalLength: Int) : Step(label)
class RemoveStep(label: String) : Step(label)
class Box(private val id: Int) {
private val lenses: MutableList<LabeledLens> = mutableListOf()
private data class LabeledLens(val label: String, val focalLength: Int)
val power by lazy {
lenses.withIndex().sumOf { ((1 + id) * (it.index + 1) * it.value.focalLength) }
}
fun set(label: String, focalLength: Int) {
val lens = LabeledLens(label, focalLength)
lenses.withIndex().find { it.value.label == label }?.let {
lenses.set(it.index, lens)
} ?: lenses.add(lens)
}
fun remove(label: String) {
lenses.removeIf { it.label == label }
}
}
val String.hash: Int
get() {
var result = 0
for (c in this) {
result += c.code
result *= 17
result %= 256
}
return result
}
fun String.toSteps(): List<Step> {
val grammar = object : Grammar<List<Step>>() {
// tokens
val commaLit by literalToken(",")
val dashLit by literalToken("-")
val equalsLit by literalToken("=")
val positiveIntRegex by regexToken("\\d+")
val lowerCaseRegex by regexToken("[a-z]+")
// parsers
val label = lowerCaseRegex use { text }
val focalLength by positiveIntRegex use { text.toInt() }
val setStep by (label and skip(equalsLit) and focalLength) map { SetStep(it.t1, it.t2) }
val removeStep by (label and skip(dashLit)) map { RemoveStep(it) }
val step by setStep or removeStep
override val rootParser by separatedTerms(step, commaLit)
}
return grammar.parseToEnd(this)
}
fun String.toInitSequence(): List<String> {
val grammar = object : Grammar<List<String>>() {
// tokens
val commaLit by literalToken(",")
val notCommaRegex by regexToken("[^,]+")
// parsers
val step by notCommaRegex use { text }
override val rootParser by separatedTerms(step, commaLit)
}
return grammar.parseToEnd(this)
}
}
override val defaultInput = """fzl-,tcjp=8,vkjr=9,xs-,jktcpk=3,gzp-,kfsxsd-,zxkv=7,fxz-,pj=7,mhbdch=7,xlss-,smk-,ppz-,kqggd-,dqh=7,gmv=6,tjjfm=2,gbv=5,gn-,ld=7,jdr-,phq=3,rd-,qz=3,sh-,gzsb=2,glrt=7,vjkrjg-,gjqmpc=7,qnx=7,mf=1,tnrm-,lppg-,gnvx=1,rv-,vnt-,bst-,gkb-,tl=1,bggff-,lm=8,mqq=7,hr-,gkb-,fspkn=2,tjjfm-,shshb=3,qfczq-,zk-,zcsc-,lnrjh=2,fz-,bkb-,rg-,bcfzn=6,xsbb=5,sm=3,rqs-,rvlv=9,pvh=9,rl-,zrb=9,lftk=1,cdn-,zp=8,hc-,mf-,hp-,zk-,dbj=5,tm=9,zx-,gmp=4,gcq-,mxq-,lvh-,lkhb-,vn=9,gzsb=6,xlss=9,drkhc=8,rgqg=1,hkr-,fxz=7,xsm-,fvmf=4,hsm=7,dlrss=9,rv-,kj-,ndtc-,zjf-,zj=9,kv=5,sxvv-,hj-,mltm-,qggz-,mntr-,td=5,lppg=1,xqb-,brt-,nm-,vlp=7,zcjnv=6,chh-,dd=2,fh-,hxfkx=6,hj=6,rzk=7,skpq-,rxb=1,fn=1,nc=1,vqq-,ndq-,xtgd=6,qlgv-,dl-,xln-,rqs=5,vpmmf=1,llvv-,hzp=6,dnbql=3,rqz=5,nfhb=7,vdb-,gmp-,hskv-,xs-,vk-,xll-,ng=2,xb-,mjjph-,tss-,lsd-,qsj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kotlin": 61384} | fun main() {
fun countElfCalories(input: List<String>): ArrayList<Int> {
val results = arrayListOf<Int>()
var current = 0
for (s in input) {
if (s.isBlank()) {
results.add(current)
current = 0
} else {
current += s.toInt()
}
}
return results
}
fun part1(input: List<String>): Int {
return countElfCalories(input).max()
}
fun part2(input: List<String>): Int {
return countElfCalories(input).sortedDescending().take(3).sum()
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 1 | Kotlin | 0 | 1 | f49aea1755c8b2d479d730d9653603421c355b60 | 764 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumOfArrays.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
import java.util.Arrays
/**
* 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons
* @see <a href="https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons">
* Source</a>
*/
fun interface NumOfArrays {
operator fun invoke(n: Int, m: Int, k: Int): Int
}
/**
* Approach 1: Top-Down Dynamic Programming
*/
class NumOfArraysTopDown : NumOfArrays {
private lateinit var memo: Array<Array<IntArray>>
private var m0 = 0
private var n0 = 0
override fun invoke(n: Int, m: Int, k: Int): Int {
memo = Array(n) { Array(m + 1) { IntArray(k + 1) } }
for (i in 0 until n) {
for (j in 0..m) {
Arrays.fill(memo[i][j], -1)
}
}
n0 = n
m0 = m
return dp(0, 0, k)
}
private fun dp(i: Int, maxSoFar: Int, remain: Int): Int {
if (i == n0) {
return if (remain == 0) {
1
} else {
0
}
}
if (remain < 0) {
return 0
}
if (memo[i][maxSoFar][remain] != -1) {
return memo[i][maxSoFar][remain]
}
var ans = 0
for (num in 1..maxSoFar) {
ans = (ans + dp(i + 1, maxSoFar, remain)) % MOD
}
for (num in maxSoFar + 1..m0) {
ans = (ans + dp(i + 1, num, remain - 1)) % MOD
}
memo[i][maxSoFar][remain] = ans
return ans
}
}
/**
* Approach 2: Bottom-Up Dynamic Programming
*/
class NumOfArraysBottomUp : NumOfArrays {
override fun invoke(n: Int, m: Int, k: Int): Int {
val dp = Array(n + 1) {
Array(m + 1) {
IntArray(
k + 1,
)
}
}
for (num in 0 until dp[0].size) {
dp[n][num][0] = 1
}
for (i in n - 1 downTo 0) {
for (maxSoFar in m downTo 0) {
for (remain in 0..k) {
var ans = 0
for (num in 1..maxSoFar) {
ans = (ans + dp[i + 1][maxSoFar][remain]) % MOD
}
if (remain > 0) {
for (num in maxSoFar + 1..m) {
ans = (ans + dp[i + 1][num][remain - 1]) % MOD
}
}
dp[i][maxSoFar][remain] = ans
}
}
}
return dp[0][0][k]
}
}
/**
* Approach 3: Space-Optimized Dynamic Programming
*/
class NumOfArraysSpaceOptimizedDp : NumOfArrays {
override fun invoke(n: Int, m: Int, k: Int): Int {
var dp = Array(m + 1) { IntArray(k + 1) }
var prevDp = Array(m + 1) { IntArray(k + 1) }
for (num in dp.indices) {
prevDp[num][0] = 1
}
for (i in n - 1 downTo 0) {
dp = Array(m + 1) { IntArray(k + 1) }
for (maxSoFar in m downTo 0) {
for (remain in 0..k) {
var ans = 0
for (num in 1..maxSoFar) {
ans = (ans + prevDp[maxSoFar][remain]) % MOD
}
if (remain > 0) {
for (num in maxSoFar + 1..m) {
ans = (ans + prevDp[num][remain - 1]) % MOD
}
}
dp[maxSoFar][remain] = ans
}
}
prevDp = dp
}
return dp[0][k]
}
}
/**
* Approach 4: A Different DP + Prefix Sums
*/
class NumOfArraysPrefixSums : NumOfArrays {
override fun invoke(n: Int, m: Int, k: Int): Int {
val dp = Array(n + 1) { Array(m + 1) { LongArray(k + 1) } }
val prefix = Array(n + 1) { Array(m + 1) { LongArray(k + 1) } }
for (num in 1..m) {
dp[1][num][1] = 1
prefix[1][num][1] = prefix[1][num - 1][1] + 1
}
for (i in 1..n) {
for (maxNum in 1..m) {
for (cost in 1..k) {
var ans = maxNum.toLong() * dp[i - 1][maxNum][cost] % MOD
ans = (ans + prefix[i - 1][maxNum - 1][cost - 1]) % MOD
dp[i][maxNum][cost] = (dp[i][maxNum][cost] + ans) % MOD
prefix[i][maxNum][cost] = (prefix[i][maxNum - 1][cost] + dp[i][maxNum][cost]) % MOD
}
}
}
return prefix[n][m][k].toInt()
}
}
/**
* Approach 5: Space-Optimized Better DP
*/
class NumOfArraysBetterDp : NumOfArrays {
override fun invoke(n: Int, m: Int, k: Int): Int {
var dp = Array(m + 1) { LongArray(k + 1) }
var prefix = Array(m + 1) { LongArray(k + 1) }
var prevDp = Array(m + 1) { LongArray(k + 1) }
var prevPrefix = Array(m + 1) { LongArray(k + 1) }
for (num in 1..m) {
dp[num][1] = 1
}
for (i in 1..n) {
if (i > 1) {
dp = Array(m + 1) { LongArray(k + 1) }
}
prefix = Array(m + 1) { LongArray(k + 1) }
for (maxNum in 1..m) {
for (cost in 1..k) {
var ans = maxNum * prevDp[maxNum][cost] % MOD
ans = (ans + prevPrefix[maxNum - 1][cost - 1]) % MOD
dp[maxNum][cost] += ans
dp[maxNum][cost] %= MOD.toLong()
prefix[maxNum][cost] = prefix[maxNum - 1][cost] + dp[maxNum][cost]
prefix[maxNum][cost] %= MOD.toLong()
}
}
prevDp = dp
prevPrefix = prefix
}
return prefix[m][k].toInt()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 6,381 | kotlab | Apache License 2.0 |
src/main/kotlin/leetcode/kotlin/array/easy/1. Two Sum.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.array.easy
fun main() {
println(twoSum(intArrayOf(2, 11, 7, 15), 9).toList())
println(twoSum2(intArrayOf(2, 11, 7, 15), 9).toList())
println(twoSum3(intArrayOf(2, 11, 7, 15), 9).toList())
println(twoSum4(intArrayOf(2, 11, 7, 15), 9).toList())
}
private fun twoSum(nums: IntArray, target: Int): IntArray {
nums.forEachIndexed { fi, first ->
nums.forEachIndexed { si, second ->
if (first + second == target) return intArrayOf(
fi,
si
)
}
}
return intArrayOf()
}
private fun twoSum2(nums: IntArray, target: Int): IntArray {
for (i in 0 until nums.size - 1) {
for (j in i + 1 until nums.size) {
if (nums[i] + nums[j] == target) return intArrayOf(i, j)
}
}
return intArrayOf()
}
private fun twoSum3(nums: IntArray, target: Int): IntArray {
val map = HashMap<Int, Int>()
for (i in nums.indices) {
map[target - nums[i]]?.let { return intArrayOf(i, it) }
map[nums[i]] = i
}
return intArrayOf()
}
private fun twoSum4(nums: IntArray, target: Int): IntArray {
var x = -1
var y = -1
for (i in nums.indices) {
val j = nums.lastIndexOf(target - nums[i])
if (j > i) {
x = i
y = j
break
}
}
return intArrayOf(x, y)
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 1,382 | kotlinmaster | Apache License 2.0 |
src/main/kotlin/g2001_2100/s2039_the_time_when_the_network_becomes_idle/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2039_the_time_when_the_network_becomes_idle
// #Medium #Array #Breadth_First_Search #Graph
// #2023_06_23_Time_1197_ms_(100.00%)_Space_104.9_MB_(100.00%)
import java.util.PriorityQueue
class Solution {
fun networkBecomesIdle(edges: Array<IntArray>, pat: IntArray): Int {
val n = pat.size
val adj = ArrayList<ArrayList<Int>>()
for (i in 0 until n) {
adj.add(ArrayList())
}
for (arr in edges) {
adj[arr[0]].add(arr[1])
adj[arr[1]].add(arr[0])
}
val distance = IntArray(n)
distance.fill(99999)
distance[0] = 0
val pq = PriorityQueue { a1: IntArray, a2: IntArray ->
Integer.compare(
a1[1], a2[1]
)
}
pq.add(intArrayOf(0, 0))
while (pq.isNotEmpty()) {
val a = pq.poll()
val node = a[0]
for (nn in adj[node]) {
if (distance[node] + 1 < distance[nn]) {
distance[nn] = 1 + distance[node]
pq.add(intArrayOf(nn, distance[nn]))
}
}
}
var max = 0
for (i in 1 until n) {
val num1 = 2 * distance[i]
var num2 = num1 / pat[i]
if (num1 % pat[i] != 0) {
num2++
}
num2--
num2 *= pat[i]
max = Math.max(max, num2 + num1)
}
return max + 1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,492 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/leetcode/random_problems/medium/atoi/Main.kt | frikit | 254,842,734 | false | null | package com.leetcode.random_problems.medium.atoi
fun main() {
println("Test case 1:")
println(Solution().myAtoi("42")) // 42
println()
println("Test case 2:")
println(Solution().myAtoi(" -42")) // -42
println()
println("Test case 3:")
println(Solution().myAtoi("4193 with words")) // 4193
println()
println("Test case 4:")
println(Solution().myAtoi("-91283472332")) // -2147483648
println()
println("Test case 5:")
println(Solution().myAtoi("words and 987")) // 0
println()
println("Test case 6:")
println(Solution().myAtoi("3.14159")) // 3
println()
println("Test case 7:")
println(Solution().myAtoi("+-12")) // 0
println()
println("Test case 8:")
println(Solution().myAtoi(".1")) // 0
println()
}
class Solution {
fun myAtoi(s: String): Int {
if (s.trim().isEmpty()) return 0
val isPositive = s.trim().first() != '-'
var firstDigit = true
var finalNumb = ""
val isFirstSign = s.trim().first() == '+' || s.trim().first() == '-'
val drop = if (isFirstSign) 1 else 0
s.trim().drop(drop).takeWhile { it.isDigit() }.toCharArray().forEach {
if (!it.isDigit() && !it.isWhitespace() && firstDigit) {
return 0
} else if (it.isDigit() && firstDigit) {
finalNumb += it
firstDigit = false
} else if (it.isDigit() && finalNumb.isNotEmpty()) {
finalNumb += it
if (finalNumb.toBigInteger() !in Int.MIN_VALUE.toBigInteger()..Int.MAX_VALUE.toBigInteger()) {
return if (isPositive) {
Int.MAX_VALUE
} else {
Int.MIN_VALUE
}
}
} else if (!it.isDigit() && finalNumb.isNotEmpty() && !firstDigit) {
return if (isPositive) finalNumb.toInt() else finalNumb.toInt() * -1
}
}
if (finalNumb.isEmpty()) finalNumb = "0"
return if (isPositive) finalNumb.toInt() else finalNumb.toInt() * -1
}
}
| 0 | Kotlin | 0 | 0 | dda68313ba468163386239ab07f4d993f80783c7 | 2,143 | leet-code-problems | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortList.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <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
fun interface SortListStrategy {
operator fun invoke(head: ListNode): ListNode?
}
class TopDownMergeSort : SortListStrategy {
override operator fun invoke(head: ListNode): ListNode? {
if (head.next == null) return head
val mid = getMid(head) ?: ListNode(0)
val left = invoke(head)
val right = invoke(mid)
return merge(left, right)
}
private fun merge(x: ListNode?, y: ListNode?): ListNode? {
var a: ListNode? = x
var b: ListNode? = y
val dummyHead = ListNode(0)
var tail: ListNode? = dummyHead
while (a != null && b != null) {
if (a.value < b.value) {
tail?.next = a
a = a.next
tail = tail?.next
} else {
tail?.next = b
b = b.next
tail = tail?.next
}
}
tail?.next = a ?: b
return dummyHead.next
}
private fun getMid(head: ListNode): ListNode? {
var midPrev: ListNode? = null
var node: ListNode? = head
while (node?.next != null) {
midPrev = if (midPrev == null) node else midPrev.next
node = node.next?.next
}
val mid = midPrev?.next
midPrev?.next = null
return mid
}
}
class BottomUpMergeSort : SortListStrategy {
var tail: ListNode? = ListNode(0)
var nextSubList: ListNode? = ListNode(0)
override operator fun invoke(head: ListNode): ListNode? {
return sortList(head)
}
private fun sortList(head: ListNode?): ListNode? {
if (head?.next == null) return head
val n = getCount(head)
var start = head
val dummyHead = ListNode(0)
var size = 1
while (size < n) {
tail = dummyHead
while (start != null) {
if (start.next == null) {
tail?.next = start
break
}
val mid = split(start, size)
merge(start, mid)
start = nextSubList
}
start = dummyHead.next
size *= 2
}
return dummyHead.next
}
private fun split(start: ListNode, size: Int): ListNode? {
var midPrev: ListNode? = start
var end = start.next
// use fast and slow approach to find middle and end of second linked list
var index = 1
while (index < size && (midPrev?.next != null || end?.next != null)) {
if (end?.next != null) {
end = if (end.next?.next != null) end.next?.next else end.next
}
if (midPrev?.next != null) {
midPrev = midPrev.next
}
index++
}
val mid = midPrev?.next
midPrev?.next = null
nextSubList = end?.next
end?.next = null
// return the start of second linked list
return mid
}
private fun merge(list1: ListNode?, list2: ListNode?) {
var a = list1
var b = list2
val dummyHead = ListNode(0)
var newTail: ListNode? = dummyHead
while (a != null && b != null) {
if (a.value < b.value) {
newTail?.next = a
a = a.next
newTail = newTail?.next
} else {
newTail?.next = b
b = b.next
newTail = newTail?.next
}
}
newTail?.next = a ?: b
// traverse till the end of merged list to get the newTail
while (newTail?.next != null) {
newTail = newTail.next
}
// link the old tail with the head of merged list
tail?.next = dummyHead.next
// update the old tail to the new tail of merged list
tail = newTail
}
private fun getCount(head: ListNode?): Int {
var cnt = 0
var ptr = head
while (ptr != null) {
ptr = ptr.next
cnt++
}
return cnt
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,694 | kotlab | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2021/Day18.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2021
import com.nibado.projects.advent.*
object Day18 : Day {
private val input = resourceLines(2021, 18)
private fun String.toSnailNumber() = if(length == 1) toSnailNumberLit() else toSnailNumberPair()
private fun String.toSnailNumberLit() = SnailNumberLit(toInt())
private fun String.toSnailNumberPair(): SnailNumber {
val inside = drop(1).dropLast(1)
var left = ""
var brackets = 0
for (c in inside) {
if (c == '[') brackets++
if (c == ']') brackets--
if (c == ',' && brackets == 0) break
left += c
}
val right = inside.drop(left.length + 1)
return SnailNumberPair(left.toSnailNumber(), right.toSnailNumber())
}
private abstract class SnailNumber {
abstract fun magnitude(): Int
abstract fun addToLeftMost(value: Int)
abstract fun addToRightMost(value: Int)
abstract fun split(): Boolean
abstract fun explode(depth: Int = 0): Pair<Int, Int>?
fun reduce() {
do {
val exploded = explode() != null
val split = if (!exploded) split() else false
} while (exploded || split)
}
}
private class SnailNumberLit(var value: Int) : SnailNumber() {
override fun magnitude() = value
override fun addToLeftMost(value: Int) = run { this.value += value }
override fun addToRightMost(value: Int) = run { this.value += value }
override fun split() = false
override fun explode(depth: Int): Pair<Int, Int>? = null
override fun toString() = value.toString()
}
private class SnailNumberPair(var left: SnailNumber, var right: SnailNumber) : SnailNumber() {
override fun magnitude() = 3 * left.magnitude() + 2 * right.magnitude()
override fun addToLeftMost(value: Int) = left.addToLeftMost(value)
override fun addToRightMost(value: Int) = right.addToRightMost(value)
override fun split(): Boolean {
if (left is SnailNumberLit) {
(left as SnailNumberLit).value.let {
if (it >= 10) {
left = SnailNumberPair(SnailNumberLit(it / 2), SnailNumberLit((it + 1) / 2))
return true
}
}
}
if (left.split()) {
return true
}
if (right is SnailNumberLit) {
(right as SnailNumberLit).value.let {
if (it >= 10) {
right = SnailNumberPair(SnailNumberLit(it / 2), SnailNumberLit((it + 1) / 2))
return true
}
}
}
return right.split()
}
override fun explode(depth: Int): Pair<Int, Int>? {
if (depth == 4) {
return (left as SnailNumberLit).value to (right as SnailNumberLit).value
}
left.explode(depth + 1)?.let { (first, second) ->
if (first != -1 && second != -1) {
this.left = SnailNumberLit(0)
this.right.addToLeftMost(second)
return first to -1
}
if (second != -1) {
this.right.addToLeftMost(second)
return -1 to -1
}
return first to -1
}
right.explode(depth + 1)?.let { (first, second) ->
if (first != -1 && second != -1) {
this.right = SnailNumberLit(0)
this.left.addToRightMost(first)
return -1 to second
}
if (first != -1) {
this.left.addToRightMost(first)
return -1 to -1
}
return -1 to second
}
return null
}
override fun toString() = "[$left,$right]"
}
override fun part1(): Int {
return input.reduce { acc, s -> "[$acc,$s]".toSnailNumber().apply { reduce() }.toString() }
.let { it.toSnailNumber().magnitude() }
}
override fun part2(): Int {
return input.maxOf { first ->
input.filterNot { it == first }.maxOf { second ->
"[$first,$second]".toSnailNumber().apply { reduce() }.magnitude()
}
}
}
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 4,476 | adventofcode | MIT License |
year2020/day12/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day12/part1/Year2020Day12Part1.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Day 12: Rain Risk ---
Your ferry made decent progress toward the island, but the storm came in faster than anyone
expected. The ferry needs to take evasive actions!
Unfortunately, the ship's navigation computer seems to be malfunctioning; rather than giving a route
directly to safety, it produced extremely circuitous instructions. When the captain uses the PA
system to ask if anyone can help, you quickly volunteer.
The navigation instructions (your puzzle input) consists of a sequence of single-character actions
paired with integer input values. After staring at them for a few minutes, you work out what they
probably mean:
- Action N means to move north by the given value.
- Action S means to move south by the given value.
- Action E means to move east by the given value.
- Action W means to move west by the given value.
- Action L means to turn left the given number of degrees.
- Action R means to turn right the given number of degrees.
- Action F means to move forward by the given value in the direction the ship is currently facing.
The ship starts by facing east. Only the L and R actions change the direction the ship is facing.
(That is, if the ship is facing east and the next instruction is N10, the ship would move north 10
units, but would still move east if the following action were F.)
For example:
F10
N3
F7
R90
F11
These instructions would be handled as follows:
- F10 would move the ship 10 units east (because the ship starts by facing east) to east 10, north
0.
- N3 would move the ship 3 units north to east 10, north 3.
- F7 would move the ship another 7 units east (because the ship is still facing east) to east 17,
north 3.
- R90 would cause the ship to turn right by 90 degrees and face south; it remains at east 17, north
3.
- F11 would move the ship 11 units south to east 17, south 8.
At the end of these instructions, the ship's Manhattan distance (sum of the absolute values of its
east/west position and its north/south position) from its starting position is 17 + 8 = 25.
Figure out where the navigation instructions lead. What is the Manhattan distance between that
location and the ship's starting position?
*/
package com.curtislb.adventofcode.year2020.day12.part1
import com.curtislb.adventofcode.common.geometry.Direction
import com.curtislb.adventofcode.common.geometry.Pose
import com.curtislb.adventofcode.common.geometry.Point
import com.curtislb.adventofcode.year2020.day12.navigation.SimpleNavigationShip
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2020, day 12, part 1.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
val file = inputPath.toFile()
val ship = SimpleNavigationShip(Pose(Point.ORIGIN, Direction.RIGHT))
file.forEachLine { ship.followInstruction(it) }
return ship.pose.position manhattanDistance Point.ORIGIN
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 3,014 | AdventOfCode | MIT License |
src/main/kotlin/com/ginsberg/advent2021/Day05.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 5 - Hydrothermal Venture
* Problem Description: http://adventofcode.com/2021/day/5
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day5/
*/
package com.ginsberg.advent2021
class Day05(input: List<String>) {
private val instructions = input.map { parseRow(it) }
fun solvePart1(): Int =
solve { it.first sharesAxisWith it.second }
fun solvePart2(): Int =
solve { true }
private fun solve(lineFilter: (Pair<Point2d, Point2d>) -> Boolean) =
instructions
.filter { lineFilter(it) }
.flatMap { it.first lineTo it.second }
.groupingBy { it }
.eachCount()
.count { it.value > 1 }
private fun parseRow(input: String): Pair<Point2d, Point2d> =
Pair(
input.substringBefore(" ").split(",").map { it.toInt() }.let { Point2d(it.first(), it.last()) },
input.substringAfterLast(" ").split(",").map { it.toInt() }.let { Point2d(it.first(), it.last()) }
)
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 1,099 | advent-2021-kotlin | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year19/Day06.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year19
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.asPair
import com.grappenmaker.aoc.bfsDistance
fun PuzzleSet.day6() = puzzle {
data class Entry(val around: String, val orbiter: String)
val entries = inputLines.map {
val (around, orbiter) = it.split(")").asPair()
Entry(around, orbiter)
}
val reverse = entries.associate { it.orbiter to it.around }
fun String.orbits(): List<String> = reverse[this]?.let { listOf(it) + it.orbits() } ?: emptyList()
val unique = entries.flatMap { listOf(it.around, it.orbiter) }.toSet()
partOne = unique.sumOf { it.orbits().size }.s()
val you = entries.first { it.orbiter == "YOU" }
val san = entries.first { it.orbiter == "SAN" }
val graph = unique.associateWith { from ->
listOfNotNull(reverse[from]) + entries.filter { it.around == from }.map { it.orbiter }
}
partTwo = bfsDistance(you.around, isEnd = { it == san.around }, neighbors = { graph[it]!! }).dist.s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,031 | advent-of-code | The Unlicense |
kotlin/src/com/daily/algothrim/leetcode/SortArrayByParityII.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 922. 按奇偶排序数组 II
*
* 给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
* 对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
*
* 你可以返回任何满足上述条件的数组作为答案。
*
* 示例:
*
* 输入:[4,2,5,7]
* 输出:[4,5,2,7]
* 解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
* */
class SortArrayByParityII {
companion object {
@JvmStatic
fun main(args: Array<String>) {
SortArrayByParityII().solution(intArrayOf(4, 2, 5, 7)).forEach {
println(it)
}
}
}
fun solution(A: IntArray): IntArray {
var evenIndex = 0
var oddIndex = 1
while (evenIndex < A.size) {
// 索引为偶数值为奇数
if (A[evenIndex] % 2 != 0) {
while (oddIndex < A.size) {
// 索引为奇数值为偶数
if (A[oddIndex] % 2 == 0) {
val temp = A[evenIndex]
A[evenIndex] = A[oddIndex]
A[oddIndex] = temp
break
}
oddIndex += 2
}
}
evenIndex += 2
}
return A
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 1,425 | daily_algorithm | Apache License 2.0 |
src/Day06.kt | xabgesagtx | 572,139,500 | false | {"Kotlin": 23192} | fun main() {
fun checkForMarker(input: String, distinctCharacters: Int): Int {
return input
.windowed(distinctCharacters)
.indexOfFirst { window -> window.toSet().size == distinctCharacters } + distinctCharacters
}
fun part1(input: String): Int {
return checkForMarker(input, 4)
}
fun part2(input: String): Int {
return checkForMarker(input, 14)
}
// test if implementation meets criteria from the description, like:
check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7)
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29)
val input = readInput("Day06").first()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 976d56bd723a7fc712074066949e03a770219b10 | 765 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc/year2021/Day07.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2021
import aoc.Puzzle
import kotlin.math.abs
/**
* [Day 7 - Advent of Code 2021](https://adventofcode.com/2021/day/7)
*/
object Day07 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int {
val map = input.lineSequence()
.single()
.split(",")
.map { it.toInt() }
.sorted()
.let {
buildMap {
(it.first()..it.last()).associateWithTo(this) { 0 }
it.groupingBy { it }.eachCountTo(this)
}
}
val cumulative = map.values.runningReduce(Int::plus)
val threshold = (cumulative.last() + 1) / 2
val median = cumulative.indexOfFirst { it > threshold } + map.keys.first()
return map.filterValues { it > 0 }.map { (pos, count) -> abs(pos - median) * count }.sum()
}
override fun solvePartTwo(input: String): Int = TODO()
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 940 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountingBits.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <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
/**
* 338. Counting Bits
* @see <a href="https://leetcode.com/problems/counting-bits">Source</a>
*/
fun interface CountingBits {
operator fun invoke(n: Int): IntArray
}
/**
* Approach 1: Pop Count
* Time complexity: O(n log n)
* Space complexity: O(1)
*/
class CountingBitsPopCount : CountingBits {
override operator fun invoke(n: Int): IntArray {
val ans = IntArray(n + 1)
for (x in 0..n) {
ans[x] = popCount(x)
}
return ans
}
private fun popCount(x: Int): Int {
var count = 0
var z = x
while (z != 0) {
z = z and z - 1 // zeroing out the least significant nonzero bit
++count
}
return count
}
}
/**
* Approach 2: DP + Most Significant Bit
* Time complexity: O(n)
* Space complexity: O(1)
*/
class MostSignificantBit : CountingBits {
override operator fun invoke(n: Int): IntArray {
val ans = IntArray(n + 1)
var x = 0
var b = 1
while (b <= n) {
while (x < b && x + b <= n) {
ans[x + b] = ans[x] + 1
++x
}
x = 0
b = b shl 1
}
return ans
}
}
/**
* Approach 3: DP + Least Significant Bit
* Time complexity: O(n)
* Space complexity: O(1)
*/
class LeastSignificantBit : CountingBits {
override operator fun invoke(n: Int): IntArray {
val ans = IntArray(n + 1)
for (x in 1..n) {
ans[x] = ans[x shr 1] + (x and 1)
}
return ans
}
}
/**
* Approach 4: DP + Last Set Bit
* Time complexity: O(n)
* Space complexity: O(1)
*/
class LastSetBit : CountingBits {
override operator fun invoke(n: Int): IntArray {
val ans = IntArray(n + 1)
for (x in 1..n) {
ans[x] = ans[x and x - 1] + 1
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,524 | kotlab | Apache License 2.0 |
src/main/kotlin/com/github/wakingrufus/eloleague/swiss/Swiss.kt | wakingrufus | 113,580,870 | false | null | package com.github.wakingrufus.eloleague.swiss
import com.github.wakingrufus.eloleague.game.GameItem
import java.util.*
import kotlin.math.pow
import kotlin.math.roundToInt
fun totalRounds(teams: Int): Int {
return teams.toDouble().pow(2).roundToInt()
}
fun randomPairing(teams: List<SwissTeamItem>): List<SwissPairingItem> {
return teams.take(teams.size / 2).toList().shuffled()
.zip(teams.takeLast(teams.size / 2).shuffled())
.map {
SwissPairingItem(id = UUID.randomUUID().toString()).apply {
teamsProperty.setAll(listOf(it.first, it.second))
}
}.toList()
}
fun pairing(records: List<SwissStanding>, previousPairings: List<SwissPairingItem>): List<SwissPairingItem> {
val playersToPair = mutableListOf<SwissStanding>()
playersToPair.addAll(records.sortedWith(standingSorter))
return records.sortedWith(standingSorter).zipWithNext { first, second ->
if (playersToPair.any { it.team.id == first.team.id }) {
SwissPairingItem(id = UUID.randomUUID().toString()
).apply {
this.teamsProperty.addAll(first.team, second.team)
playersToPair.remove(first)
playersToPair.remove(second)
}
} else {
null
}
}.filterNotNull()
}
fun gameMatchesPairing(game: GameItem, pairing: SwissPairingItem): Boolean =
pairing.teamsProperty
.all { team ->
listOf(game.team1Players, game.team2Players)
.any { team.players.map { it.id }.containsAll(it.map { it.id }) }
}
fun calculateCurrentStandings(tournament: SwissTournamentItem): List<SwissStanding> {
return tournament.rounds.fold(
initial = tournament.teams.map { SwissStanding(it) },
operation = ::addRoundToStandings)
.let(::calculateOpponentStats)
}
fun calculateOpponentStats(standings: List<SwissStanding>): List<SwissStanding> =
standings.map { standing ->
standing.copy(
opponentGameWinPct = standing.opponents
.map { opponentId ->
standings.first { it.team.id == opponentId }
}.map { arrayOf(gameWinPct(it), .33).max() as Double }.average(),
opponentMatchWinPct = standing.opponents
.map { opponentId ->
standings.first { it.team.id == opponentId }
}.map { arrayOf(matchWinPct(it), .33).max() as Double }.average())
}
fun addRoundToStandings(oldStandings: List<SwissStanding>, round: SwissRoundItem): List<SwissStanding> =
round.pairingsProperty.flatMap { pairing ->
pairing.teamsProperty.map { teamItem ->
oldStandings.first { it.team.id == teamItem.id }.let {
it.copy(
gamePoints = it.gamePoints + pairing.gamePoints(teamItem.id),
totalGames = it.totalGames + pairing.gamesProperty.size,
matchPoints = it.matchPoints + matchPoints(pairing = pairing, teamId = teamItem.id),
totalMatches = it.totalMatches + 1,
opponents = it.opponents.plus(pairing.teamsProperty.map { it.id }.minus(teamItem.id))
)
}
}
}
fun matchPoints(pairing: SwissPairingItem, teamId: String): Int = when {
pairing.getWinningTeam() == null -> 1
pairing.getWinningTeam() == teamId -> 3
else -> 0
}
fun gameWinPct(standing: SwissStanding): Double =
standing.gamePoints.toDouble() / standing.totalGames.toDouble().times(3)
fun matchWinPct(standing: SwissStanding): Double =
standing.matchPoints.toDouble() / (standing.totalMatches.toDouble().times(3))
val standingSorter: Comparator<SwissStanding> =
Comparator.comparingInt(SwissStanding::matchPoints)
.then(Comparator.comparingDouble(SwissStanding::opponentMatchWinPct))
.then(Comparator.comparingDouble(::gameWinPct))
.then(Comparator.comparingDouble(SwissStanding::opponentGameWinPct)).reversed() | 3 | Kotlin | 0 | 1 | 49fdacf104b5bb42ea72ec72f6b36aab33b1b8f8 | 4,310 | elo-league-jfx | MIT License |
src/commonMain/kotlin/io/nacular/measured/units/Units.kt | nacular | 153,705,303 | false | {"Kotlin": 58838} | package io.nacular.measured.units
import kotlin.jvm.JvmName
import kotlin.math.roundToInt
/**
* Base class for all types that can represent a unit of measure.
* A Units type can have multiple "members", each being some fraction of the base
* unit for that type. Time for example, might have seconds as the base unit
* and minute as a unit that is 60 times the base unit. This allows for a
* set of different representations of the unit.
*
* @constructor
* @param suffix to use when printing the unit in a human readable way
* @param ratio of this unit relative to the base-unit
*/
abstract class Units(val suffix: String, val ratio: Double = 1.0) {
/**
* Whether there should be a space between the unit's name and the magnitude
* of a value with that unit. Most units are displayed like this: 45 kg. But
* some, like degrees are done w/o the space: 45°
*/
protected open val spaceBetweenMagnitude = true
internal fun measureSuffix() = if (spaceBetweenMagnitude) " $suffix" else suffix
override fun toString() = suffix
override fun hashCode(): Int {
var result = suffix.hashCode()
result = 31 * result + ratio.hashCode()
result = 31 * result + spaceBetweenMagnitude.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Units) return false
if (suffix != other.suffix) return false
if (ratio != other.ratio ) return false
if (spaceBetweenMagnitude != other.spaceBetweenMagnitude) return false
return true
}
}
/**
* Represents the product of two Units: A * B.
*
* @constructor
* @param first unit being multiplied
* @param second unit being multiplied
*/
class UnitsProduct<A: Units, B: Units>(val first: A, val second: B): Units(if (first==second) "($first)^2" else "$first$second", first.ratio * second.ratio)
typealias Square<T> = UnitsProduct<T, T>
/**
* Represents the ratio of two Units: A / B.
*
* @constructor
* @param numerator unit being divided
* @param denominator unit dividing numerator
*/
class UnitsRatio<A: Units, B: Units>(val numerator: A, val denominator: B): Units("$numerator/$denominator", numerator.ratio / denominator.ratio) {
/** The Inverse of this unit. */
val reciprocal by lazy { UnitsRatio(denominator, numerator) }
}
/**
* The inverse of a given Units.
*
* @constructor
* @param unit this is the inverse of
*/
class InverseUnits<T: Units>(val unit: T): Units("1/${unit.suffix}", 1 / unit.ratio)
/**
* Compares two units
* @param other unit to compare
* @return -1 if this unit is smaller, 1 if the other is smaller, and 0 if they are equal
*/
operator fun <A: Units, B: A> A.compareTo(other: B): Int = ratio.compareTo(other.ratio)
/**
* @return the smaller of the two Units
*/
fun <A: Units, B: A> minOf(first: A, second: B) = if (first < second) first else second
/**
* A quantity with a unit type.
*
* @property amount of the measure (i.e. it's coefficient)
* @property units of the measure
*/
class Measure<T: Units>(val amount: Double, val units: T): Comparable<Measure<T>> {
/**
* Convert this Measure into another compatible one with different units. Type must share parent
* (i.e. Mile into Kilometer, because they both are made from Distance)
*/
infix fun <A: T> `as`(other: A): Measure<T> = if (units == other) this else Measure(this `in` other, other)
/**
* Gets the value of the Measure in the given unit.
*/
infix fun <A: T> `in`(other: A): Double = if (units == other) amount else amount * (units.ratio / other.ratio)
/**
* Add another compatible quantity to this one
*/
operator fun plus(other: Measure<T>): Measure<T> = minOf(units, other.units).let { Measure((this `in` it) + (other `in` it), it) }
/**
* Subtract a compatible quantity from this one
*/
operator fun minus(other: Measure<T>): Measure<T> = minOf(units, other.units).let { Measure((this `in` it) - (other `in` it), it) }
operator fun unaryMinus(): Measure<T> = Measure(-amount, units)
/**
* Multiply this by a scalar value, used for things like "double this distance",
* "1.5 times the speed", etc
*/
operator fun times(other: Number): Measure<T> = amount * other.toDouble() * units
/**
* Divide this by a scalar, used for things like "halve the speed"
*/
operator fun div(other: Number): Measure<T> = amount / other.toDouble() * units
/**
* Rounds this Measure to the closest integer value.
*/
fun roundToInt(): Measure<T> = amount.roundToInt() * units
/**
* Compare this value with another quantity - which must have the same type
* Units are converted before comparison
*/
override fun compareTo(other: Measure<T>): Int = (this `as` other.units).amount.compareTo(other.amount)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Measure<*>) return false
// if (this.amount == 0.0 && other.amount == 0.0) return true TODO: Should this be true?
val resultUnit = minOf(units, (other as Measure<T>).units)
val a = this `in` resultUnit
val b = other `in` resultUnit
return a == b
}
override fun hashCode(): Int {
return (amount * units.ratio).hashCode()
}
override fun toString(): String = "$amount${units.measureSuffix()}"
}
// region ================ Units * Units Math ============================
/** A * B */ operator fun <A: Units, B: Units> A. times(other: B ): UnitsProduct<A, B> = UnitsProduct(this, other)
@JvmName("times7") operator fun <A: Units> A. times(other: InverseUnits<A> ): Double = ratio / other.ratio
/** A * (1 / B) */ operator fun <A: Units, B: Units> A. times(other: InverseUnits<B> ): UnitsRatio<A, B> = this / other.unit
/** A * (1 / A^2) */ operator fun <A: Units> A. times(other: InverseUnits<Square<A>> ): Measure<InverseUnits<A>> = ratio / other.unit.first.ratio / other.unit.first
/** A * (B / A) */ operator fun <A: Units, B: Units> A. times(other: UnitsRatio<B, A>): Measure<B> = ratio / other.denominator.ratio * other.numerator
/** (A / B) * B */ @JvmName("times1") operator fun <A: Units, B: Units> UnitsRatio<A, B>. times(other: B ): Measure<A> = other.ratio / denominator.ratio * numerator
/** (A / (B * C)) * B */ @JvmName("times2") operator fun <A: Units, B: Units, C: Units> UnitsRatio<A, UnitsProduct<B, C>>.times(other: B ): Measure<UnitsRatio<A, C>> = other.ratio / denominator.first.ratio * (numerator / denominator.second)
/** (A / (B * C)) * D) */ @JvmName("times3") operator fun <A: Units, B: Units, C: Units, D: Units> UnitsRatio<A, UnitsProduct<B, C>>.times(other: D ): UnitsRatio<UnitsProduct<A, D>, UnitsProduct<B, C>> = numerator * other / denominator
/** (A / B) * (A / B) */ @JvmName("times4") operator fun <A: Units, B: Units> UnitsRatio<A, B>. times(other: UnitsRatio<A, B>): UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, B>> = numerator * other.numerator / (denominator * other.denominator)
/** (A / B) * (B / A)) */ @JvmName("times5") operator fun <A: Units, B: Units> UnitsRatio<A, B>. times(other: UnitsRatio<B, A>): Double = numerator * other.numerator / (denominator * other.denominator)
/** (A / B) * (C / D)) */ @JvmName("times6") operator fun <A: Units, B: Units, C: Units, D: Units> UnitsRatio<A, B>. times(other: UnitsRatio<C, D>): UnitsRatio<UnitsProduct<A, C>, UnitsProduct<B, D>> = numerator * other.numerator / (denominator * other.denominator)
@JvmName("times8") operator fun <A: Units> InverseUnits<A>. times(other: A ): Double = ratio * other.ratio
@JvmName("times9") operator fun <A: Units, B: Units> InverseUnits<A>. times(other: B ): UnitsRatio<B, A> = other * this
// FIXME operator fun <A: Units, B: Units> UnitsProduct<A, B>. times(other: InverseUnits<A> ): Measure<B> = units * other
// FIXME operator fun <A: Units, B: Units> UnitsProduct<A, B>. times(other: InverseUnits<B> ): A = units * other
// FIXME operator fun <A: Units, B: Units, C: Units> UnitsProduct<A, B>. times(other: UnitsRatio<C, B>): UnitsRatio<A, C> = units * other
// FIXME operator fun <A: Units, B: Units, C: Units> UnitsProduct<A, B>. times(other: UnitsRatio<C, A>): UnitsRatio<B, C> = units * other
// FIXME operator fun <A: Units, B: Units, C: Units> UnitsProduct<A, B>. times(other: UnitsRatio<B, C>): UnitsRatio<A, C> = units * other
// FIXME operator fun <A: Units, B: Units, C: Units> UnitsProduct<A, B>. times(other: UnitsRatio<A, C>): UnitsRatio<B, C> = units * other
// FIXME operator fun <A: Units, B: Units> UnitsProduct<A, B>. times(other: UnitsRatio<A, A>): UnitsRatio<B, A> = units * other
// FIXME operator fun <A: Units, B: Units> UnitsProduct<A, B>. times(other: UnitsRatio<B, B>): UnitsRatio<A, B> = units * other
// endregion
// region ================ Units / Units Math ============================
// This cannot be defined given the next definition unfortunately
//operator fun <A: Units> A.div(other: A) = this.ratio / other.ratio
/** A / B */ operator fun <A: Units, B: Units> A.div (other: B ): UnitsRatio<A, B> = UnitsRatio(this, other)
/** A / (A / B) == A * (B / A) */ operator fun <A: Units, B: Units> A.div (other: UnitsRatio<A, B>): Measure<B> = this * other.reciprocal
/** (A * B) / A */ @JvmName("div1") operator fun <A: Units, B: Units> UnitsProduct<A, B>.div(other: A ): Measure<B> = first.ratio / other.ratio * second
/** (A * B) / B */ @JvmName("div2") operator fun <A: Units, B: Units> UnitsProduct<A, B>.div(other: B ): Measure<A> = second.ratio / other.ratio * first
/** (A * A) / A */ @JvmName("div3") operator fun <A: Units> UnitsProduct<A, A>.div(other: A ): Measure<A> = first.ratio / other.ratio * second
/** (A * B) / (C * B) */ @JvmName("div1") operator fun <A: Units, B: Units, C: Units> UnitsProduct<A, B>.div(other: UnitsProduct<C, B>): UnitsRatio<A, C> = first / other.first
/** (A * B) / (C * A) */ @JvmName("div2") operator fun <A: Units, B: Units, C: Units> UnitsProduct<A, B>.div(other: UnitsProduct<C, A>): UnitsRatio<B, C> = second / other.first
/** (A * B) / (B * C) */ @JvmName("div3") operator fun <A: Units, B: Units, C: Units> UnitsProduct<A, B>.div(other: UnitsProduct<B, C>): UnitsRatio<A, C> = first / other.second
/** (A * B) / (A * C) */ @JvmName("div4") operator fun <A: Units, B: Units, C: Units> UnitsProduct<A, B>.div(other: UnitsProduct<A, C>): UnitsRatio<B, C> = second / other.second
/** (A * B) / (A * A) */ @JvmName("div5") operator fun <A: Units, B: Units> UnitsProduct<A, B>.div(other: UnitsProduct<A, A>): UnitsRatio<B, A> = second / other.second
/** (A * B) / (A * B) */ @JvmName("div7") operator fun <A: Units, B: Units> UnitsProduct<A, B>.div(other: UnitsProduct<A, B>): Double = ratio / other.ratio
/** (A * B) / (B * A) */ @JvmName("div6") operator fun <A: Units, B: Units> UnitsProduct<A, B>.div(other: UnitsProduct<B, A>): Double = ratio / other.ratio
/** (A * B) / (B * B) */ @JvmName("div8") operator fun <A: Units, B: Units> UnitsProduct<A, B>.div(other: UnitsProduct<B, B>): Measure<UnitsRatio<A, B>> = second.ratio / other.second.ratio * (first / other.first)
@JvmName("div1") operator fun <A: Units, B: Units> UnitsRatio<A, B>. div(other: UnitsRatio<A, B>): Double = this * other.reciprocal
@JvmName("div2") operator fun <A: Units, B: Units> UnitsRatio<A, B>. div(other: UnitsRatio<B, A>): UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, B>> = this * other.reciprocal
@JvmName("div3") operator fun <A: Units, B: Units, C: Units, D: Units> UnitsRatio<A, B>. div(other: UnitsRatio<C, D>): UnitsRatio<UnitsProduct<A, D>, UnitsProduct<B, C>> = this * other.reciprocal
operator fun <A: Units, B: Units> UnitsRatio<A, B>. div(other: B ): UnitsRatio<A, UnitsProduct<B, B>> = numerator / (denominator * other)
@JvmName("div1") operator fun <A: Units, B: Units> UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, B>>.div(other: A ): Measure<UnitsRatio<A, UnitsProduct<B, B>>> = numerator.first.ratio / other.ratio * (numerator.second / denominator)
@JvmName("div2") operator fun <A: Units, B: Units, C: Units> UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, C>>.div(other: A ): Measure<UnitsRatio<A, UnitsProduct<B, C>>> = numerator.first.ratio / other.ratio * (numerator.second / denominator)
@JvmName("div3") operator fun <A: Units, B: Units, C: Units, D: Units> UnitsRatio<UnitsProduct<A, B>, UnitsProduct<C, D>>.div(other: A ): Measure<UnitsRatio<B, UnitsProduct<C, D>>> = numerator.first.ratio / other.ratio * (numerator.second / denominator)
// m/s * (s^2/m) => s
operator fun <A: Units, B: Units> UnitsRatio<A, B>.div(other: UnitsRatio<A, Square<B>>): Measure<B> = numerator.ratio / other.numerator.ratio * (other.denominator / denominator)
// m/s / s => m/s^2
operator fun <A: Units> InverseUnits<A>.div(other: A): Measure<InverseUnits<Square<A>>> = ratio * other.ratio * 1 / Square(other, other)
// endregion
// region ================ Measure * Measure Math ========================
@JvmName("times1") operator fun <A: Units, B: Units> Measure<A>. times(other: Measure<B> ): Measure<UnitsProduct<A, B>> = amount * other.amount * (units * other.units)
@JvmName("times2") operator fun <A: Units, B: Units> Measure<A>. times(other: Measure<UnitsRatio<B, A>>): Measure<B> = amount * other.amount * (units * other.units)
@JvmName("times7") operator fun <A: Units, B: Units> Measure<A>. times(other: Measure<InverseUnits<B>> ): Measure<UnitsRatio<A, B>> = amount * other.amount * (units * other.units)
@JvmName("times3") operator fun <A: Units, B: Units> Measure<UnitsRatio<A, B>>. times(other: Measure<B> ): Measure<A> = amount * other.amount * (units * other.units)
@JvmName("times4") operator fun <A: Units, B: Units> Measure<UnitsRatio<A, B>>. times(other: Measure<UnitsRatio<A, B>>): Measure<UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, B>>> = amount * other.amount * (units * other.units)
@JvmName("times5") operator fun <A: Units, B: Units, C: Units> Measure<UnitsRatio<A, UnitsProduct<B, C>>>.times(other: Measure<B> ): Measure<UnitsRatio<A, C>> = amount * other.amount * (units * other.units)
@JvmName("times6") operator fun <A: Units, B: Units, C: Units, D: Units> Measure<UnitsRatio<A, UnitsProduct<B, C>>>.times(other: Measure<D> ): Measure<UnitsRatio<UnitsProduct<A, D>, UnitsProduct<B, C>>> = amount * other.amount * (units * other.units)
@JvmName("times8" ) operator fun <A: Units> Measure<A>.times (other: Measure<InverseUnits<Square<A>>>): Measure<InverseUnits<A>> = amount * other.amount * (units * other.units)
@JvmName("times9" ) operator fun <A: Units> Measure<InverseUnits<Square<A>>>.times(other: Measure<A> ): Measure<InverseUnits<A>> = other * this
@JvmName("times10") operator fun <A: Units> Measure<InverseUnits<A>>.times (other: Measure<A> ): Double = amount * other.amount * (units * other.units)
@JvmName("times11") operator fun <A: Units> Measure<A>.times (other: Measure<InverseUnits<A>> ): Double = other * this
@JvmName("times10") operator fun <A: Units> Measure<InverseUnits<A>>.times (other: Measure<InverseUnits<A>> ): Measure<InverseUnits<Square<A>>> = amount * other.amount * InverseUnits(Square(units.unit, units.unit))
// endregion
// TODO: Kapt code generation possible?
operator fun <A: Units> Measure<A>.rem(other: Measure<A>): Double = amount % other.amount * (units.ratio % other.units.ratio)
// region ================ Measure / Measure Math ========================
@JvmName("div16") operator fun <A: Units> Measure<A>. div(other: Measure<A> ): Double = amount / other.amount * (units.ratio / other.units.ratio)
@JvmName("div16") operator fun <A: Units, B: Units> Measure<A>. div(other: Measure<B> ): Measure<UnitsRatio<A, B>> = amount / other.amount * (units / other.units)
@JvmName("div1" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.div(other: Measure<A> ): Measure<B> = amount / other.amount * (units / other.units)
@JvmName("div2" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.div(other: Measure<B> ): Measure<A> = amount / other.amount * (units / other.units)
@JvmName("div3" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.div(other: Measure<UnitsProduct<C, B>>): Measure<UnitsRatio<A, C>> = amount / other.amount * (units / other.units)
@JvmName("div4" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.div(other: Measure<UnitsProduct<C, A>>): Measure<UnitsRatio<B, C>> = amount / other.amount * (units / other.units)
@JvmName("div5" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.div(other: Measure<UnitsProduct<B, C>>): Measure<UnitsRatio<A, C>> = amount / other.amount * (units / other.units)
@JvmName("div6" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.div(other: Measure<UnitsProduct<A, C>>): Measure<UnitsRatio<B, C>> = amount / other.amount * (units / other.units)
@JvmName("div7" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.div(other: Measure<UnitsProduct<A, A>>): Measure<UnitsRatio<B, A>> = amount / other.amount * (units / other.units)
@JvmName("div8" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.div(other: Measure<UnitsProduct<B, B>>): Measure<UnitsRatio<A, B>> = amount / other.amount * (units / other.units)
@JvmName("div9" ) operator fun <A: Units, B: Units> Measure<UnitsRatio<A, B>>. div(other: Measure<B> ): Measure<UnitsRatio<A, UnitsProduct<B, B>>> = amount / other.amount * (units / other.units)
@JvmName("div10") operator fun <A: Units, B: Units, C: Units, D: Units> Measure<UnitsRatio<A, B>>. div(other: Measure<UnitsRatio<C, D>> ): Measure<UnitsRatio<UnitsProduct<A, D>, UnitsProduct<B, C>>> = amount / other.amount * (units / other.units)
@JvmName("div11") operator fun <A: Units, B: Units> Measure<UnitsRatio<A, B>>. div(other: Measure<UnitsRatio<A, Square<B>>>): Measure<B> = amount / other.amount * (units / other.units)
@JvmName("div12") operator fun <A: Units, B: Units> Measure<UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, B>>>.div(other: Measure<A> ): Measure<UnitsRatio<A, UnitsProduct<B, B>>> = amount / other.amount * (units / other.units)
@JvmName("div13") operator fun <A: Units, B: Units, C: Units> Measure<UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, C>>>.div(other: Measure<A> ): Measure<UnitsRatio<A, UnitsProduct<B, C>>> = amount / other.amount * (units / other.units)
@JvmName("div14") operator fun <A: Units, B: Units, C: Units, D: Units> Measure<UnitsRatio<UnitsProduct<A, B>, UnitsProduct<C, D>>>.div(other: Measure<A> ): Measure<UnitsRatio<B, UnitsProduct<C, D>>> = amount / other.amount * (units / other.units)
@JvmName("div15") operator fun <A: Units, B: Units> Measure<A>. div(other: Measure<UnitsRatio<A, B>> ): Measure<B> = amount / other.amount * (units / other.units)
@JvmName("div17") operator fun <A: Units> Measure<InverseUnits<A>>.div (other: Measure<InverseUnits<Square<A>>>): Measure<A> = this.amount / other.amount * other.units.unit.first
@JvmName("div18") operator fun <A: Units> Measure<InverseUnits<A>>.div (other: Measure<A> ): Measure<InverseUnits<Square<A>>> = (this.amount / other.amount) * (units / other.units)
// endregion
// region ================ Measure * Units Math ============================
@JvmName("times16") operator fun <A: Units> Measure<InverseUnits<A>>. times(other: A ): Double = amount * (units * other)
@JvmName("times16") operator fun <A: Units> Measure<A>. times(other: InverseUnits<A> ): Double = amount * (units * other)
@JvmName("times16") operator fun <A: Units, B: Units> Measure<InverseUnits<A>>. times(other: B ): Measure<UnitsRatio<B, A>> = amount * (units * other)
// FIXME @JvmName("times1" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.times(other: InverseUnits<A> ): Measure<B> = amount * (units * other)
// FIXME @JvmName("times2" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.times(other: InverseUnits<B> ): Measure<A> = amount * (units * other)
// FIXME @JvmName("times3" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.times(other: UnitsRatio<C, B>): Measure<UnitsRatio<A, C>> = amount * (units * other)
// FIXME @JvmName("times4" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.times(other: UnitsRatio<C, A>): Measure<UnitsRatio<B, C>> = amount * (units * other)
// FIXME @JvmName("times5" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.times(other: UnitsRatio<B, C>): Measure<UnitsRatio<A, C>> = amount * (units * other)
// FIXME @JvmName("times6" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.times(other: UnitsRatio<A, C>): Measure<UnitsRatio<B, C>> = amount * (units * other)
// FIXME @JvmName("times7" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.times(other: UnitsRatio<A, A>): Measure<UnitsRatio<B, A>> = amount * (units * other)
// FIXME @JvmName("times8" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.times(other: UnitsRatio<B, B>): Measure<UnitsRatio<A, B>> = amount * (units * other)
@JvmName("times1") operator fun <A: Units, B: Units> Measure<A>. times(other: B ): Measure<UnitsProduct<A, B>> = amount * (units * other)
@JvmName("times2") operator fun <A: Units, B: Units> Measure<A>. times(other: UnitsRatio<B, A>): Measure<B> = amount * (units * other)
@JvmName("times7") operator fun <A: Units, B: Units> Measure<A>. times(other: InverseUnits<B> ): Measure<UnitsRatio<A, B>> = amount * (units * other)
@JvmName("times3") operator fun <A: Units, B: Units> Measure<UnitsRatio<A, B>>. times(other: B ): Measure<A> = amount * (units * other)
@JvmName("times4") operator fun <A: Units, B: Units> Measure<UnitsRatio<A, B>>. times(other: UnitsRatio<A, B>): Measure<UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, B>>> = amount * (units * other)
@JvmName("times5") operator fun <A: Units, B: Units, C: Units> Measure<UnitsRatio<A, UnitsProduct<B, C>>>.times(other: B ): Measure<UnitsRatio<A, C>> = amount * (units * other)
@JvmName("times6") operator fun <A: Units, B: Units, C: Units, D: Units> Measure<UnitsRatio<A, UnitsProduct<B, C>>>.times(other: D ): Measure<UnitsRatio<UnitsProduct<A, D>, UnitsProduct<B, C>>> = amount * (units * other)
// endregion
// region ================ Measure / Units Math =========================
@JvmName("div16") operator fun <A: Units> Measure<A>. div(other: A ): Double = amount * (units.ratio / other.ratio)
@JvmName("div16") operator fun <A: Units, B: Units> Measure<A>. div(other: B ): Measure<UnitsRatio<A, B>> = amount * (units / other)
@JvmName("div1" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.div(other: A ): Measure<B> = amount * (units / other)
@JvmName("div2" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.div(other: B ): Measure<A> = amount * (units / other)
@JvmName("div3" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.div(other: UnitsProduct<C, B>): Measure<UnitsRatio<A, C>> = amount * (units / other)
@JvmName("div4" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.div(other: UnitsProduct<C, A>): Measure<UnitsRatio<B, C>> = amount * (units / other)
@JvmName("div5" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.div(other: UnitsProduct<B, C>): Measure<UnitsRatio<A, C>> = amount * (units / other)
@JvmName("div6" ) operator fun <A: Units, B: Units, C: Units> Measure<UnitsProduct<A, B>>.div(other: UnitsProduct<A, C>): Measure<UnitsRatio<B, C>> = amount * (units / other)
@JvmName("div7" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.div(other: UnitsProduct<A, A>): Measure<UnitsRatio<B, A>> = amount * (units / other)
@JvmName("div8" ) operator fun <A: Units, B: Units> Measure<UnitsProduct<A, B>>.div(other: UnitsProduct<B, B>): Measure<UnitsRatio<A, B>> = amount * (units / other)
@JvmName("div9" ) operator fun <A: Units, B: Units> Measure<UnitsRatio<A, B>>. div(other: B ): Measure<UnitsRatio<A, UnitsProduct<B, B>>> = amount * (units / other)
@JvmName("div10") operator fun <A: Units, B: Units, C: Units, D: Units> Measure<UnitsRatio<A, B>>. div(other: UnitsRatio<C, D> ): Measure<UnitsRatio<UnitsProduct<A, D>, UnitsProduct<B, C>>> = amount * (units / other)
@JvmName("div11") operator fun <A: Units, B: Units> Measure<UnitsRatio<A, B>>. div(other: UnitsRatio<A, Square<B>>): Measure<B> = amount * (units / other)
@JvmName("div12") operator fun <A: Units, B: Units> Measure<UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, B>>>.div(other: A ): Measure<UnitsRatio<A, UnitsProduct<B, B>>> = amount * (units / other)
@JvmName("div13") operator fun <A: Units, B: Units, C: Units> Measure<UnitsRatio<UnitsProduct<A, A>, UnitsProduct<B, C>>>.div(other: A ): Measure<UnitsRatio<A, UnitsProduct<B, C>>> = amount * (units / other)
@JvmName("div14") operator fun <A: Units, B: Units, C: Units, D: Units> Measure<UnitsRatio<UnitsProduct<A, B>, UnitsProduct<C, D>>>.div(other: A ): Measure<UnitsRatio<B, UnitsProduct<C, D>>> = amount * (units / other)
@JvmName("div15") operator fun <A: Units, B: Units> Measure<A>. div(other: UnitsRatio<A, B> ): Measure<B> = amount * (units / other)
// endregion
// region ================ Number - Measure Math =========================
private infix fun <T: Units> Number.into(unit: T): Measure<T> = Measure(this.toDouble(), unit)
operator fun <T: Units> Number.times(unit: T): Measure<T> = this into unit
operator fun <T: Units> Number.div (unit: T): Measure<InverseUnits<T>> = this into InverseUnits(unit)
operator fun <T: Units> Number.times(measure: Measure<T>): Measure<T> = measure * this
@JvmName("divMeasure" ) operator fun <T: Units> Number.div (measure: Measure<T>): Measure<InverseUnits<T>> = this.toDouble() / measure.amount * InverseUnits(measure.units)
@JvmName("divInvMeasure") operator fun <T: Units> Number.div (measure: Measure<InverseUnits<T>>): Measure<T> = this * measure.units.unit / measure.amount
operator fun <T: Units> T.times (value: Number): Measure<T> = value into this
operator fun <T: Units> T.invoke(value: Number): Measure<T> = value into this
// endregion
// region ================ Measure Math ==================================
/**
* @return the absolute value of [measure], retaining its units.
* @see absoluteValue extension property for [Measure]
*/
fun <T: Units> abs(measure: Measure<T>) = kotlin.math.abs (measure.amount) * measure.units
/**
* Rounds the [measure] to the closest integer, retaining its units.
*/
fun <T: Units> round(measure: Measure<T>) = kotlin.math.round(measure.amount) * measure.units
/**
* Rounds the [measure] to the next, larger integer, retaining its units.
*/
fun <T: Units> ceil(measure: Measure<T>) = kotlin.math.ceil (measure.amount) * measure.units
/**
* Rounds the [measure] to the previous, smaller integer, retaining its units.
*/
fun <T: Units> floor(measure: Measure<T>) = kotlin.math.floor(measure.amount) * measure.units
/**
* Returns a [Measure] that is rounded to he closest multiple of [toNearest], and has the
* the units of [toNearest].
*
* ```
*
* val length = 25 * inches
*
* round(length, toNearest = 1 * feet ) // 2.0 feet
* round(length, toNearest = 0.1 * meters) // 0.6 m
* ```
*
* @see toNearest extension property of [Measure]
*/
fun <T: Units> round(measure: Measure<T>, toNearest: Measure<T>): Measure<T> = when (toNearest.amount) {
0.0 -> measure
else -> kotlin.math.round(measure / toNearest) * toNearest
}
/**
* Returns a [Measure] that is rounded to he closest multiple of [toNearest], and has the
* the units of [toNearest].
*
* ```
*
* val length = 25 * inches
*
* length toNearest 1 * feet // 2.0 feet
* length toNearest 0.1 * meters // 0.6 m
* ```
*/
infix fun <T: Units> Measure<T>.toNearest(value: Measure<T>): Measure<T> = round(this, toNearest = value)
/**
* @return the absolute value of this measure, retaining its units.
*/
inline val <T: Units> Measure<T>.absoluteValue: Measure<T> get() = abs(this)
/**
* @return the sign of this value:
* - `-1.0` when it is negative
* - `0.0` when it is zero
* - `1.0` when it is positive
*/
val <T: Units> Measure<T>.sign: Double get() = kotlin.math.sign(amount)
// endregion
// region ================ Units Aliases =================================
typealias Velocity = UnitsRatio<Length, Time>
typealias Acceleration = UnitsRatio<Length, Square<Time>>
// endregion | 1 | Kotlin | 3 | 108 | 9341443ee423e64a6b78006935b5394c7b2f7756 | 33,985 | measured | MIT License |
Retos/Reto #45 - EL CALENDARIO DE ADEVIENTO 2023 [Fácil]/kotlin/codigo-alan.kt | mouredev | 581,049,695 | false | {"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | package retos2023
import java.util.*
/*
* ¿Conoces el calendario de aDEViento de la comunidad (https://adviento.dev)?
* 24 días, 24 regalos sorpresa relacionados con desarrollo de software.
* Desde el 1 al 24 de diciembre.
*
* Crea un programa que simule el mecanismo de participación:
* - Mediante la terminal, el programa te preguntará si quieres añadir y borrar
* participantes, mostrarlos, lanzar el sorteo o salir.
* - Si seleccionas añadir un participante, podrás escribir su nombre y pulsar enter.
* - Si seleccionas añadir un participante, y este ya existe, avisarás de ello.
* (Y no lo duplicarás)
* - Si seleccionas mostrar los participantes, se listarán todos.
* - Si seleccionas eliminar un participante, podrás escribir su nombre y pulsar enter.
* (Avisando de si lo has eliminado o el nombre no existe)
* - Si seleccionas realizar el sorteo, elegirás una persona al azar
* y se eliminará del listado.
* - Si seleccionas salir, el programa finalizará.
*/
fun main(){
val competitors = mutableListOf<String>()
val scanner = Scanner(System.`in`)
boardOptions()
var userInput = scanner.nextLine().lowercase()
while ((userInput != "5") && (userInput != "Salir".lowercase())){
when(userInput){
"1", "Agregar participante".lowercase() -> {
val competitorName = competitorNameInput(scanner)
if (!competitors.contains(competitorName)) competitors.add(competitorName)
else println("El participante ya existe.")
}
"2", "Borrar participante".lowercase() -> {
val competitorName = competitorNameInput(scanner)
if (competitors.contains(competitorName)) competitors.remove(competitorName)
else println("El participante no existe.")
}
"3", "Mostrar todos los participantes".lowercase() -> showAllCompetitors(competitors)
"4", "Lanzar sorteo".lowercase() -> {
if (competitors.isNotEmpty()) {
val randomlySelectCompetitor = launchLottery(competitors)
println("Ha salido sorteado $randomlySelectCompetitor")
competitors.remove(randomlySelectCompetitor)
} else println("La lista de participantes está vacía")
}
else -> println("Opción incorrecta. Ingrésela otra vez.")
}
boardOptions()
userInput = scanner.nextLine().lowercase()
}
println("Hasta pronto!")
}
private fun launchLottery(competitors: List<String>) = competitors.random()
private fun showAllCompetitors(competitors: List<String>) = competitors.forEach { println(it) }
private fun competitorNameInput(scanner: Scanner): String {
println("Ingrese nombre: ")
return scanner.nextLine()
}
private fun boardOptions() {
println("Seleccione una opción:\n" +
"1-Agregar participante\n" +
"2-Borrar participante\n" +
"3-Mostrar todos los participantes\n" +
"4-Lanzar sorteo\n" +
"5-Salir\n")
}
| 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 3,110 | retos-programacion-2023 | Apache License 2.0 |
LeetCode/Easy/maximum-depth-of-binary-tree/Solution.kt | GregoryHo | 254,657,102 | false | null | import java.util.*
class Solution {
fun maxDepth(root: TreeNode?): Int {
// return bfs(root)
return dfs(root)
}
// time complexity O(N)
// space complexity O(N/2)
private fun bfs(root: TreeNode?): Int {
if (root == null) {
return 0
}
var depth = 0
val stack = Stack<TreeNode>()
val depths = Stack<Int>()
stack.add(root)
depths.add(1)
while (!stack.isEmpty()) {
val currentNode = stack.pop()
val currentDepth = depths.pop()
if (currentNode.left != null) {
depths.add(currentDepth + 1)
stack.add(currentNode.left!!)
}
if (currentNode.right != null) {
depths.add(currentDepth + 1)
stack.add(currentNode.right!!)
}
depth = Math.max(depth, currentDepth)
}
return depth
}
// time complexity O(N)
// space complexity O(N)
private fun dfs(root: TreeNode?): Int {
return root?.run {
Math.max(dfs(root.left), dfs(root.right)) + 1
} ?: 0
}
}
class TreeNode(var value: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun main(args: Array<String>) {
val solution = Solution()
val node = TreeNode(3).apply {
left = TreeNode(9)
right = TreeNode(20).apply {
left = TreeNode(15)
right = TreeNode(7)
}
}
println(solution.maxDepth(node))
}
| 0 | Kotlin | 0 | 0 | 8f126ffdf75aa83a6d60689e0b6fcc966a173c70 | 1,348 | coding-fun | MIT License |
src/day13/fr/Day13_1-2.kt | BrunoKrantzy | 433,844,189 | false | {"Kotlin": 63580} | package day13.fr
import java.io.File
private fun readChars(): CharArray = readLn().toCharArray()
private fun readLn() = readLine()!! // string line
private fun readSb() = StringBuilder(readLn())
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single long
private fun readDouble() = readLn().toDouble() // single double
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints
private fun readLongs() = readStrings().map { it.toLong() } // list of longs
private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles
private fun readIntArray() = readStrings().map { it.toInt() }.toIntArray() // Array of ints
private fun readLongArray() = readStrings().map { it.toLong() }.toLongArray() // Array of longs
fun readInput(name: String) = File("src", "$name.txt").readLines()
fun main() {
var rep = 0L
//val vInGrille = day11.fr.readInput("test13a")
//val vInFold = day11.fr.readInput("test13b")
val vInGrille = day11.fr.readInput("input13a")
val vInFold = day11.fr.readInput("input13b")
var maxX = 0
var maxY = 0
var regex = "^(\\d+),(\\d+)".toRegex()
vInGrille.forEach {
val match = regex.find(it)
val x = match!!.groups[1]!!.value.toInt()
val y = match.groups[2]!!.value.toInt()
maxX = maxOf(maxX, x)
maxY = maxOf(maxY, y)
}
var tabTrans = Array (maxY + 1) { Array(maxX + 1) { '.' } }
vInGrille.forEach {
val match = regex.find(it)
val x = match!!.groups[1]!!.value.toInt()
val y = match.groups[2]!!.value.toInt()
tabTrans[y][x] = '#'
}
var nLarg = maxX
var nHaut = maxY
for (f in 0 until vInFold.size) {
var sFold = vInFold[f]
regex = "^[a-z]+\\s[a-z]+\\s([xy])=(\\d+)".toRegex()
val match = regex.find(sFold)
val xy = match!!.groups[1]!!.value
val vXY = match.groups[2]!!.value.toInt()
if (xy == "y") { // pli hauteur
var dif = (nHaut - vXY) * 2
var difSize = dif / 2
for (i in nHaut downTo vXY) {
for (j in 0 .. nLarg) {
if (tabTrans[i][j] != '.') {
tabTrans[i-dif][j] = tabTrans[i][j]
}
}
dif -= 2
}
nHaut = nHaut - (difSize + 1)
}
else { // pli largeur
for (i in 0 .. nHaut) {
var dif = ((nLarg - vXY) * 2)
for (j in nLarg downTo vXY) {
if (tabTrans[i][j-dif] != '#') {
tabTrans[i][j-dif] = tabTrans[i][j]
}
dif -= 2
}
}
nLarg = (nLarg - vXY) - 1
}
}
for (i in 0 .. nHaut) {
for (j in 0 .. nLarg) {
if (tabTrans[i][j] == '#') {
rep++
}
print(tabTrans[i][j])
}
print("\n")
}
println(rep)
}
| 0 | Kotlin | 0 | 0 | 0d460afc81fddb9875e6634ee08165e63c76cf3a | 3,111 | Advent-of-Code-2021 | Apache License 2.0 |
src/main/kotlin/dayFive/DayFive.kt | janreppien | 573,041,132 | false | {"Kotlin": 26432} | package dayFive
import AocSolution
import java.io.File
import java.util.Stack
class DayFive : AocSolution(5) {
private val file = File("src/main/resources/inputs/dayFive/input.txt")
private var stacks1 = readStacks()
private var stacks2 = readStacks()
private val instructions = readInstructions()
private fun readStacks(): MutableList<Stack<Char>> {
var blankLine = 0
for ((num, line) in file.readLines().withIndex()) {
if (line.isEmpty()) {
blankLine = num - 1
}
}
val stackNumbers = file.readLines()[blankLine].split(' ').filter { it != "" }
.map { Pair(it.toInt(), file.readLines()[blankLine].indexOf(it)) }
val stacks = mutableListOf<Stack<Char>>()
for (i in stackNumbers.indices) {
stacks.add(Stack())
}
for (i in blankLine downTo 0) {
stackNumbers.forEach {
if (file.readLines()[i].length > it.second && file.readLines()[i][it.second] != ' ') {
stacks[it.first - 1].push(file.readLines()[i][it.second])
}
}
}
return stacks
}
private fun readInstructions(): MutableList<Instruction> {
var blankLine = 0
for ((num, line) in file.readLines().withIndex()) {
if (line.isEmpty()) {
blankLine = num - 1
}
}
return file.readLines().subList(blankLine + 1, file.readLines().size).map {
it.replace("move", "").replace("from", "").replace("to", "").split(" ").filter { it.isNotBlank() }
.map { it.toInt() }
}.filter { it.isNotEmpty() }.map { Instruction(it[0], it[1]-1, it[2]-1) }.toMutableList()
}
override fun solvePartOne(): String {
instructions.forEach {
for(i in 0 until it.amount) {
stacks1[it.to].push(stacks1[it.from].pop())
}
}
var output = ""
stacks1.forEach { output+= it.peek() }
return output
}
override fun solvePartTwo(): String {
val buffer = Stack<Char>()
instructions.forEach {
for(i in 0 until it.amount) {
buffer.push(stacks2[it.from].pop())
}
for(i in 0 until buffer.size) {
stacks2[it.to].push(buffer.pop())
}
}
var output = ""
stacks2.forEach { output+= it.peek() }
return output
}
} | 0 | Kotlin | 0 | 0 | b53f6c253966536a3edc8897d1420a5ceed59aa9 | 2,499 | aoc2022 | MIT License |
src/main/kotlin/com/github/wtfjoke/day3/Day3Part2.kts | WtfJoke | 434,008,687 | false | {"Kotlin": 80582} | import java.nio.file.Paths
val inputs = Paths.get("inputs.txt").toFile()
.useLines { it.toList() }
val bitLength = inputs.first().length
fun determineOxygen(): Int {
var oxygens = inputs
for (i in 0 until bitLength) {
val oxygensCount = oxygens
.groupingBy { it[i] }
.eachCount()
val maxEntries = oxygensCount.filterValues { it == oxygensCount.values.maxOrNull() }
val bitCriteria = if (maxEntries.size > 1) '1' else maxEntries.keys.first()
oxygens = oxygens.filter { bit ->
bit[i] == bitCriteria
}
}
return oxygens.first().toInt(2)
}
fun determineCo2(): Int {
var co2 = inputs
for (i in 0 until bitLength) {
val co2Count = co2
.groupingBy { it[i] }
.eachCount()
val minEntries = co2Count.filterValues { it == co2Count.values.minOrNull() }
val bitCriteria = if (minEntries.size > 1) '0' else minEntries.keys.first()
co2 = co2.filter { bit ->
bit[i] == bitCriteria
}
}
return co2.first().toInt(2)
}
determineOxygen() * determineCo2()
| 1 | Kotlin | 0 | 0 | 9185b9ddf3892be24838139fcfc849d3cb6e89b4 | 1,131 | adventofcode-21 | MIT License |
src/main/kotlin/org/olafneumann/regex/generator/diff/Diff.kt | noxone | 239,624,807 | false | {"Kotlin": 246877, "HTML": 22083, "CSS": 5034, "C": 2817, "Dockerfile": 1748, "JavaScript": 220} | package org.olafneumann.regex.generator.diff
//import dev.andrewbailey.diff.DiffOperation
//import dev.andrewbailey.diff.differenceOf
import io.github.petertrr.diffutils.diff
import io.github.petertrr.diffutils.patch.Delta
import io.github.petertrr.diffutils.patch.DeltaType
import org.olafneumann.regex.generator.RegexGeneratorException
import org.olafneumann.regex.generator.utils.add
import org.olafneumann.regex.generator.utils.addPosition
import org.olafneumann.regex.generator.utils.remove
import org.olafneumann.regex.generator.utils.toIndexedString
internal fun <T> findDifferences(input1: List<T>, input2: List<T>): List<Difference> =
findDifferencesPeterTrr(input1, input2)
/*{
val p1 = findDifferencesAndrewbailey(input1, input2)
val p2 = findDifferencesPeterTrr(input1, input2)
console.log(p1.toIndexedString("Andrewbailey"))
console.log(p2.toIndexedString("PeterTrr"))
return p2
}*/
/*private fun <T> findDifferencesAndrewbailey(input1: List<T>, input2: List<T>): List<Difference> =
differenceOf(original = input1, updated = input2, detectMoves = false)
.operations
.map { it.toDifference() }
private fun <T> DiffOperation<T>.toDifference(): Difference = when (this) {
is DiffOperation.Add -> Difference(Difference.Type.Add, index..index)
is DiffOperation.AddAll -> Difference(Difference.Type.Add, index until index + items.size)
is DiffOperation.Remove -> Difference(Difference.Type.Remove, index..index)
is DiffOperation.RemoveRange -> Difference(Difference.Type.Remove, startIndex until endIndex)
else -> throw RegexGeneratorException("Invalid diff operation: $this")
}*/
private fun <T> findDifferencesPeterTrr(input1: List<T>, input2: List<T>): List<Difference> =
diff(original = input1, revised = input2)
.deltas
.flatMap { it.toDifference() }
private fun <T> Delta<T>.toDifference(): List<Difference> {
return when (type) {
DeltaType.INSERT -> listOf(Difference(Difference.Type.Add, target.position..target.last()))
DeltaType.DELETE -> listOf(Difference(Difference.Type.Remove, source.position..source.last()))
DeltaType.CHANGE -> listOf(
Difference(Difference.Type.Remove, source.position..source.last()),
Difference(Difference.Type.Add, target.position..target.last())
)
else -> throw RegexGeneratorException("Invalid delta type: $this")
}
}
internal data class Difference(
val type: Type,
val range: IntRange,
) {
val action: RangeAction
get() = when (type) {
Type.Add -> RangeAction(add, range)
Type.Remove -> RangeAction(remove, range)
}
internal fun move(index: Int) = ModifiedDifference(type, range).move(index)
enum class Type {
Add, Remove
}
companion object {
private val add: (IntRange, IntRange) -> List<IntRange> = { a, b -> a.add(b) }
private val remove: (IntRange, IntRange) -> List<IntRange> = { a, b -> a.remove(b) }
}
}
internal data class RangeAction(
val action: (IntRange, IntRange) -> List<IntRange>,
val range: IntRange
) {
fun applyTo(range: IntRange): List<IntRange> = action(range, this.range)
}
internal data class ModifiedDifference(
val type: Difference.Type,
val range: IntRange,
) {
fun move(index: Int) = ModifiedDifference(type, range.addPosition(index))
}
| 13 | Kotlin | 69 | 355 | 001cc69d2592afa70b492441e119753789494816 | 3,401 | regex-generator | MIT License |
src/main/kotlin/leetcode/problem0047/Permutations2.kt | ayukatawago | 456,312,186 | false | {"Kotlin": 266300, "Python": 1842} | package leetcode.problem0047
class Permutations2 {
fun permuteUnique(nums: IntArray): List<List<Int>> {
val hashMap = hashMapOf<Int, Int>()
nums.forEach {
hashMap[it] = if (hashMap.containsKey(it)) {
requireNotNull(hashMap[it]) + 1
} else {
1
}
}
return permute(hashMap)
}
private fun permute(hashMap: HashMap<Int, Int>): List<List<Int>> =
if (hashMap.values.filter { it > 0 }.size == 1) {
val tmp = hashMap.filterValues { it > 0 }
listOf(IntArray(tmp.values.first()) { tmp.keys.first() }.toList())
} else {
hashMap.flatMap { (key, value) ->
if (value == 0) {
return@flatMap emptyList<List<Int>>()
}
hashMap[key] = value - 1
try {
permute(hashMap).map {
val tmpList = mutableListOf<Int>()
tmpList.add(key)
tmpList.addAll(it)
tmpList
}
} finally {
hashMap[key] = value
}
}
}
}
| 0 | Kotlin | 0 | 0 | f9602f2560a6c9102728ccbc5c1ff8fa421341b8 | 1,235 | leetcode-kotlin | MIT License |
Algorithm/coding_interviews/Kotlin/Questions39.kt | ck76 | 314,136,865 | false | {"HTML": 1420929, "Java": 723214, "JavaScript": 534260, "Python": 437495, "CSS": 348978, "C++": 348274, "Swift": 325819, "Go": 310456, "Less": 203040, "Rust": 105712, "Ruby": 96050, "Kotlin": 88868, "PHP": 67753, "Lua": 52032, "C": 30808, "TypeScript": 23395, "C#": 4973, "Elixir": 4945, "Pug": 1853, "PowerShell": 471, "Shell": 163} | package com.qiaoyuang.algorithm
/**
* 找出一个数组中出现次数超过数组长度一般的数字
*/
fun main() {
try {
val arg0 = intArrayOf(1, 2, 3, 2, 2, 2, 5, 4, 2)
val arg1 = intArrayOf(1, 2, 3, 2, 2, 2, 5, 4)
val message = "超过数组长度一半的数为:"
println("$message${arg0.moreThanHalfNum2()}")
println("$message${arg1.moreThanHalfNum2()}")
println("$message${arg0.moreThanHalfNum1()}")
println("$message${arg1.moreThanHalfNum1()}")
} catch (e: RuntimeException) {
e.printStackTrace()
}
}
/**
* 解法一,需要修改输入数组,时间复杂度为O(n)
* 此方法较为受限,首先必须明确知道数组中一定有数量超过长度一半的数字。
* 如果没有也不能发现这种情况,且会返回一个错误的值,即数组排序后的中位数,
* 因此总体来说,解法二更为优秀。
*/
fun IntArray.moreThanHalfNum1(): Int {
val mid = this.size / 2
var index = partition(0, this.size - 1)
while (index != mid) {
if (index > mid) {
index = partition(0, index - 1)
} else {
index = partition(index + 1, this.size - 1)
}
}
return this[mid]
}
//解法二,无需修改输入数组,时间复杂度为O(n)
fun IntArray.moreThanHalfNum2(): Int {
var index = 0
var number = this[index]
var count = 0
this.forEach {
if (it == number) {
count++
} else {
--count
if (count == 0) {
number = this[++index]
count = 1
}
}
}
require(count > 1) { "数组中没有长度超过一般的数字" }
return number
} | 0 | HTML | 0 | 2 | 2a989fe85941f27b9dd85b3958514371c8ace13b | 1,554 | awesome-cs | Apache License 2.0 |
kotlin/udemy_course/src/main/kotlin/geek_for_geeks/GeekForGeeks.kt | pradyotprksh | 385,586,594 | false | {"Kotlin": 1973871, "Dart": 1066884, "Python": 313491, "Swift": 147167, "C++": 113494, "CMake": 94132, "Go": 45704, "HTML": 21089, "Ruby": 12424, "Rust": 8550, "C": 7125, "Makefile": 1480, "Shell": 817, "JavaScript": 781, "CSS": 588, "Objective-C": 380, "Dockerfile": 32} | package geek_for_geeks
import data_structures.trees.BinarySearchTree
import data_structures.trees.MaxBinaryHeap
import data_structures.trees.TreeNode
class GeekForGeeks {
fun startGeekForGeeks() {
println("Starting problems from GeekForGeeks [https://practice.geeksforgeeks.org/explore?page=1]")
println(palinArray(a = listOf(121, 131, 20)))
println(palinArray(a = listOf(111, 222, 333, 444, 555)))
printAl(a = listOf(1, 2, 3, 4))
printAl(a = listOf(1, 2, 3, 4, 5))
println()
println(sumElement(a = listOf(3, 2, 1)))
println(sumElement(a = listOf(1, 2, 3, 4)))
println(isPerfect(a = listOf(1, 2, 3, 2, 1)))
println(isPerfect(a = listOf(1, 2, 3, 4, 5)))
println(isPerfect(a = listOf(1, 2, 3, 4)))
println(isPerfect(a = listOf(1, 2, 2, 1)))
println(isPerfect(a = listOf(1, 2, 1, 1)))
println(findIndex(a = listOf(1, 2, 3, 4, 5, 5), k = 5))
println(findIndex(a = listOf(6, 5, 4, 3, 1, 2), k = 4))
println(findIndex(a = listOf(6, 5, 4, 3, 1, 2), k = 8))
println(seriesSum(1))
println(seriesSum(5))
println(findElements(a = listOf(2, 8, 7, 1, 5)))
println(findElements(a = listOf(7, -2, 3, 4, 9, -1)))
println(fascinating(192))
println(fascinating(853))
println(valueEqualToIndex(a = listOf(15, 2, 45, 12, 7)))
println(valueEqualToIndex(a = listOf(1)))
println(valueEqualToIndex(a = listOf(1, 2, 3, 4, 6)))
println(scores(a = listOf(4, 2, 7), b = listOf(5, 6, 3)))
println(scores(a = listOf(4, 2, 7), b = listOf(5, 2, 8)))
println(swapKth(a = listOf(1, 2, 3, 4, 5, 6, 7, 8), k = 3))
println(swapKth(a = listOf(5, 3, 6, 1, 2), k = 2))
println(print2largest(a = listOf(12, 35, 1, 10, 34, 1)))
println(print2largest(a = listOf(10, 5, 10)))
println(getMoreAndLess(a = listOf(1, 2, 8, 10, 11, 12, 19), x = 0))
println(getMoreAndLess(a = listOf(1, 2, 8, 10, 11, 12, 19), x = 5))
println(streamAvg(a = listOf(10, 20, 30, 40, 50)))
println(streamAvg(a = listOf(12, 2)))
println(leftElement(a = listOf(7, 8, 3, 4, 2, 9, 5)))
println(leftElement(a = listOf(8, 1, 2, 9, 4, 3, 7, 5)))
println(longest(a = listOf("Geek", "Geeks", "Geeksfor", "GeeksforGeek", "GeeksforGeeks")))
println(getSum(a = listOf(1, 2, 3, 4)))
println(getSum(a = listOf(5, 8, 3, 10, 22, 45)))
println(transpose(a = listOf(listOf(1, 2, 3), listOf(4, 5, 6), listOf(7, 8, 9))))
println(transpose(a = listOf(listOf(1, 2), listOf(1, 2))))
preorderExampleOne()
heapHeight()
getHeight()
removeLoopExampleOne()
removeLoopExampleTwo()
removeLoopExampleThree()
detectLoopExampleOne()
getNthFromLastExampleOne()
getNthFromLastExampleTwo()
pattern1()
pattern2()
pattern3()
pattern4()
println(matrixDiagonal(arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9))))
println(matrixDiagonal(arrayOf(intArrayOf(1, 2, 3, 4), intArrayOf(5, 6, 7, 8), intArrayOf(9, 10, 11, 12))))
}
private fun matrixDiagonal(matrix: Array<IntArray>) {
for (k in matrix.indices) {
var i = k
var j = 0
while (i >= 0) {
print("${matrix[i][j]} ")
--i
++j
}
}
for (k in 1 until matrix.first().size) {
var i = k
var j = matrix.size - 1
while (i < matrix.first().size) {
print("${matrix[j][i]} ")
++i
--j
}
}
}
private fun pattern4(n: Int = 5) {
for (row in 1 until 2 * n) {
val totalCol = if (row > n) 2 * n - row else row
for (space in 1..n - totalCol) {
print(" ")
}
for (col in 1..totalCol) {
print("* ")
}
println()
}
}
private fun pattern3(n: Int = 5) {
for (row in 1 until 2 * n) {
val totalCol = if (row > n) 2 * n - row else row
for (col in 1..totalCol) {
print("* ")
}
println()
}
}
private fun pattern2(n: Int = 5) {
for (row in 1..n) {
for (col in 1..row) {
print("$col ")
}
println()
}
}
private fun pattern1(n: Int = 5) {
for (row in 1..n) {
for (col in row..n) {
print("* ")
}
println()
}
}
private fun getNthFromLastExampleTwo() {
val one = data_structures.linked_lists.ListNode(data = 1)
val two = data_structures.linked_lists.ListNode(data = 2)
val three = data_structures.linked_lists.ListNode(data = 3)
val four = data_structures.linked_lists.ListNode(data = 4)
one.next = two
two.next = three
three.next = four
println(one)
println(getNthFromLast(head = one, n = 5))
}
private fun getNthFromLastExampleOne() {
val one = data_structures.linked_lists.ListNode(data = 1)
val two = data_structures.linked_lists.ListNode(data = 2)
val three = data_structures.linked_lists.ListNode(data = 3)
val four = data_structures.linked_lists.ListNode(data = 4)
val five = data_structures.linked_lists.ListNode(data = 5)
val six = data_structures.linked_lists.ListNode(data = 6)
val seven = data_structures.linked_lists.ListNode(data = 7)
val eight = data_structures.linked_lists.ListNode(data = 8)
val nine = data_structures.linked_lists.ListNode(data = 9)
one.next = two
two.next = three
three.next = four
four.next = five
five.next = six
six.next = seven
seven.next = eight
eight.next = nine
println(one)
println(getNthFromLast(head = one, n = 2))
}
private fun getNthFromLast(head: data_structures.linked_lists.ListNode?, n: Int): Int {
var size = 0
var temp = head
while (temp != null) {
++size
temp = temp.next
}
if (n <= size) {
temp = head
while (size != n) {
--size
temp = temp?.next
}
return temp?.data ?: -1
}
return -1
}
private fun detectLoopExampleOne() {
val one = data_structures.linked_lists.ListNode(data = 1)
val two = data_structures.linked_lists.ListNode(data = 2)
val three = data_structures.linked_lists.ListNode(data = 3)
val four = data_structures.linked_lists.ListNode(data = 4)
one.next = two
two.next = three
three.next = four
four.next = two
detectLoop(listNode = one)
}
private fun detectLoop(listNode: data_structures.linked_lists.ListNode?) {
var slow = listNode
var fast = listNode?.next?.next
while (fast != null && slow != null) {
if (fast == slow) {
println("Loop Found")
break
}
fast = fast.next?.next
slow = slow.next
}
}
private fun removeLoopExampleThree() {
val one = data_structures.linked_lists.ListNode(data = 1)
val two = data_structures.linked_lists.ListNode(data = 2)
val three = data_structures.linked_lists.ListNode(data = 3)
val four = data_structures.linked_lists.ListNode(data = 4)
one.next = two
two.next = three
three.next = four
four.next = two
removeLoop(listNode = one)
println(one)
}
private fun removeLoopExampleTwo() {
val one = data_structures.linked_lists.ListNode(data = 1)
val eight = data_structures.linked_lists.ListNode(data = 8)
val three = data_structures.linked_lists.ListNode(data = 3)
val four = data_structures.linked_lists.ListNode(data = 4)
one.next = eight
eight.next = three
three.next = four
removeLoop(listNode = one)
}
private fun removeLoopExampleOne() {
val one = data_structures.linked_lists.ListNode(data = 1)
val three = data_structures.linked_lists.ListNode(data = 3)
val four = data_structures.linked_lists.ListNode(data = 4)
one.next = three
three.next = four
four.next = three
removeLoop(listNode = one)
println(one)
}
private fun removeLoop(listNode: data_structures.linked_lists.ListNode?) {
var slow = listNode
var fast = listNode?.next?.next
while (fast != null && slow != null) {
if (fast.next == slow || slow.next == fast) {
break
}
fast = fast.next?.next
slow = slow.next
}
if (fast != null && slow != null) {
if (fast.next == slow) {
println("Loop Found ${fast.data}->${slow.data}")
fast.next = null
} else if (slow.next == fast) {
println("Loop Found ${slow.data}->${fast.data}")
slow.next = null
}
} else {
println("No Loop Was Found")
}
}
private fun getHeight() {
val binarySearchTree = BinarySearchTree()
binarySearchTree.insert(1)
binarySearchTree.insert(10)
binarySearchTree.insert(39)
binarySearchTree.insert(5)
println(binarySearchTree.getSize())
}
private fun preorderExampleOne() {
val node = TreeNode(data = 1)
node.left = TreeNode(data = 4)
node.left?.left = TreeNode(data = 4)
node.left?.right = TreeNode(data = 2)
preorder(node)
println()
}
private fun heapHeight() {
val maxBinaryHeap1 = MaxBinaryHeap()
maxBinaryHeap1.insert(1)
maxBinaryHeap1.insert(3)
maxBinaryHeap1.insert(6)
maxBinaryHeap1.insert(5)
maxBinaryHeap1.insert(9)
maxBinaryHeap1.insert(8)
maxBinaryHeap1.print()
println(maxBinaryHeap1.height())
val maxBinaryHeap2 = MaxBinaryHeap()
maxBinaryHeap2.insert(3)
maxBinaryHeap2.insert(6)
maxBinaryHeap2.insert(9)
maxBinaryHeap2.insert(2)
maxBinaryHeap2.insert(15)
maxBinaryHeap2.insert(10)
maxBinaryHeap2.insert(14)
maxBinaryHeap2.insert(5)
maxBinaryHeap2.insert(12)
maxBinaryHeap2.print()
println(maxBinaryHeap2.height())
}
private fun preorder(root: TreeNode?) {
if (root == null) return
print("${root.data} ")
preorder(root.left)
preorder(root.right)
}
private fun transpose(a: List<List<Int>>): List<List<Int>> {
val temp = ArrayList<ArrayList<Int>>()
for (i in a.indices) {
val row = ArrayList<Int>()
for (j in a[i].indices) {
row.add(a[j][i])
}
temp.add(row)
}
return temp
}
private fun getSum(a: List<Int>): Int {
var sum = 0
for (num in a) {
sum += num
}
return sum
}
private fun longest(a: List<String>): String {
var longestString = ""
for (str in a) {
if (str.length > longestString.length) {
longestString = str
}
}
return longestString
}
private fun leftElement(a: List<Int>): Int {
val temp = ArrayList(a)
var removeMax = true
while (temp.size > 1) {
var num = if (removeMax) Int.MIN_VALUE else Int.MAX_VALUE
var numIndex = -1
for ((i, item) in temp.withIndex()) {
if (removeMax) {
if (item > num) {
num = item
numIndex = i
}
} else {
if (item < num) {
num = item
numIndex = i
}
}
}
temp.removeAt(numIndex)
removeMax = !removeMax
}
return temp.first()
}
private fun streamAvg(a: List<Int>): List<Int> {
val avg = ArrayList<Int>()
var sum = 0
for ((i, num) in a.withIndex()) {
sum += num
avg.add(sum / (i + 1))
}
return avg
}
private fun getMoreAndLess(a: List<Int>, x: Int): List<Int> {
var lessNum = 0
var moreNum = 0
for (num in a) {
if (num <= x) {
++lessNum
}
if (num >= x) {
++moreNum
}
}
return listOf(lessNum, moreNum)
}
private fun print2largest(a: List<Int>): Int {
if (a.size == 1) {
return -1
}
var largestNum = a[0]
var secondLargestNum = -1
for (num in a) {
if (num > largestNum) {
secondLargestNum = largestNum
largestNum = num
} else if (num > secondLargestNum && num != largestNum) {
secondLargestNum = num
}
}
return secondLargestNum
}
private fun swapKth(a: List<Int>, k: Int): List<Int> {
val swapList = ArrayList<Int>(a)
val temp = swapList[k - 1]
swapList[k - 1] = swapList[swapList.size - k]
swapList[swapList.size - k] = temp
return swapList
}
private fun scores(a: List<Int>, b: List<Int>): List<Int> {
var firstScore = 0
var secondScore = 0
for (i in a.indices) {
if (a[i] > b[i]) {
++firstScore
} else if (a[i] < b[i]) {
++secondScore
}
}
return listOf(firstScore, secondScore)
}
private fun valueEqualToIndex(a: List<Int>): List<Int> {
val elements = ArrayList<Int>()
for ((index, value) in a.withIndex()) {
if (value == index + 1) {
elements.add(value)
}
}
return elements
}
private fun fascinating(a: Int): Boolean {
if (a.toString().length < 3) {
return false
} else {
val num1 = a * 2
val num2 = a * 3
val finalNum = "$a$num1$num2"
for (i in 1..9) {
if (!finalNum.contains(i.toString())) {
return false
}
}
}
return true
}
private fun findElements(a: List<Int>): List<Int> {
val sorted = a.sorted()
return sorted.subList(0, sorted.size - 2)
}
private fun seriesSum(n: Int): Int {
var sum = 0
for (i in 1..n) {
sum += i
}
return sum
}
private fun findIndex(a: List<Int>, k: Int): Any {
var start = -1
var end = -1
for (i in a.indices) {
if (a[i] == k && start == -1) {
start = i
}
if (a[a.size - 1 - i] == k && end == -1) {
end = a.size - 1 - i
}
}
if (start == -1 && end == -1) {
return -1
}
return listOf(start, end)
}
private fun isPerfect(a: List<Int>): Boolean {
for (i in 0 until a.size / 2) {
if (a[i] != a[a.size - 1 - i]) {
return false
}
}
return true
}
private fun sumElement(a: List<Int>): Int {
var sum = 0
for (i in a.indices) {
sum += a[i]
}
return sum
}
private fun printAl(a: List<Int>) {
for (i in a.indices) {
if (i % 2 != 0) continue
print(a[i])
}
}
private fun palinArray(a: List<Int>): Int {
for (num in a) {
if (!isPalindrome(num.toString())) {
return 0
}
}
return 1
}
private fun isPalindrome(data: String): Boolean {
for (i in data.indices) {
if (data[i] != data[data.length - 1 - i]) {
return false
}
}
return true
}
} | 0 | Kotlin | 10 | 17 | 2520dc56fc407f97564ed9f7c086292803d5d92d | 16,511 | development_learning | MIT License |
src/main/kotlin/org/mony/investor/Portfolio.kt | joow | 121,801,144 | false | null | package org.mony.investor
import java.math.BigDecimal
import java.math.RoundingMode
class Portfolio(private val positions: List<Position>) {
private val amount: BigDecimal = positions.map { it.amount }.fold(BigDecimal.ZERO) { acc, amount -> acc + amount }
private fun allocations() =
positions.groupingBy { it.type }.fold(BigDecimal.ZERO) { acc, position -> acc + position.amount }
private fun candidate(type: String, max: BigDecimal) =
positions
.filter { it.type == type && it.buy && it.price <= max }
.sortedByDescending { it.price }
.firstOrNull()
tailrec fun optimize(investment: BigDecimal, allocations: List<Allocation>, acc: List<Position> = emptyList()): Map<String, Int> {
val newPortfolio = Portfolio(positions.plus(acc))
val futureAmount = newPortfolio.amount + investment
val currentAllocations = newPortfolio.allocations()
val idealAllocations = allocations.map {
Pair(
it.type,
it.target.divide(BigDecimal("100"), 2, RoundingMode.HALF_EVEN) * futureAmount
)
}
val differences = idealAllocations
.map { (type, amount) -> Pair(type, currentAllocations.getOrDefault(type, BigDecimal.ZERO) - amount) }
.filter { it.second < BigDecimal.ZERO }
.sortedBy { it.second }
val nextPosition = differences.mapNotNull { candidate(it.first, investment) }
.firstOrNull()?.copy(shares = BigDecimal.ONE)
return if (nextPosition == null) acc.groupingBy { it.type }.eachCount()
else optimize(investment - nextPosition.price, allocations, acc.plus(nextPosition))
}
}
| 0 | Kotlin | 0 | 0 | a931de56cd10d5f9f948e0bf1e26994a84f235b3 | 1,734 | investor | MIT License |
kotlin/src/katas/kotlin/leetcode/partition_labels/PartitionLabels.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.partition_labels
import datsok.*
import org.junit.*
/**
* https://leetcode.com/problems/partition-labels/
*
* A string S of lowercase letters is given. We want to partition this string into as many parts as possible
* so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
*/
class PartitionLabelsTests {
@Test fun examples() {
partitionLabels("ababcbacadefegdehijhklij") shouldEqual listOf(
"ababcbaca", "defegde", "hijhklij"
)
}
}
private fun partitionLabels(s: String): List<String> {
val counts = IntArray(s.length)
val chars = HashSet<Char>()
s.indices.forEach { i -> if (chars.add(s[i])) counts[i] += 1 }
chars.clear()
s.indices.reversed().forEach { i -> if (chars.add(s[i])) counts[i] -= 1 }
val indices = ArrayList<Int>()
counts.foldIndexed(0) { index, sum, count ->
if (sum == 0) indices.add(index)
sum + count
}
indices.add(s.length)
return indices.windowed(size = 2).map { (from, to) -> s.substring(from, to) }
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,116 | katas | The Unlicense |
year2023/day03/engine/src/main/kotlin/com/curtislb/adventofcode/year2023/day03/engine/EngineSchematic.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2023.day03.engine
import com.curtislb.adventofcode.common.geometry.Point
import com.curtislb.adventofcode.common.grid.Grid
import com.curtislb.adventofcode.common.grid.forEachPointValue
import com.curtislb.adventofcode.common.grid.mutableGridOf
import com.curtislb.adventofcode.common.number.digitsToInt
import com.curtislb.adventofcode.common.number.product
import java.io.File
/**
* The schematic for a gondola lift engine, consisting of a grid of digits and symbols.
*
* @property grid The grid of characters that make up the schematic.
*
* @constructor Creates a new instance of [EngineSchematic] with the given character [grid].
*/
class EngineSchematic(private val grid: Grid<Char>) {
/**
* Returns the sum of all part numbers in the schematic.
*
* A part number is defined as a contiguous sequence of decimal digits that is horizontally or
* vertically adjacent to at least one "symbol", which can be any character other than a period
* (`.`) or digit (`'0'..'9'`).
*/
fun sumPartNumbers(): Int {
var total = 0
grid.forEachPointValue { point, value ->
if (value != '.' && !value.isDigit()) {
total += findAdjacentPartNumbers(point).sum()
}
}
return total
}
/**
* Returns the sum of all gear ratios in the schematic.
*
* A gear ratio is defined as the product of both part numbers (see [sumPartNumbers]) that are
* horizontally or vertically adjacent to a `*` symbol with *exactly* two adjacent part numbers.
*/
fun sumGearRatios(): Int {
var total = 0
grid.forEachPointValue { point, value ->
if (value == '*') {
val partNumbers = findAdjacentPartNumbers(point)
if (partNumbers.size == 2) {
total += partNumbers.product()
}
}
}
return total
}
/**
* Returns a list of all part numbers in the schematic that are adjacent to the given [point].
*/
private fun findAdjacentPartNumbers(point: Point): List<Int> {
val partNumbers = mutableListOf<Int>()
val foundRanges = mutableMapOf<Int, MutableList<IntRange>>()
for (neighbor in point.allNeighbors()) {
// Ignore out-of-bounds and non-digit points
if (grid.getOrNull(neighbor)?.isDigit() != true) {
continue
}
// Ignore points that are part of an already-found number
val neighborRow = neighbor.matrixRow
val neighborCol = neighbor.matrixCol
if (foundRanges[neighborRow]?.any { neighborCol in it } == true) {
continue
}
// Find the value and column range of the part number
val (number, colRange) = findPartNumber(neighborRow, neighborCol)
partNumbers.add(number)
foundRanges.getOrPut(neighborRow) { mutableListOf() }.add(colRange)
}
return partNumbers
}
/**
* Returns the value of the full part number with a digit at the given [rowIndex] and [colIndex]
* in the schematic, along with an integer range representing the column indices of its digits.
*/
private fun findPartNumber(rowIndex: Int, colIndex: Int): Pair<Int, IntRange> {
val numberChars = ArrayDeque<Int>()
// Add digits to the right of the starting point (inclusive)
var digitIndex = colIndex
while (digitIndex < grid.width && grid[rowIndex, digitIndex].isDigit()) {
numberChars.addLast(grid[rowIndex, digitIndex].digitToInt())
digitIndex++
}
val rangeEnd = digitIndex - 1
// Add digits to the left of the starting point (exclusive)
digitIndex = colIndex - 1
while (digitIndex >= 0 && grid[rowIndex, digitIndex].isDigit()) {
numberChars.addFirst(grid[rowIndex, digitIndex].digitToInt())
digitIndex--
}
val rangeStart = digitIndex + 1
// Return the part number and its column range
val partNumber = numberChars.digitsToInt()
return Pair(partNumber, rangeStart..rangeEnd)
}
companion object {
/**
* Returns an [EngineSchematic] with a grid of characters read from the given [file].
*
* @throws IllegalArgumentException If [file] is not formatted correctly.
*/
fun fromFile(file: File): EngineSchematic {
val grid = mutableGridOf<Char>().apply {
file.forEachLine { addShallowRow(it.toList()) }
}
return EngineSchematic(grid)
}
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 4,718 | AdventOfCode | MIT License |
2022/14/14.kt | LiquidFun | 435,683,748 | false | {"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191} | fun main() {
val lines = generateSequence(::readlnOrNull).toList()
.map { it.split(" -> ", ",").map { it.toInt() }.chunked(2) }
val width = lines.flatten().maxOf { it[0] } + 200
val height = lines.flatten().maxOf { it[1] } + 2
val field = MutableList(height) { MutableList(width) { '.' } }
fun range(a: Int, b: Int) = minOf(a, b)..maxOf(a, b)
fun drawLine(rx: IntRange, ry: IntRange) = rx.map { x -> ry.map { y -> field[y][x] = '#' } }
lines.map { it.zipWithNext { (x1, y1), (x2, y2) -> drawLine(range(x1, x2), range(y1, y2))} }
fun fill(): Int {
var endDfs = false
fun dfs(x: Int, y: Int): Boolean {
endDfs = endDfs || y >= field.size || field[0][500] == 'O'
if (endDfs || field[y][x] != '.')
return endDfs
if (!(dfs(x, y+1) || dfs(x-1, y+1) || dfs(x+1, y+1)))
field[y][x] = 'O'
return true
}
while (!endDfs) dfs(500, 0)
return field.flatten().count { it == 'O' }
}
println(fill())
field.add(MutableList(width) { '#' })
println(fill())
}
| 0 | Kotlin | 7 | 43 | 7cd5a97d142780b8b33b93ef2bc0d9e54536c99f | 1,119 | adventofcode | Apache License 2.0 |
kotlin/0322-coin-change.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} | // DP
class Solution {
fun coinChange(coins: IntArray, amount: Int): Int {
val dp = IntArray (amount + 1) { amount + 1 }
dp[0] = 0
for (i in 0..amount) {
for (j in 0 until coins.size) {
if (coins[j] <= i) {
dp[i] = minOf(dp[i], dp[i - coins[j]] + 1)
}
}
}
return if (dp[amount] > amount) -1 else dp[amount]
}
}
// Recursion + memoization
class Solution {
fun coinChange(coins: IntArray, amount: Int): Int {
val dp = IntArray (amount + 1) { -1 }
fun dfs(amount: Int): Int {
if (amount == 0) return 0
if (dp[amount] != -1) return dp[amount]
var res = Integer.MAX_VALUE
for (coin in coins) {
if (amount - coin >= 0) {
var count = dfs(amount - coin)
if (count != Integer.MAX_VALUE)
res = minOf(res, count + 1)
}
}
dp[amount] = res
return res
}
val res = dfs(amount)
return if (res == Integer.MAX_VALUE) -1 else res
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,172 | leetcode | MIT License |
day07/Kotlin/day07.kt | Ad0lphus | 353,610,043 | false | {"C++": 195638, "Python": 139359, "Kotlin": 80248} | import java.io.*
import kotlin.math.abs
fun print_day_7() {
val yellow = "\u001B[33m"
val reset = "\u001b[0m"
val green = "\u001B[32m"
println(yellow + "-".repeat(25) + "Advent of Code - Day 7" + "-".repeat(25) + reset)
println(green)
val process = Runtime.getRuntime().exec("figlet The Treachery of Whales -c -f small")
val reader = BufferedReader(InputStreamReader(process.inputStream))
reader.forEachLine { println(it) }
println(reset)
println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n")
}
fun main() {
print_day_7()
Day7().part_1()
Day7().part_2()
println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n")
}
class Day7 {
val crabs = File("../Input/day7.txt").readLines().first().split(",").map{it.toInt()}
fun part_1() {
val min = crabs.minOrNull()!!
val max = crabs.maxOrNull()!!
var lowest = Int.MAX_VALUE
for(i in min .. max) {
var fuelUsed = 0
for(crab in crabs) { fuelUsed += abs(crab - i) }
if (fuelUsed < lowest) {
lowest = fuelUsed
}
}
println("Puzzle 1: $lowest")
}
fun part_2() {
val min = crabs.minOrNull()!!
val max = crabs.maxOrNull()!!
var lowest = Int.MAX_VALUE
for(i in min .. max) {
var fuelUsed = 0
for(crab in crabs) { fuelUsed += calcFibIncrement(abs(crab - i)) }
if (fuelUsed < lowest) {
lowest = fuelUsed
}
}
println("Puzzle 2: $lowest")
}
fun calcFibIncrement(increment: Int, incrementBy: Int = 0): Int {
return if (increment == 0)
incrementBy
else
calcFibIncrement(increment - 1, incrementBy + 1) + incrementBy
}
} | 0 | C++ | 0 | 0 | 02f219ea278d85c7799d739294c664aa5a47719a | 1,840 | AOC2021 | Apache License 2.0 |
src/main/kotlin/g0801_0900/s0850_rectangle_area_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0850_rectangle_area_ii
// #Hard #Array #Ordered_Set #Segment_Tree #Line_Sweep
// #2023_03_30_Time_171_ms_(100.00%)_Space_35.7_MB_(100.00%)
class Solution {
fun rectangleArea(rectangles: Array<IntArray>): Int {
val memo: MutableList<IntArray> = ArrayList()
for (rectangle in rectangles) {
helper(0, rectangle, memo)
}
var res: Long = 0
val mod = (1e9 + 7).toInt()
for (m in memo) {
res = (res + (m[2] - m[0]).toLong() * (m[3] - m[1]).toLong()) % mod
}
return res.toInt()
}
private fun helper(id: Int, rectangle: IntArray, memo: MutableList<IntArray>) {
if (id >= memo.size) {
memo.add(rectangle)
return
}
val cur = memo[id]
if (rectangle[2] <= cur[0] || rectangle[0] >= cur[2] || rectangle[1] >= cur[3] || rectangle[3] <= cur[1]) {
helper(id + 1, rectangle, memo)
return
}
if (rectangle[0] < cur[0]) {
helper(id + 1, intArrayOf(rectangle[0], rectangle[1], cur[0], rectangle[3]), memo)
}
if (rectangle[2] > cur[2]) {
helper(id + 1, intArrayOf(cur[2], rectangle[1], rectangle[2], rectangle[3]), memo)
}
if (rectangle[1] < cur[1]) {
helper(
id + 1,
intArrayOf(
rectangle[0].coerceAtLeast(cur[0]),
rectangle[1],
rectangle[2].coerceAtMost(cur[2]),
cur[1]
),
memo
)
}
if (rectangle[3] > cur[3]) {
helper(
id + 1,
intArrayOf(
rectangle[0].coerceAtLeast(cur[0]),
cur[3],
rectangle[2].coerceAtMost(cur[2]),
rectangle[3]
),
memo
)
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,965 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/co/csadev/advent2022/Day23.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2022 by <NAME>
* Advent of Code 2022, Day 23
* Problem Description: http://adventofcode.com/2021/day/23
*/
package co.csadev.advent2022
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Point2D
import co.csadev.adventOfCode.Resources.resourceAsList
import co.csadev.adventOfCode.printArea
import kotlin.math.abs
class Day23(override val input: List<String> = resourceAsList("22day23.txt")) :
BaseDay<List<String>, Int, Int> {
private val elvesStart = input.flatMapIndexed { y, s -> s.mapIndexedNotNull { x, c -> if (c == '#') Point2D(x, y) else null } }.toSet()
private val northern = listOf(Point2D(0, -1), Point2D(1, -1), Point2D(-1, -1))
private val southern = listOf(Point2D(0, 1), Point2D(1, 1), Point2D(-1, 1))
private val western = listOf(Point2D(-1, 0), Point2D(-1, -1), Point2D(-1, 1))
private val eastern = listOf(Point2D(1, 0), Point2D(1, -1), Point2D(1, 1))
private val directionList = listOf(northern, southern, western, eastern)
override fun solvePart1(): Int {
val state = elvesStart.toMutableSet()
val dirs = directionList.toMutableList()
// state.print()
repeat(10) {
state.moveElves(dirs)
dirs.add(dirs.removeAt(0))
// state.print()
}
val ySize = abs(state.maxOf { it.y } - state.minOf { it.y }) + 1
val xSize = abs(state.maxOf { it.x } - state.minOf { it.x }) + 1
return (xSize * ySize) - state.size
}
@Suppress("unused")
private fun Set<Point2D>.print() {
val min = Point2D(minOf { p -> p.x }, minOf { p -> p.y })
val max = Point2D(maxOf { p -> p.x }, maxOf { p -> p.y })
printArea(min, max) { c, _ -> if (c) '#' else '.' }
println()
}
override fun solvePart2(): Int {
val state = elvesStart.toMutableSet()
val dirs = directionList.toMutableList()
// var num = 0
return generateSequence {
state.moveElves(dirs).also {
dirs.add(dirs.removeAt(0))
// state.print()
}
}.takeWhile {
// println("Round ${num++}")
it
}.count() + 1
}
private fun MutableSet<Point2D>.moveElves(dirList: List<List<Point2D>>): Boolean {
var moved = false
val proposal = mutableMapOf<Point2D, MutableList<Point2D>>()
for (p in this) {
if (p.neighbors.none { n -> n in this }) continue
dirList.firstOrNull { dir ->
dir.map { n -> n + p }.none { p -> p in this }
}?.let { propDir ->
(proposal.getOrPut(p + propDir.first()) { mutableListOf() }) += p
}
}
proposal.filter { it.value.size == 1 }.forEach { (newP, oldP) ->
moved = true
if (remove(oldP[0])) add(newP)
}
return moved
}
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 2,910 | advent-of-kotlin | Apache License 2.0 |
src/main/kotlin/io/dkozak/search/astar/sokoban/map.kt | d-kozak | 156,193,078 | false | null | package io.dkozak.search.astar.sokoban
typealias Location = Pair<Int, Int>
/**
* The neighbour indexes in the clockwise fashion, starting from the top
*/
val Location.neighbours: List<Location>
get() {
return listOf(
first - 1 to second,
first to second + 1,
first + 1 to second,
first to second - 1
)
}
val Location.neighboursAndDirections: List<Pair<Location, Direction>>
get() {
return this.neighbours.zip(listOf(Direction.UP, Direction.RIGHT, Direction.DOWN, Direction.LEFT))
}
enum class Field {
WALL,
PATH
}
/**
*
* Example input:
* 07 12 04
* XXXXXXX
* XG....X
* X.....X
* XGXG.GX
* XXXX.XX
* X.J...X
* X.J...X
* X..XXXX
* X.J.JMX
* X.....X
* X...XXX
* XXXXX
*/
fun parseMap(serializedMap: String): SokobanMap {
val lines = serializedMap.split("\n")
val header = lines[0]
val map = lines.subList(1, lines.size)
val (rowCount, colCount, diamondCount) = header.split(" ").map { it.toInt() }
val fields = mutableListOf<MutableList<Field>>()
val goals = mutableListOf<Location>()
val cans = mutableListOf<Location>()
var playerPosition = 0 to 0
map.forEachIndexed { i, line ->
val lineList = mutableListOf<Field>()
line.forEachIndexed { j, char ->
val location = i to j
when (char) {
'M' -> playerPosition = location
'J' -> cans.add(location)
'G' -> goals.add(location)
}
lineList.add(if (char != 'X' && char != ' ') Field.PATH else Field.WALL)
}
fields.add(lineList)
}
return SokobanMap(SokobanMap__Static(fields, goals), SokobanMap__Dynamic(playerPosition, cans))
}
fun isFinished(sokobanMap__Static: SokobanMap__Static, sokobanMap__Dynamic: SokobanMap__Dynamic) = sokobanMap__Static.goals == sokobanMap__Dynamic.canPositions
val SokobanMap.isFinished
get() = isFinished(this.sokobanMap__Static, this.sokobanMap__Dynamic)
data class SokobanMap(
val sokobanMap__Static: SokobanMap__Static,
val sokobanMap__Dynamic: SokobanMap__Dynamic
) {
override fun toString(): String = buildString {
sokobanMap__Static.fields.forEachIndexed { i, line ->
line.forEachIndexed { j, field ->
val location = i to j
when (location) {
sokobanMap__Dynamic.playerPosition -> append('M')
in sokobanMap__Dynamic.canPositions -> append('J')
in sokobanMap__Static.goals -> append('G')
else -> if (field == Field.PATH) append('.') else append('X')
}
if (j == line.size - 1) append('\n')
}
}
}
}
data class SokobanMap__Static(
val fields: List<List<Field>>,
val goals: List<Location>
) {
operator fun get(i: Int, j: Int): Field = if (i < 0 || j < 0 || i >= fields.size || j >= fields[0].size) {
Field.WALL
} else {
fields[i][j]
}
operator fun get(location: Location) = this[location.first, location.second]
}
data class SokobanMap__Dynamic(
val playerPosition: Location,
val canPositions: List<Location>
) {
} | 0 | Kotlin | 0 | 0 | da0a0de3872558293cb71cbc71a5fc374a3939a6 | 3,282 | search | MIT License |
diceroller/src/main/kotlin/com/nicolas/diceroller/roll/FacesReport.kt | CNicolas | 124,060,465 | false | null | package com.nicolas.diceroller.roll
import com.nicolas.models.dice.Face
typealias FacesReport = Map<Face, Int>
internal fun facesToFacesReport(faces: List<Face>): FacesReport {
val report = hashMapOf<Face, Int>()
faces.distinct()
.map { face -> report.put(face, faces.count { it == face }) }
return report
}
internal fun facesReportToFaces(facesReport: FacesReport): List<Face> {
return facesReport.flatMap { entry ->
(0 until entry.value).map { entry.key }
}
}
fun mergeReports(reports: List<FacesReport>): FacesReport =
reports.reduce { finalReport, rollResultReport -> mergeTwoReports(finalReport, rollResultReport) }
private fun mergeTwoReports(report1: FacesReport, report2: FacesReport): FacesReport =
report1.mergeReduce(report2) { a, b -> a + b }
private fun <K, V> Map<K, V>.mergeReduce(other: Map<K, V>, reduce: (V, V) -> V = { _, b -> b }): Map<K, V> {
val result = LinkedHashMap<K, V>(this.size + other.size)
result.putAll(this)
other.forEach { (key, value) ->
result[key] = result[key]?.let { reduce(value, it) } ?: value
}
return result
}
| 0 | Kotlin | 0 | 1 | ec6e8048f7f01c75b19bddf7ec5c0485b76aea99 | 1,146 | WHFRP3Companion | Apache License 2.0 |
src/main/kotlin/week1/DiskDrive.kt | waikontse | 572,850,856 | false | {"Kotlin": 63258} | package week1
import shared.Puzzle
class DiskDrive : Puzzle(7) {
enum class NodeType {
DIR,
FILE
}
data class Node(
val parent: Node?,
val type: NodeType,
var fileSize: Int,
val name: String
) {
val nodes: MutableList<Node> = mutableListOf()
fun addDir(name: String) =
this.apply { nodes.add(Node(this, NodeType.DIR, 0, name)) }
fun addFile(size: Int, name: String) =
this.apply { nodes.add(Node(this, NodeType.FILE, size, name)) }
}
override fun solveFirstPart(): Any {
val rootNode = getRootNode(puzzleInput)
return findTarget(listOf(rootNode), emptyList()) { node: Node -> node.type == NodeType.DIR && node.fileSize <= 100000 }
.sum()
}
override fun solveSecondPart(): Any {
val rootNode = getRootNode(puzzleInput)
val totalFsSize = 70000000
val targetFreeSize = 30000000
val currentFreeSize = totalFsSize - rootNode.fileSize
val neededFreeSize = targetFreeSize - currentFreeSize
return findTarget(listOf(rootNode), emptyList()) { node: Node -> (node.type == NodeType.DIR) && (node.fileSize >= neededFreeSize) }
.filter { it > 0 }
.minOf { it }
}
private fun getRootNode(input: List<String>): Node {
val rootNode = Node(null, NodeType.DIR, 0, "/")
parseFolder(input, rootNode)
calculateAndPropagateSize(listOf(rootNode))
return rootNode
}
private tailrec fun parseFolder(lines: List<String>, nodes: Node) {
if (lines.isEmpty()) {
return
}
parseFolder(lines.drop(1), parseCommandLine(lines.first(), nodes))
}
private fun parseCommandLine(line: String, nodes: Node): Node {
return when (line) {
"$ cd /" -> nodes
"$ cd .." -> nodes.parent!!
"$ ls" -> nodes
else -> {
parseDirEntries(line, nodes)
}
}
}
private val cdToRegex = """\$ cd (\w+)""".toRegex()
private val dirRegex = """dir (\w+)""".toRegex()
private val fileRegex = """(\d+) (\p{Graph}+)""".toRegex()
private fun parseDirEntries(line: String, nodes: Node): Node {
return if (cdToRegex.matches(line)) {
val (dirName) = cdToRegex.matchEntire(line)?.destructured ?: throw IllegalArgumentException()
nodes.nodes.find { it.name == dirName }!!
} else if (dirRegex.matches(line)) {
val (dirName) = dirRegex.matchEntire(line)?.destructured ?: throw IllegalArgumentException()
nodes.addDir(dirName)
} else if (fileRegex.matches(line)) {
val (fileSize, fileName) = fileRegex.matchEntire(line)?.destructured ?: throw IllegalArgumentException()
nodes.addFile(fileSize.toInt(), fileName)
} else {
throw IllegalArgumentException("Could not parse line: $line")
}
}
private fun calculateAndPropagateSize(acc: List<Node>): Int {
if (acc.isEmpty()) {
return 0
}
return acc.sumOf { calculateSize(it) }
}
private fun calculateSize(node: Node): Int {
return when (node.type) {
NodeType.FILE -> node.fileSize
NodeType.DIR -> {
node.fileSize = calculateAndPropagateSize(node.nodes)
return node.fileSize
}
}
}
private tailrec fun findTarget(
stack: List<Node>,
acc: List<Int>,
predicate: (Node) -> Boolean
): List<Int> {
if (stack.isEmpty()) {
return acc
}
val fileSize = if (predicate(stack.first())) stack.first().fileSize else 0
return findTarget(stack.drop(1) + stack.first().nodes, acc + fileSize, predicate)
}
}
| 0 | Kotlin | 0 | 0 | 860792f79b59aedda19fb0360f9ce05a076b61fe | 3,851 | aoc-2022-in-kotllin | Creative Commons Zero v1.0 Universal |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions50.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round0
fun test50() {
val str1 = "abacdeff"
println(findNotRepeatingChar(str1))
val str2 = "We are Students."
val str3 = "aeiou"
println(deleteChar(str2, str3))
val str4 = "google"
println(deleteRepeatChar(str4))
val str5 = "silent"
val str6 = "listen"
val str7 = "evil"
val str8 = "live"
println(isAnagram(str5, str6))
println(isAnagram(str7, str8))
}
/**
* 题目一:寻找一个字符串中第一个只出现一次的字符
*/
fun findNotRepeatingChar(str: String): Char {
val map = LinkedHashMap<Char, Int>()
for (i in str.indices) {
val c = str[i]
val v = map[c]
map[c] = if (v == null) 1 else v + 1
}
var result: Char? = null
var isFound = true
map.forEach {
val (c, i) = it
if (i == 1 && isFound) {
result = c
isFound = false
}
}
return result!!
}
/**
* 相关题目:输入两个字符串,从第一个字符串中删除所有第二个字符串中出现过的字符
*/
fun deleteChar(str1: String, str2: String): String {
val list = ArrayList<Char>()
for (i in str2.indices) {
val c = str2[i]
if (c !in list)
list.add(c)
}
val builder = StringBuilder(str1)
var i = 0
while (i < builder.length) {
val c = builder[i]
if (c in list) {
builder.deleteAt(i)
} else i++
}
return builder.toString()
}
/**
* 相关题目:删除一个字符串中的所有重复字符
*/
fun deleteRepeatChar(str: String): String {
val list = ArrayList<Char>()
val builder = StringBuilder(str)
var i = 0
while (i < builder.length) {
val c = builder[i]
if (c in list) {
builder.deleteAt(i)
} else {
list.add(c)
i++
}
}
return builder.toString()
}
/**
* 相关题目:判断两个单词是否为变位词
*/
fun isAnagram(str1: String, str2: String): Boolean {
if (str1.length != str2.length) return false
fun create(str: String): HashMap<Char, Int> {
val map = HashMap<Char, Int>()
for (i in str.indices) {
val c = str2[i]
if (map[c] == null) {
map[c] = 1
} else {
map[c] = map[c]!! + 1
}
}
return map
}
val map1 = create(str1)
val map2 = create(str2)
return map1 == map2
}
/**
* 题目二:字符流中第一个只出现一次的字符
*/ | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,216 | Algorithm | Apache License 2.0 |
src/Day03.kt | JonasDBB | 573,382,821 | false | {"Kotlin": 17550} | private fun stringHalves(line: String) = Pair(line.substring(0, line.length / 2), line.substring(line.length / 2))
private fun part1(input: List<String>) {
var ret = 0
for (line in input) {
val strings = stringHalves(line)
run end@ {
strings.first.forEach { c ->
if (strings.second.any { it == c }) {
ret += if (c.isLowerCase()) c - 'a' + 1 else c - 'A' + 27
return@end
}
}
}
}
println(ret)
}
private fun part2(input: List<String>) {
var ret = 0
for (group in input.chunked(3)) {
run end@ {
group[0].forEach { c ->
if (group[1].any { it == c} && group[2].any { it == c}) {
ret += if (c.isLowerCase()) c - 'a' + 1 else c - 'A' + 27
return@end
}
}
}
}
println(ret)
}
fun main () {
val input = readInput("03")
println("part 1")
part1(input)
println("part 2")
part2(input)
} | 0 | Kotlin | 0 | 0 | 199303ae86f294bdcb2f50b73e0f33dca3a3ac0a | 1,057 | AoC2022 | Apache License 2.0 |
src/Day06.kt | BHFDev | 572,832,641 | false | null | fun main() {
fun part1(input: List<String>): Int {
val mostRecentCharactersQueue = ArrayDeque<Char>()
fun checkQueue(): Boolean {
var success = true
(1..(mostRecentCharactersQueue.size)).forEach { _ ->
val currentChar = mostRecentCharactersQueue.removeFirst()
if (mostRecentCharactersQueue.contains(currentChar)) {
success = false
}
mostRecentCharactersQueue.addLast(currentChar)
}
return success
}
return input[0].indexOfFirst {
if(mostRecentCharactersQueue.size == 4 && checkQueue()) {
true
} else {
if(mostRecentCharactersQueue.size == 4) {
mostRecentCharactersQueue.removeFirst()
}
mostRecentCharactersQueue.addLast(it)
false
}
}
}
fun part2(input: List<String>): Int {
val mostRecentCharactersQueue = ArrayDeque<Char>()
fun checkQueue(): Boolean {
var success = true
(1..(mostRecentCharactersQueue.size)).forEach { _ ->
val currentChar = mostRecentCharactersQueue.removeFirst()
if (mostRecentCharactersQueue.contains(currentChar)) {
success = false
}
mostRecentCharactersQueue.addLast(currentChar)
}
return success
}
return input[0].indexOfFirst {
if(mostRecentCharactersQueue.size == 14 && checkQueue()) {
true
} else {
if(mostRecentCharactersQueue.size == 14) {
mostRecentCharactersQueue.removeFirst()
}
mostRecentCharactersQueue.addLast(it)
false
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | b158069483fa02636804450d9ea2dceab6cf9dd7 | 2,139 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/aoc2016/Day16.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2016
class Day16(private val length: Int, private val input: String) {
private fun String.reverseInvert(): String {
return this.reversed().map {
when (it) {
'1' -> '0'
'0' -> '1'
else -> it
}
}.joinToString("")
}
fun dragonStep(a: String): String {
return "${a}0${a.reverseInvert()}"
}
private fun dragonCurve(size: Int, input: String): String {
return generateSequence(input) { dragonStep(it) }
.dropWhile { it.length < size }
.first()
.take(size)
}
// Approach 1: Concatenate strings
// Part 2 takes forever to run (aborted 2 after 20 minutes)
fun checksum(input: String): String {
var checksum = input
while (checksum.length % 2 == 0) {
var i = 2
var newChecksum = ""
while (i <= checksum.length) {
val pair = checksum.substring(i - 2, i)
newChecksum += if (pair == "11" || pair == "00") {
1
} else {
0
}
i += 2
}
checksum = newChecksum
}
return checksum
}
// Approach 2: Convert the input to a list of chars and add to the list then join back to a string
// Part 2 takes in total 7-10 seconds
fun checksumOptimized(input: String): String {
var checksum = input.toList()
while (checksum.size % 2 == 0) {
val checksum2 = (checksum.indices step 2).map {
when (checksum[it] == checksum[it + 1]) {
true -> '1'
false -> '0'
}
}
checksum = checksum2
}
return checksum.joinToString("")
}
// Approach 3: Try tail recursion instead of an iterative approach. Possibly slightly simpler code.
// Takes about the same time as the iterative approach.
fun checksumOptimized2(input: String) = checksumTailRec(input.toList()).joinToString("")
private tailrec fun checksumTailRec(input: List<Char>): List<Char> {
val checksum = (input.indices step 2).map { if (input[it] == input[it + 1]) '1' else '0' }
if (checksum.size % 2 != 0) {
return checksum
}
return checksumTailRec(checksum)
}
private fun getChecksumForDisk(length: Int, initialState: String): String {
return checksumOptimized2(dragonCurve(length, initialState))
}
fun solvePart1(): String {
return getChecksumForDisk(length, input)
}
fun solvePart2(): String {
return getChecksumForDisk(length, input)
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,746 | aoc | MIT License |
packages/dotlin/lib/src/kotlin/ranges/Ranges.kt | dotlin-org | 434,960,829 | false | {"Kotlin": 2136413, "Dart": 128641, "Java": 6266} | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Copyright 2021-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 kotlin.ranges
/**
* A range of values of type `Int`.
*/
class IntRange(start: Int, endInclusive: Int) : IntProgression(start, endInclusive, 1), ClosedRange<Int> {
override val start: Int get() = first
override val endInclusive: Int get() = last
override fun contains(value: Int): Boolean = first <= value && value <= last
/**
* Checks whether the range is empty.
*
* The range is empty if its start value is greater than the end value.
*/
override fun isEmpty(): Boolean = first > last
override fun equals(other: Any?): Boolean =
other is IntRange && (isEmpty() && other.isEmpty() ||
first == other.first && last == other.last)
override fun hashCode(): Int =
if (isEmpty()) -1 else (31 * first + last)
override fun toString(): String = "$first..$last"
companion object {
/** An empty range of values of type Int. */
val EMPTY: IntRange = IntRange(1, 0)
}
}
/**
* Represents a range of [Comparable] values.
*/
private open class ComparableRange<T : Comparable<T>>(
override val start: T,
override val endInclusive: T
) : ClosedRange<T> {
override fun equals(other: Any?): Boolean {
return other is ComparableRange<*> && (isEmpty() && other.isEmpty() ||
start == other.start && endInclusive == other.endInclusive)
}
override fun hashCode(): Int {
return if (isEmpty()) -1 else 31 * start.hashCode() + endInclusive.hashCode()
}
override fun toString(): String = "$start..$endInclusive"
}
/**
* Creates a range from this [Comparable] value to the specified [that] value.
*
* This value needs to be smaller than or equal to [that] value, otherwise the returned range will be empty.
* @sample samples.ranges.Ranges.rangeFromComparable
*/
operator fun <T : Comparable<T>> T.rangeTo(that: T): ClosedRange<T> = ComparableRange(this, that)
/**
* Represents a range of floating point numbers.
* Extends [ClosedRange] interface providing custom operation [lessThanOrEquals] for comparing values of range domain type.
*
* This interface is implemented by floating point ranges returned by [Float.rangeTo] and [Double.rangeTo] operators to
* achieve IEEE-754 comparison order instead of total order of floating point numbers.
*/
@SinceKotlin("1.1")
interface ClosedFloatingPointRange<T : Comparable<T>> : ClosedRange<T> {
override fun contains(value: T): Boolean = lessThanOrEquals(start, value) && lessThanOrEquals(value, endInclusive)
override fun isEmpty(): Boolean = !lessThanOrEquals(start, endInclusive)
/**
* Compares two values of range domain type and returns true if first is less than or equal to second.
*/
fun lessThanOrEquals(a: T, b: T): Boolean
}
/**
* A closed range of values of type `Double`.
*
* Numbers are compared with the ends of this range according to IEEE-754.
*/
private class ClosedDoubleRange(
start: Double,
endInclusive: Double
) : ClosedFloatingPointRange<Double> {
private val _start = start
private val _endInclusive = endInclusive
override val start: Double get() = _start
override val endInclusive: Double get() = _endInclusive
override fun lessThanOrEquals(a: Double, b: Double): Boolean = a <= b
override fun contains(value: Double): Boolean = value >= _start && value <= _endInclusive
override fun isEmpty(): Boolean = !(_start <= _endInclusive)
override fun equals(other: Any?): Boolean {
return other is ClosedDoubleRange && (isEmpty() && other.isEmpty() ||
_start == other._start && _endInclusive == other._endInclusive)
}
override fun hashCode(): Int {
return if (isEmpty()) -1 else 31 * _start.hashCode() + _endInclusive.hashCode()
}
override fun toString(): String = "$_start..$_endInclusive"
}
/**
* Creates a range from this [Double] value to the specified [that] value.
*
* Numbers are compared with the ends of this range according to IEEE-754.
* @sample samples.ranges.Ranges.rangeFromDouble
*/
@SinceKotlin("1.1")
operator fun Double.rangeTo(that: Double): ClosedFloatingPointRange<Double> = ClosedDoubleRange(this, that)
/**
* Returns `true` if this iterable range contains the specified [element].
*
* Always returns `false` if the [element] is `null`.
*/
@SinceKotlin("1.3")
//@kotlin.internal.InlineOnly
inline operator fun <T, R> R.contains(element: T?): Boolean where T : Any, R : Iterable<T>, R : ClosedRange<T> =
element != null && contains(element)
internal fun checkStepIsPositive(isPositive: Boolean, step: Number) {
if (!isPositive) throw ArgumentError("Step must be positive, was: $step.")
} | 5 | Kotlin | 3 | 223 | 174ade2b64fb8275eb6914e29df2b18e6f74f85f | 5,367 | dotlin | Apache License 2.0 |
codeforces/kotlinheroes8/e.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes8
private fun solve(): Int {
val n = readInt()
val s = readLn().map { "()".indexOf(it) }
val a = readLn()
val must = IntArray(n) { -1 }
val diff = BooleanArray(n)
for (i in a.indices) {
if (a[i] == '0') continue
if (must[i] == 1) return -1
must[i] = 0
must[i + 3] = 1
diff[i + 2] = true
}
val inf = n + 1
val ans = s.indices.fold(listOf(0, 0)) { prev, i -> List(2) { j ->
if (must[i] == 1 - j) inf else
(s[i] xor j) + if (diff[i]) prev[1 - j] else prev.minOrNull()!!
}}.minOrNull()!!
return if (ans >= inf) -1 else ans
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 710 | competitions | The Unlicense |
src/main/kotlin/com/hj/leetcode/kotlin/problem1220/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1220
/**
* LeetCode page: [1220. Count Vowels Permutation](https://leetcode.com/problems/count-vowels-permutation/);
*/
class Solution {
/* Complexity:
* Time O(n) and Space O(1);
*/
fun countVowelPermutation(n: Int): Int {
val modulo = 1_000_000_007
/* dp@L::= the number of length L permutations ending with
* 'a', 'e', 'i', 'o', and 'u' respectively
*/
val dp = mutableListOf(1, 1, 1, 1, 1) // Base case where L equals 1
for (length in 2..n) {
val (a, e, i, o, u) = dp
dp[0] = ((e + i) % modulo + u) % modulo
dp[1] = (a + i ) % modulo
dp[2] = (e + o) % modulo
dp[3] = i
dp[4] = (i + o) % modulo
}
return dp.fold(0) { acc, i -> (acc + i) % modulo }
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 855 | hj-leetcode-kotlin | Apache License 2.0 |
_7Function/src/main/kotlin/practice/76 Array Is All Larger.kt | Meus-Livros-Lidos | 690,208,771 | false | {"Kotlin": 166470} | package practice
/**
* Write a method arrayIsAllLarger that, given two Int arrays,
* returns true if all the values in the first array are larger than
* or equal to all the values in the same position in the second array.
* If the first array is longer than the second array, or the second array is longer than the first array,
* then the extra values can be ignored. If either array is empty, return false.
*
* For example, given {1, 2, 4} and {0, 1, 7}, you should return false, since 7 is greater than 4.
* Given {1, 2, 4} and {0, 1} you should return true, since the first two values of the first array
* are greater than the first two values of the second array. Given {1, 2, 4} and {0, 1, 3, 8}, you should return true,
* since the first three values of the first array are greater than the first three values of the second array. Given {1, 2} and {1, 2},
* you should return true, since all values in the two arrays are equal.
*/
fun main() {
println("Enter with the size of array:")
var sizeArray = readlnOrNull()?.toIntOrNull() ?: 1
while (!correctSizeArray5(sizeArray)) {
println("The size array must be int the range 1 .. 3")
println("Enter with the size of array again:")
sizeArray = readlnOrNull()?.toIntOrNull() ?: 1
correctSizeArray5(sizeArray)
}
val array1 = IntArray(sizeArray)
for (i in array1.indices) {
println("Enter with the number:")
val inputNumber = readlnOrNull()?.toIntOrNull() ?: 0
array1[i] = inputNumber
}
println("Enter with the size of array:")
var sizeArray2 = readlnOrNull()?.toIntOrNull() ?: 1
while (!correctSizeArray5(sizeArray2)) {
println("The size array must be int the range 1 .. 3")
println("Enter with the size of array again:")
sizeArray2 = readlnOrNull()?.toIntOrNull() ?: 1
correctSizeArray5(sizeArray2)
}
val array2 = IntArray(sizeArray2)
for (i in array2.indices) {
println("Enter with the number:")
val inputNumber = readlnOrNull()?.toIntOrNull() ?: 0
array2[i] = inputNumber
}
val arrayMinSize = checkArrayLarger(array1, array2)
println("Array is all larger: ${arrayLargeValueCompare(array1, array2, arrayMinSize)}")
}
fun correctSizeArray5(sizeArray: Int): Boolean {
return sizeArray > 0
}
fun checkArrayLarger(array1: IntArray, array2: IntArray): Int {
if (array1.size < array2.size) {
return array1.size
}
return array2.size
}
fun arrayLargeValueCompare(array1: IntArray, array2: IntArray, arrayMinSize: Int): Boolean {
for (i in 0..< arrayMinSize) {
if (array1[i] >= array2[i]) {
return true
}
}
return false
} | 0 | Kotlin | 0 | 1 | 2d05e5528b9dd2cf9ed8799bce47444246be6b42 | 2,729 | LearnCsOnline-Kotlin | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[59]螺旋矩阵 II.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
//
//
//
// 示例 1:
//
//
//输入:n = 3
//输出:[[1,2,3],[8,9,4],[7,6,5]]
//
//
// 示例 2:
//
//
//输入:n = 1
//输出:[[1]]
//
//
//
//
// 提示:
//
//
// 1 <= n <= 20
//
// Related Topics 数组 矩阵 模拟
// 👍 444 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun generateMatrix(n: Int): Array<IntArray> {
//返回结果
val arr = Array(n) { IntArray(n) }
//数组矩阵初始值
var startVal = 1
//当前计算矩阵旋转 index
var index = 0
while (startVal <= n*n){
//左到右
for (i in index until n -index)
arr[index][i] = startVal++
//上到下
for (i in index+1 until n -index)
arr[i][n-index - 1] = startVal++
//右到左
for (i in n - index - 2 downTo index)
arr[n - index - 1][i] = startVal++
//下到上
for (i in n - index - 2 downTo index + 1)
arr[i][index] = startVal++
index++
}
return arr
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,374 | MyLeetCode | Apache License 2.0 |
testers/SortedSquaresTester.kt | GwGibson | 590,189,035 | false | null | package challenges.testers
import challenges.sortedSquares
object SortedSquaresTester {
private val t1 = listOf(1, 2, 3, 5, 6, 8, 9, 10)
private val r1 = listOf(1, 4, 9, 25, 36, 64, 81, 100)
private val t2 = listOf(1)
private val r2 = listOf(1)
private val t3 = listOf(0)
private val r3 = listOf(0)
private val t4 = listOf(-1)
private val r4 = listOf(1)
private val t5 = listOf(-5, -4, -3, -2, -1)
private val r5 = listOf(1, 4, 9, 16, 25)
private val t6 = listOf(-50, -10, -2, -1, 0, 0, 1, 1, 5, 19, 22)
private val r6 = listOf(0, 0, 1, 1, 1, 4, 25, 100, 361, 484, 2500)
private val t7 = listOf(0, 0, 0, 0, 0)
private val r7 = listOf(0, 0, 0, 0, 0)
private val t8 = listOf<Int>()
private val r8 = listOf<Int>()
private val t9 = listOf(2, 3, 5, 7, 9)
private val r9 = listOf(4, 9, 25, 49, 81)
private val tests = listOf(t1, t2, t3, t4, t5, t6, t7, t8, t9)
private val expected = listOf(r1, r2, r3, r4, r5, r6, r7, r8, r9)
fun run() {
println("Running sortedSquares tester.")
var results = mutableListOf<Result>()
var index = 1
tests.zip(expected) { a, b ->
results.add(buildResult(index++, "list: ${convertToString(a)}", sortedSquares(a), b))
}
results.forEach { it.print() }
}
}
| 0 | Kotlin | 19 | 1 | 71d24dcf63ba5f09e6f2f32a4c3dfe2ec82030b5 | 1,368 | jav1001-challenges | MIT License |
src/main/kotlin/net/codetreats/aoc2021/day16/Package.kt | codetreats | 433,929,847 | false | {"Kotlin": 133030, "Shell": 811} | package net.codetreats.aoc2021.day16
import net.codetreats.aoc2021.util.Logger
data class Package(
val bitsConsumed: Int,
val version: Int,
val type: Int,
val literal: Long?,
val subPackages: List<Package>
) {
fun versionSum(): Int = version + subPackages.map { it.versionSum() }.sum()
fun value(): Long = when (type) {
0 -> subPackages.map { it.value() }.sum()
1 -> subPackages.map { it.value() }.reduce { op1, op2 -> op1 * op2 }
2 -> subPackages.map { it.value() }.min()!!
3 -> subPackages.map { it.value() }.max()!!
4 -> literal!!
5 -> if (subPackages[0]!!.value() > subPackages[1]!!.value()) 1 else 0
6 -> if (subPackages[0]!!.value() < subPackages[1]!!.value()) 1 else 0
7 -> if (subPackages[0]!!.value() == subPackages[1]!!.value()) 1 else 0
else -> throw IllegalArgumentException("Unknown type $type")
}
companion object {
val logger: Logger = Logger.forDay(16, Package::class.java.simpleName)
fun from(binaryString: String): Package {
logger.info("New package from $binaryString")
val version: Int = binaryString.substring(0, 3).toInt(2)
val type: Int = binaryString.substring(3, 6).toInt(2)
logger.info("Version: $version - Type: $type")
val substring = binaryString.substring(6)
val pkg = if (type == 4) {
val literal = parseLiteral(substring)
Package(literal.bitsConsumed + 6, version, type, literal.literal, emptyList())
} else {
parseOperator(version, type, substring)
}
logger.info("Created new package from $binaryString: $pkg")
return pkg
}
private fun parseOperator(version: Int, type: Int, substring: String): Package {
val subPackages = mutableListOf<Package>()
var bitsConsumed = 0
var headerConsumed : Int
var condition: () -> Boolean
if (substring[0] == '0') {
headerConsumed = 16
condition = { subPackages.map { it.bitsConsumed }.sum() < substring.substring(1, 16).toInt(2) }
} else {
headerConsumed = 12
condition = { subPackages.size < substring.substring(1, 12).toInt(2) }
}
var subStringRest = substring.substring(headerConsumed)
bitsConsumed += headerConsumed
while (condition()) {
val p = from(subStringRest)
subPackages.add(p)
bitsConsumed += p.bitsConsumed
subStringRest = subStringRest.substring(p.bitsConsumed)
}
return Package(bitsConsumed + 6, version, type, null, subPackages)
}
private fun parseLiteral(substring: String): Literal {
logger.info("parseLiteral: $substring")
var number = ""
var consumed = 0
for (i in 0 until substring.length / 5) {
number += substring.substring(i * 5 + 1, i * 5 + 5)
consumed += 5
if (substring[i * 5] == '0') {
break
}
}
val literal = number.toLong(2)
return Literal(literal, consumed)
}
}
}
data class Literal(val literal: Long, val bitsConsumed: Int) | 0 | Kotlin | 0 | 0 | f7c456faa31f85420e988baa47682e0de973e906 | 3,411 | aoc2021 | MIT License |
src/main/kotlin/me/giacomozama/adventofcode2023/days/Day01.kt | giacomozama | 725,810,476 | false | {"Kotlin": 12023} | package me.giacomozama.adventofcode2023.days
import java.io.File
class Day01 : Day() {
private lateinit var input: List<String>
override fun parseInput(inputFile: File) {
input = inputFile.readLines()
}
override fun solveFirstPuzzle(): Int {
var result = 0
for (line in input) {
var lineResult = 0
for (c in line) {
if (c.isDigit()) {
lineResult = c.digitToInt() * 10
break
}
}
for (i in line.lastIndex downTo 0) {
val c = line[i]
if (c.isDigit()) {
lineResult += c.digitToInt()
break
}
}
result += lineResult
}
return result
}
override fun solveSecondPuzzle(): Int {
fun findFirstDigit(line: String, names: List<String>): Int {
for (i in line.indices) {
val possible = names.toMutableList()
var j = i
while (possible.size > 1 || possible.size == 1 && j - i < possible[0].length) {
val c = line[j++]
if (c.isDigit()) return c.digitToInt()
val l = j - i - 1
possible.removeIf { it.length <= l || it[l] != c }
}
if (possible.size == 1) return names.indexOf(possible[0])
}
throw IllegalArgumentException()
}
val names = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
val reversedNames = names.map { it.reversed() }
return input.sumOf { findFirstDigit(it, names) * 10 + findFirstDigit(it.reversed(), reversedNames) }
}
} | 0 | Kotlin | 0 | 0 | a86e9757288c63778e1f8f1f3fa5a2cfdaa6dcdd | 1,799 | aoc2023 | MIT License |
LeetCode/Kth Smallest Element in a Sorted Matrix/main.kt | thedevelopersanjeev | 112,687,950 | false | null | class Solution {
private fun lowerBound(arr: IntArray, ele: Int): Int {
var (lo, hi, ans) = listOf(0, arr.size - 1, 0)
while (lo <= hi) {
val mid = lo + (hi - lo) / 2
if (arr[mid] < ele) {
ans = mid + 1
lo = mid + 1
} else {
hi = mid - 1
}
}
return ans
}
private fun good(matrix: Array<IntArray>, ele: Int, k: Int): Boolean {
var cnt = 0
for (row in matrix) {
cnt += lowerBound(row, ele)
}
return cnt < k
}
fun kthSmallest(matrix: Array<IntArray>, k: Int): Int {
var (lo, hi, ans) = listOf(matrix[0][0], matrix.last().last(), 0)
while (lo <= hi) {
val mid = lo + (hi - lo) / 2
if (good(matrix, mid, k)) {
ans = mid
lo = mid + 1
} else {
hi = mid - 1
}
}
return ans
}
} | 0 | C++ | 58 | 146 | 610520cc396fb13a03c606b5fb6739cfd68cc444 | 994 | Competitive-Programming | MIT License |
src/leetcodeProblem/leetcode/editor/en/StringWithoutAaaOrBbb.kt | faniabdullah | 382,893,751 | false | null | //Given two integers a and b, return any string s such that:
//
//
// s has length a + b and contains exactly a 'a' letters, and exactly b 'b'
//letters,
// The substring 'aaa' does not occur in s, and
// The substring 'bbb' does not occur in s.
//
//
//
// Example 1:
//
//
//Input: a = 1, b = 2
//Output: "abb"
//Explanation: "abb", "bab" and "bba" are all correct answers.
//
//
// Example 2:
//
//
//Input: a = 4, b = 1
//Output: "aabaa"
//
//
//
// Constraints:
//
//
// 0 <= a, b <= 100
// It is guaranteed such an s exists for the given a and b.
//
// Related Topics String Greedy 👍 392 👎 307
package leetcodeProblem.leetcode.editor.en
class StringWithoutAaaOrBbb {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun strWithout3a3b(A: Int, B: Int): String {
var A = A
var B = B
val ans = StringBuilder()
while (A > 0 || B > 0) {
var writeA = false
val L = ans.length
if (L >= 2 && ans[L - 1] == ans[L - 2]) {
if (ans[L - 1] == 'b') writeA = true
} else {
if (A >= B) writeA = true
}
if (writeA) {
A--
ans.append('a')
} else {
B--
ans.append('b')
}
}
return ans.toString()
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 1,693 | dsa-kotlin | MIT License |