path
stringlengths 5
169
| owner
stringlengths 2
34
| repo_id
int64 1.49M
755M
| is_fork
bool 2
classes | languages_distribution
stringlengths 16
1.68k
⌀ | content
stringlengths 446
72k
| issues
float64 0
1.84k
| main_language
stringclasses 37
values | forks
int64 0
5.77k
| stars
int64 0
46.8k
| commit_sha
stringlengths 40
40
| size
int64 446
72.6k
| name
stringlengths 2
64
| license
stringclasses 15
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/ginsberg/advent2019/Day06.kt
|
tginsberg
| 222,116,116 | false | null |
/*
* Copyright (c) 2019 by <NAME>
*/
/**
* Advent of Code 2019, Day 6 - Universal Orbit Map
* Problem Description: http://adventofcode.com/2019/day/6
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day6/
*/
package com.ginsberg.advent2019
class Day06(input: List<String>) {
// Note that this is Orbiting -> Orbited, not Orbited -> Orbiting
private val orbitPairs: Map<String, String> = input.map { it.split(")") }.map { it.last() to it.first() }.toMap()
fun solvePart1(): Int =
orbitPairs.keys.sumBy { pathTo(it).size -1 }
fun solvePart2(): Int {
val youToRoot = pathTo("YOU")
val santaToRoot = pathTo("SAN")
val intersection = youToRoot.intersect(santaToRoot).first()
return youToRoot.indexOf(intersection) + santaToRoot.indexOf(intersection) - 2
}
private fun pathTo(orbit: String, path: MutableList<String> = mutableListOf(orbit)): List<String> =
orbitPairs[orbit]?.let { around ->
path.add(around)
pathTo(around, path)
} ?: path
}
| 0 |
Kotlin
| 2 | 23 |
a83e2ecdb6057af509d1704ebd9f86a8e4206a55
| 1,086 |
advent-2019-kotlin
|
Apache License 2.0
|
kotlin/16.3Sum Closest(最接近的三数之和).kt
|
learningtheory
| 141,790,045 | false |
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
|
/**
<p>Given an array <code>nums</code> of <em>n</em> integers and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>. Return the sum of the three integers. You may assume that each input would have exactly one solution.</p>
<p><strong>Example:</strong></p>
<pre>
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
</pre>
<p>给定一个包括 <em>n</em> 个整数的数组 <code>nums</code><em> </em>和 一个目标值 <code>target</code>。找出 <code>nums</code><em> </em>中的三个整数,使得它们的和与 <code>target</code> 最接近。返回这三个数的和。假定每组输入只存在唯一答案。</p>
<pre>例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
</pre>
<p>给定一个包括 <em>n</em> 个整数的数组 <code>nums</code><em> </em>和 一个目标值 <code>target</code>。找出 <code>nums</code><em> </em>中的三个整数,使得它们的和与 <code>target</code> 最接近。返回这三个数的和。假定每组输入只存在唯一答案。</p>
<pre>例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
</pre>
**/
class Solution {
fun threeSumClosest(nums: IntArray, target: Int): Int {
}
}
| 0 |
Python
| 1 | 3 |
6731e128be0fd3c0bdfe885c1a409ac54b929597
| 1,540 |
leetcode
|
MIT License
|
src/main/kotlin/aoc2022/Day04.kt
|
lukellmann
| 574,273,843 | false |
{"Kotlin": 175166}
|
package aoc2022
import AoCDay
// https://adventofcode.com/2022/day/4
object Day04 : AoCDay<Int>(
title = "Camp Cleanup",
part1ExampleAnswer = 2,
part1Answer = 459,
part2ExampleAnswer = 4,
part2Answer = 779,
) {
private class ElfPair(input: String) {
val sections1: IntRange
val sections2: IntRange
init {
val (s1, s2) = input.split(',', limit = 2)
fun String.toSections() = split('-', limit = 2)
.map(String::toInt)
.let { (start, end) -> start..end }
sections1 = s1.toSections()
sections2 = s2.toSections()
}
}
private fun elfPairs(input: String) = input.lineSequence().map(::ElfPair)
private operator fun <T : Comparable<T>> ClosedRange<T>.contains(other: ClosedRange<T>) =
other.isEmpty() || ((other.start >= this.start) && (other.endInclusive <= this.endInclusive))
private infix fun <T : Comparable<T>> ClosedRange<T>.overlapsWith(other: ClosedRange<T>) =
this.isEmpty() || other.isEmpty() ||
(this.start in other) || (this.endInclusive in other) ||
(other.start in this) || (other.endInclusive in this)
override fun part1(input: String) = elfPairs(input)
.count { it.sections1 in it.sections2 || it.sections2 in it.sections1 }
override fun part2(input: String) = elfPairs(input)
.count { it.sections1 overlapsWith it.sections2 }
}
| 0 |
Kotlin
| 0 | 1 |
344c3d97896575393022c17e216afe86685a9344
| 1,463 |
advent-of-code-kotlin
|
MIT License
|
src/main/kotlin/com/sk/topicWise/tree/medium/105. Construct Binary Tree from Preorder and Inorder Traversal.kt
|
sandeep549
| 262,513,267 | false |
{"Kotlin": 530613}
|
package com.sk.topicWise.tree.medium
import com.sk.topicWise.tree.TreeNode
import com.sun.source.tree.Tree
class Solution105 {
/**
* 1. traverse in preorder from left to right and pick one element e1.
* 2. find this element e1's location in inorder, divide inorder in two parts being e1 as pivot.
* 3. Make e1 as root, recur in left sub-part of inorder for left subtree and right part of inorder for right subtree.
*/
fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
return dfs(preorder, inorder, 0, 0, inorder.size)
}
private fun dfs(preorder: IntArray, inorder: IntArray, i: Int, l: Int, r: Int): TreeNode? {
if (i >= preorder.size || l > r) return null
val root = preorder[i]
var k = l
while (k < r) {
if (inorder[k] == root) break
k++
}
val node = TreeNode(root)
node.left = dfs(preorder, inorder, i + 1, l, k - 1)
node.right = dfs(preorder, inorder, i + k - l + 1, k + 1, r)
return node
}
}
| 1 |
Kotlin
| 0 | 0 |
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
| 1,063 |
leetcode-kotlin
|
Apache License 2.0
|
src/main/java/challenges/educative_grokking_coding_interview/merge_intervals/_2/InsertInterval.kt
|
ShabanKamell
| 342,007,920 | false | null |
package challenges.educative_grokking_coding_interview.merge_intervals._2
import challenges.educative_grokking_coding_interview.merge_intervals.Interval
import challenges.util.PrintHyphens
import java.util.*
object InsertInterval {
private fun insertInterval(existingIntervals: List<Interval>, newInterval: Interval) {
// Read the starting and ending time of the new interval, into separate variables
val newStart: Int = newInterval.start
val newEnd: Int = newInterval.end
println("The new interval starts at $newStart and ends at $newEnd.")
// Initialize variables to help in iterating over the existing intervals list
var i = 0
val n = existingIntervals.size
println("There are $n intervals present in the list already.")
// Initialize an empty list to store the output
val output: MutableList<Interval> = ArrayList<Interval>()
// Append all intervals that start before the new interval to the output list
println("Let's start adding these intervals into our output list one by one, until we come across an overlapping interval.")
println(PrintHyphens.repeat("-", 100))
while (i < n && existingIntervals[i].start < newStart) {
output.add(existingIntervals[i])
println("We can add " + (i + 1) + " intervals in our new list without merging any intervals yet:")
println(display(output))
i += 1
println(PrintHyphens.repeat("-", 100))
}
println()
}
private fun display(l1: List<Interval>): String {
var resultStr = "["
for (i in 0 until l1.size - 1) {
resultStr += "[" + l1[i].start.toString() + ", " + l1[i].end
.toString() + "], "
}
resultStr += "[" + l1[l1.size - 1].start.toString() + ", " + l1[l1.size - 1].end
.toString() + "]"
resultStr += "]"
return resultStr
}
@JvmStatic
fun main(args: Array<String>) {
val newInterval = Interval(5, 7)
val existingIntervals: List<Interval> =
listOf(Interval(1, 2), Interval(3, 5), Interval(6, 8))
insertInterval(existingIntervals, newInterval)
}
}
| 0 |
Kotlin
| 0 | 0 |
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
| 2,233 |
CodingChallenges
|
Apache License 2.0
|
src/main/kotlin/g1701_1800/s1723_find_minimum_time_to_finish_all_jobs/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g1701_1800.s1723_find_minimum_time_to_finish_all_jobs
// #Hard #Array #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask
// #2023_06_16_Time_167_ms_(100.00%)_Space_33.3_MB_(100.00%)
class Solution {
private var min = Int.MAX_VALUE
fun minimumTimeRequired(jobs: IntArray, k: Int): Int {
backtraking(jobs, jobs.size - 1, IntArray(k))
return min
}
private fun backtraking(jobs: IntArray, j: Int, sum: IntArray) {
val max = getMax(sum)
if (max >= min) {
return
}
if (j < 0) {
min = max
return
}
for (i in sum.indices) {
if (i > 0 && sum[i] == sum[i - 1]) {
continue
}
sum[i] += jobs[j]
backtraking(jobs, j - 1, sum)
sum[i] -= jobs[j]
}
}
private fun getMax(sum: IntArray): Int {
var max = Int.MIN_VALUE
for (j in sum) {
max = Math.max(max, j)
}
return max
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 1,036 |
LeetCode-in-Kotlin
|
MIT License
|
ejercicio4A.kt
|
salvaMsanchez
| 658,507,022 | false | null |
// Parte 1: Crea una lista “listaRandom” de 100 elementos compuesta de números aleatorios comprendidos entre el 0 y el 9.
// Imprime la lista por pantalla
// Parte 2: Crea una lista vacía “listaResultado” en cuya posición…
// Posición 0 se debe contar cuantos 0 hay en la listaRandom.
// Posición 1 se debe contar cuantos 1 hay en la listaRandom.
// etc. con todos los números.
fun main() {
var listaRandom:ArrayList<Int> = listaRandom()
imprimirListaRandom(listaRandom)
var listaResultado:ArrayList<Int> = listaResultado(listaRandom)
imprimirListaResultado(listaResultado)
println()
sumaListaResultado(listaResultado)
}
fun listaRandom() : ArrayList<Int> {
var listaRandom:ArrayList<Int> = arrayListOf()
repeat(100) {
var numRandom:Int = (0..9).random()
listaRandom.add(numRandom)
}
return listaRandom
}
fun imprimirListaRandom(listaRandom:ArrayList<Int>) {
for (num in listaRandom)
println(num)
}
fun listaResultado(listaRandom:ArrayList<Int>) : ArrayList<Int> {
var listaResultado:ArrayList<Int> = arrayListOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
for (num in listaRandom) {
when(num) {
0 -> listaResultado[0] = listaResultado[0] + 1
1 -> listaResultado[1] = listaResultado[1] + 1
2 -> listaResultado[2] = listaResultado[2] + 1
3 -> listaResultado[3] = listaResultado[3] + 1
4 -> listaResultado[4] = listaResultado[4] + 1
5 -> listaResultado[5] = listaResultado[5] + 1
6 -> listaResultado[6] = listaResultado[6] + 1
7 -> listaResultado[7] = listaResultado[7] + 1
8 -> listaResultado[8] = listaResultado[8] + 1
9 -> listaResultado[9] = listaResultado[9] + 1
}
}
return listaResultado
}
fun imprimirListaResultado(listaResultado:ArrayList<Int>) {
listaResultado.forEachIndexed { index, i ->
println("- El número $index aparece $i veces")
}
}
fun sumaListaResultado(listaResultado:ArrayList<Int>) {
var sumaTotal:Int = 0
for (num in listaResultado) {
sumaTotal = sumaTotal + num
}
println("Hay $sumaTotal números")
}
| 0 |
Kotlin
| 0 | 0 |
a2fa5b8e26d73e1602f33c2081216b8fad7725b5
| 2,198 |
curso-intro-kotlin
|
MIT License
|
baparker/17/main.kt
|
VisionistInc
| 433,099,870 | false |
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
|
import kotlin.math.abs
import kotlin.math.sqrt
var xMin = 0
var xMax = 0
var yMin = 0
var yMax = 0
fun step(curX: Int, curY: Int, tarX: Int, tarY: Int): Boolean {
val nextX = curX + tarX
val nextY = curY + tarY
if ((nextX >= xMin && nextX <= xMax) && (nextY >= yMin && nextY <= yMax)) {
return true
} else if (nextX > xMax || nextY < yMin) {
return false
}
return step(nextX, nextY, if (tarX > 0) tarX - 1 else 0, tarY - 1)
}
fun getTri(num: Int): Int {
return num * (num + 1) / 2
}
fun getTriRoot(num: Int): Int {
return sqrt(2.0 * num).toInt()
}
fun main(args: Array<String>) {
xMin = args.getOrElse(0) { "241" }.toInt()
xMax = args.getOrElse(1) { "273" }.toInt()
yMin = args.getOrElse(2) { "-97" }.toInt()
yMax = args.getOrElse(3) { "-63" }.toInt()
val maxHeight = getTri(abs(yMin)) + yMin
println("Max Height: " + maxHeight)
val maxYTraj = getTriRoot(maxHeight)
val minXTraj = getTriRoot(xMin)
val validTrajectories: MutableList<Pair<Int, Int>> = mutableListOf()
for (x in minXTraj..xMax) {
for (y in yMin..maxYTraj) {
if (step(0, 0, x, y)) {
validTrajectories.add(Pair(x, y))
}
}
}
println("Possible Trajectories: " + validTrajectories.size)
}
| 0 |
Kotlin
| 4 | 1 |
e22a1d45c38417868f05e0501bacd1cad717a016
| 1,313 |
advent-of-code-2021
|
MIT License
|
src/main/kotlin/com/github/dmstocking/levenshtein/Levenshtein.kt
|
dmstocking
| 651,298,593 | false | null |
package com.github.dmstocking.levenshtein
import kotlin.math.min
class Levenshtein(private var height: Int = 16, private var width: Int = 16) {
private var distance = Array(height) { Array(width) { 0 } }
init {
for (i in 0 until width) {
distance[i][0] = i
}
for (j in 0 until height) {
distance[0][j] = j
}
}
fun distance(a: String, b: String): Int {
val rows = a.length
val columns = b.length
growToFit(rows, columns)
for (j in 1..columns) {
for (i in 1..rows) {
val substitutionCost = if (a[i-1] == b[j-1]) 0 else 1
distance[i][j] = min(
distance[i-1][j ] + 1, // delete
distance[i ][j-1] + 1, // insert
distance[i-1][j-1] + substitutionCost // substitution
)
}
}
return distance[rows][columns]
}
private fun growToFit(rows: Int, columns: Int) {
while (width < rows + 2 || height < columns + 2) {
height *= 2
width *= 2
}
distance = Array(height) { Array(width) { 0 } }
for (i in 0 until width) {
distance[i][0] = i
}
for (j in 0 until height) {
distance[0][j] = j
}
}
}
fun min(vararg values: Int): Int {
return values.reduce { current, next -> min(current, next) }
}
| 0 |
Kotlin
| 0 | 0 |
30609663842123a360db8aa6e066c9ae1180a923
| 1,459 |
levenshtein
|
MIT License
|
src/main/kotlin/model/Board.kt
|
mihassan
| 600,617,064 | false | null |
package model
import util.Bag
import util.frequency
import util.groupContiguousBy
import util.isDistinct
import util.transpose
enum class Direction {
Horizontal,
Vertical
}
enum class Orientation {
Portrait,
Landscape
}
data class Point(val x: Int, val y: Int) {
fun moveBy(dir: Direction, steps: Int): Point = when (dir) {
Direction.Horizontal -> Point(x + steps, y)
Direction.Vertical -> Point(x, y + steps)
}
}
data class PlacedWord(val word: String, val position: Point, val direction: Direction) {
val cells: List<Point> = when (direction) {
Direction.Horizontal -> word.indices.map { Point(position.x + it, position.y) }
Direction.Vertical -> word.indices.map { Point(position.x, position.y + it) }
}
}
@Suppress("NOTHING_TO_INLINE")
data class Board(val cells: MutableMap<Point, Char> = mutableMapOf()) {
inline fun clone(): Board = Board(cells.toMutableMap())
inline fun transpose(): Board = Board(cells.mapKeys { Point(it.key.y, it.key.x) }.toMutableMap())
inline fun orient(orientation: Orientation): Board = when (orientation) {
Orientation.Portrait -> if (rowCount() < columnCount()) transpose() else this
Orientation.Landscape -> if (rowCount() > columnCount()) transpose() else this
}
inline fun letters(): Bag<Char> = cells.values.toList().frequency()
inline fun topLeft(): Point =
Point(
cells.keys.minOfOrNull(Point::x) ?: 0,
cells.keys.minOfOrNull(Point::y) ?: 0
)
inline fun bottomRight(): Point =
Point(
cells.keys.maxOfOrNull(Point::x) ?: 0,
cells.keys.maxOfOrNull(Point::y) ?: 0
)
inline fun rowCount(): Int = bottomRight().y - topLeft().y + 1
inline fun columnCount(): Int = bottomRight().x - topLeft().x + 1
inline fun xRange(): IntRange = topLeft().x..bottomRight().x
inline fun yRange(): IntRange = topLeft().y..bottomRight().y
inline fun show(): String = yRange().joinToString("\n") { y ->
xRange().map { x ->
cells[Point(x, y)] ?: ' '
}.joinToString("")
}
inline fun showAsMarkDown(): String {
val lines = lines().map { it.map { " $it " } }
val firstLine = lines[0]
val restOfTheLines = lines.drop(1)
val markdownRows = buildList {
add(firstLine)
add(firstLine.map { "---" })
addAll(restOfTheLines)
}
return markdownRows.joinToString("\n") {
it.joinToString("|", "|", "|")
}
}
inline fun lines(): List<String> = show().lines()
inline fun columns(): List<String> = lines().transpose()
inline fun grid(): List<List<String>> = lines().map { it.map { "$it" } }
fun words(minWordLength: Int): List<PlacedWord> {
val topLeftX = topLeft().x
val topLeftY = topLeft().y
fun String.wordsWithIndex(): List<Pair<String, Int>> =
withIndex()
.toList()
.groupContiguousBy { (_, c) -> c == ' ' }
.filter { it.size >= minWordLength && it.first().value != ' ' }
.map {
val word = it.map { (_, c) -> c }.joinToString("")
val idx = it.first().index
word to idx
}
fun String.wordsInRow(rowIndex: Int): List<PlacedWord> =
wordsWithIndex()
.map { (word, idx) ->
PlacedWord(word, Point(topLeftX + idx, topLeftY + rowIndex), Direction.Horizontal)
}
fun String.wordsInColumn(columnIndex: Int): List<PlacedWord> =
wordsWithIndex()
.map { (word, idx) ->
PlacedWord(word, Point(topLeftX + columnIndex, topLeftY + idx), Direction.Vertical)
}
return buildList {
lines().forEachIndexed { rowIndex, row -> addAll(row.wordsInRow(rowIndex)) }
columns().forEachIndexed { columnIndex, column -> addAll(column.wordsInColumn(columnIndex)) }
}
}
inline fun clearCells(cellsToRemove: Iterable<Point>) = cellsToRemove.forEach { cells.remove(it) }
inline fun place(letter: Char, cell: Point) = place("$letter", cell, Direction.Horizontal)
inline fun place(word: String, startCell: Point, dir: Direction): List<Point> =
buildList {
word.forEachIndexed { idx, letter ->
val cell = startCell.moveBy(dir, idx)
if (cell !in cells) {
cells[cell] = letter
add(cell)
}
}
}
inline fun canPlace(word: String, startCell: Point, dir: Direction): Boolean =
canMergeWithoutConflict(word, startCell, dir) && canPlaceNewLetter(word, startCell, dir)
inline fun canMergeWithoutConflict(word: String, startCell: Point, dir: Direction): Boolean =
word.withIndex().all { (idx, letter) ->
(cells[startCell.moveBy(dir, idx)] ?: letter) == letter
}
inline fun canPlaceNewLetter(word: String, startCell: Point, dir: Direction): Boolean =
word.indices.any { idx ->
startCell.moveBy(dir, idx) !in cells
}
inline fun isValid(
dictionary: Dictionary,
bagOfInputLetters: Bag<Char>,
allowTouchingWords: Boolean,
allowDuplicateWords: Boolean,
): Boolean =
allWordsAreValid(dictionary)
&& allLettersUsedExactlyOnce(bagOfInputLetters)
&& (allowTouchingWords || noTouchingWords())
&& (allowDuplicateWords || noDuplicateWords())
inline fun allLettersUsedExactlyOnce(bagOfInputLetters: Bag<Char>): Boolean =
bagOfInputLetters == letters()
inline fun allWordsAreValid(dictionary: Dictionary): Boolean =
words(3).all { it.word in dictionary }
inline fun noTouchingWords(): Boolean = words(2).none { it.word.length == 2 }
inline fun noDuplicateWords(): Boolean = words(3).map { it.word }.isDistinct()
inline fun getConnectedCells(point: Point, minWordLength: Int): Set<Point> =
words(minWordLength)
.filter { point in it.cells }
.flatMap { it.cells }
.toSet()
inline fun getConnectedWords(point: Point, minWordLength: Int): Set<String> =
words(minWordLength)
.filter { point in it.cells }
.map { it.word }
.toSet()
}
| 0 |
Kotlin
| 0 | 2 |
f99324e092a9eb7d9644417ac3423763059513ee
| 5,880 |
qless-solver
|
Apache License 2.0
|
src/main/kotlin/days/Day14.kt
|
poqueque
| 430,806,840 | false |
{"Kotlin": 101024}
|
package days
import kotlin.math.min
class Day14 : Day(14) {
override fun partOne(): Any {
var data = inputList[0]
val rules = mutableMapOf<String,String>()
inputList.forEach {
if (it.contains("->")){
val (a,b) = it.split(" -> ")
rules[a] = b
}
}
for (i in 1..10) {
var newData = ""
for (c in data) {
if (newData.isNotEmpty()) {
val r = ""+newData.last()+c
val c2 = rules[r]
if (c2 != null)
newData += c2
}
newData += c
}
data = newData
}
val totals = mutableMapOf<Char, Long>()
for (c in data) {
totals[c] = (totals[c] ?: 0) + 1
}
var maxC = ' '
var minC = ' '
var max = 0L
var min = 100000000L
for (t in totals.keys) {
if (totals[t]!! > max) {
max = totals[t]!!
maxC = t
}
if (totals[t]!! < min) {
min = totals[t]!!
minC = t
}
}
return max - min
}
override fun partTwo(): Any {
val data = inputList[0]
val rules = mutableMapOf<String,String>()
var pairs = mutableMapOf<String,Long>()
var chars = mutableMapOf<Char,Long>()
var pC = ' '
for (d in data) {
if (pC != ' ') {
pairs[""+pC+d] = (pairs[""+pC+d] ?: 0) +1
}
pC = d
chars[d] = (chars[d] ?: 0) +1
}
inputList.forEach {
if (it.contains("->")){
val (a,b) = it.split(" -> ")
rules[a] = b
}
}
for (i in 1..40) {
val newPairs: MutableMap<String, Long> = mutableMapOf()
pairs.forEach {
val r = rules[it.key]!!
newPairs[""+it.key[0]+r] = (newPairs[""+it.key[0]+r] ?: 0) + it.value
newPairs[""+r+it.key[1]] = (newPairs[""+r+it.key[1]] ?: 0) + it.value
chars[r[0]] = (chars[r[0]] ?: 0) + it.value
}
pairs = newPairs
}
var maxC = ' '
var minC = ' '
var max = 0L
var min = 1000000000000L
for (t in chars.keys) {
if (chars[t]!! > max) {
max = chars[t]!!
maxC = t
}
if (chars[t]!! < min) {
min = chars[t]!!
minC = t
}
}
println("$maxC -> $max")
println("$minC -> $min")
return max - min
}
}
| 0 |
Kotlin
| 0 | 0 |
4fa363be46ca5cfcfb271a37564af15233f2a141
| 2,755 |
adventofcode2021
|
MIT License
|
src/main/kotlin/com/github/kory33/kalgebra/operations/Operations.kt
|
kory33
| 135,460,140 | false | null |
package com.github.kory33.kalgebra.operations
/**
* Interface for operations which take two values of type [M] and return a value of type [M].
*
* The requirement is that for all `(x1, y1): (M, M)` and `(x2, y2): (M, M)`,
* if `x1 == x2` and `y1 == y2` then `x1 applyTo y1 == x2 applyTo y2`.
*
* This means that the values returned from an operation should be consistent.
*/
interface MagmaOperation<M>: (M, M) -> M {
/**
* Applies the operation to the pair of receiver and the given argument.
*/
infix fun M.applyTo(another: M) = this@MagmaOperation(this@applyTo, another)
}
/**
* Interface for operations which are commutative.
* That is, for all `(a, b): (M, M)`, `a applyTo b == b applyTo a`.
*/
interface CommutativeOperation<M>: MagmaOperation<M>
/**
* Interface for operations which are associative.
* That is, for all `(a, b, c): (M, M, M)`, `(a applyTo b) applyTo c == a applyTo (b applyTo c)`
*/
interface AssociativeOperation<M>: MagmaOperation<M>
/**
* Interface for operations which have an identity element `e` that satisfies the following condition:
*
* For all `a: M`, `a applyTo e == e applyTo a` and `a applyTo e == a`.
*/
interface IdentityElementOperation<M>: MagmaOperation<M> {
/**
* Identity element of the operation
*/
val identity: M
}
/**
* Interface for operations which has a property of operation of a monoid.
*/
interface MonoidOperation<M>: AssociativeOperation<M>, IdentityElementOperation<M>
/**
* Interface for commutative monoid operations.
*/
interface CommutativeMonoidOperation<M>: MonoidOperation<M>, CommutativeOperation<M>
/**
* Interface for operations which has a property of operation of a group.
*
* That is, for all `a: M`, there exists an inverse `b: M` which satisfies
* `a applyTo b == b applyTo a` and `a applyTo b == e`, where `e: M` is an identity element in the monoid.
*/
interface GroupOperation<M>: MonoidOperation<M> {
/**
* Extension property on [M] which gives an inverse on this operation
*/
val M.inverse: M
}
/**
* Interface for commutative group operations.
*/
interface AbelianGroupOperation<M>: GroupOperation<M>, CommutativeMonoidOperation<M>
| 0 |
Kotlin
| 0 | 2 |
ae2420a27ef848c13fd5728d6c5cfeae3901f905
| 2,206 |
Kalgebra
|
MIT License
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestPalindrome.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
fun interface ShortestPalindromeStrategy {
operator fun invoke(s: String): String
}
class ShortestPalindromeBruteForce : ShortestPalindromeStrategy {
override operator fun invoke(s: String): String {
val n = s.length
var len = 0
for (k in n - 1 downTo 0) {
var i = 0
var j = k
while (i < j) {
if (s[i] != s[j]) break
i++
j--
}
if (i >= j) {
len = k
break
}
}
val sb = java.lang.StringBuilder()
for (i in n - 1 downTo len + 1) {
sb.append(s[i])
}
sb.append(s)
return sb.toString()
}
}
class ShortestPalindromeTwoPointers : ShortestPalindromeStrategy {
override operator fun invoke(s: String): String {
var str = s
var i = 0
var j = str.length - 1
while (i < j) {
val ith = str[i]
val jth = str[j]
if (ith == jth) {
i++
j--
} else {
str = str.substring(0, i) + jth + str.substring(i)
i++
}
}
return str
}
}
class ShortestPalindromeMP : ShortestPalindromeStrategy {
override operator fun invoke(s: String): String {
val temp = s + "#" + StringBuilder(s).reverse().toString()
val table = getTable(temp)
return StringBuilder(s.substring(table[table.size - 1])).reverse().toString() + s
}
private fun getTable(s: String): IntArray {
// get lookup table
val table = IntArray(s.length)
// pointer that points to matched char in prefix part
var index = 0
// skip index 0, we will not match a string with itself
for (i in 1 until s.length) {
if (s[index] == s[i]) {
// we can extend match in prefix and postfix
table[i] = table[i - 1] + 1
index++
} else {
// match failed, we try to match a shorter substring
// by assigning index to table[i-1], we will shorten the match string length, and jump to the
// prefix part that we used to match postfix ended at i - 1
index = table[i - 1]
while (index > 0 && s[index] != s[i]) {
// we will try to shorten the match string length until we revert to the beginning of
// match (index 1)
index = table[index - 1]
}
// when we are here may either found a match char or we reach the boundary and still no luck
// so we need check char match
if (s[index] == s[i]) {
// if match, then extend one char
index++
}
table[i] = index
}
}
return table
}
}
| 4 |
Kotlin
| 0 | 19 |
776159de0b80f0bdc92a9d057c852b8b80147c11
| 3,617 |
kotlab
|
Apache License 2.0
|
src/Day04.kt
|
Shykial
| 572,927,053 | false |
{"Kotlin": 29698}
|
fun main() {
fun part1(input: List<String>) = input.count { line ->
line.cutExcluding(",")
.map { it.parseIntRange() }
.let { it.first hasFullOverlapWith it.second }
}
fun part2(input: List<String>) = input.count { line ->
line.cutExcluding(",")
.map { it.parseIntRange() }
.let { it.first hasAnyOverlapWith it.second }
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun String.parseIntRange() = cutExcluding("-").let { it.first.toInt()..it.second.toInt() }
private infix fun <T> Iterable<T>.hasFullOverlapWith(other: Iterable<T>): Boolean {
val firstSet = this.toSet()
val secondSet = other.toSet()
return firstSet.containsAll(secondSet) || secondSet.containsAll(firstSet)
}
private infix fun <T> Iterable<T>.hasAnyOverlapWith(other: Iterable<T>): Boolean =
(this.toSet() intersect other.toSet()).isNotEmpty()
| 0 |
Kotlin
| 0 | 0 |
afa053c1753a58e2437f3fb019ad3532cb83b92e
| 964 |
advent-of-code-2022
|
Apache License 2.0
|
day07/src/Day07.kt
|
simonrules
| 491,302,880 | false |
{"Kotlin": 68645}
|
import java.io.File
import kotlin.math.absoluteValue
class Day07(path: String) {
private var positions = mutableListOf<Int>()
private var fuelCost = mutableListOf<Int>()
init {
val lines = File(path).readLines()
val items = lines[0].split(',')
items.forEach { positions.add(it.toInt()) }
positions.sort()
fuelCost.add(0)
fuelCost.add(1)
for (i in 2 until 9999) {
fuelCost.add(fuelCost[i - 1] + i)
}
}
fun part1(): Int {
var minFuel = 999999
//var minFuelPos = -1
val left = positions.first()
val right = positions.last()
for (i in left..right) {
var fuel = 0
positions.forEach {
fuel += (i - it).absoluteValue
}
if (fuel < minFuel) {
minFuel = fuel
//minFuelPos = i
}
}
return minFuel
}
fun part2(): Int {
var minFuel = 999999999
//var minFuelPos = -1
val left = positions.first()
val right = positions.last()
for (i in left..right) {
var fuel = 0
positions.forEach {
fuel += fuelCost[(i - it).absoluteValue]
}
if (fuel < minFuel) {
minFuel = fuel
//minFuelPos = i
}
}
return minFuel
}
}
fun main(args: Array<String>) {
val aoc = Day07("day07/input.txt")
//println(aoc.part1())
println(aoc.part2())
}
| 0 |
Kotlin
| 0 | 0 |
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
| 1,564 |
aoc2021
|
Apache License 2.0
|
src/main/kotlin/se/brainleech/adventofcode/aoc2022/Aoc2022Day06.kt
|
fwangel
| 435,571,075 | false |
{"Kotlin": 150622}
|
package se.brainleech.adventofcode.aoc2022
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
class Aoc2022Day06 {
private fun process(input: String, packetSize: Int) : Int {
if (input.length < packetSize) return -1
return input
.asSequence()
.windowed(size = packetSize, partialWindows = false)
.withIndex()
.filter { it.value.distinct().size == packetSize }
.map { it.index + packetSize }
.first()
}
fun part1(input: String) : Int { return process(input, packetSize = 4) }
fun part2(input: String) : Int { return process(input, packetSize = 14) }
}
fun main() {
val solver = Aoc2022Day06()
val prefix = "aoc2022/aoc2022day06"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
listOf(7, 5, 6, 10, 11).forEachIndexed { index, expected -> verify(expected, solver.part1(testData[index])) }
compute({ solver.part1(realData.first()) }, "$prefix.part1 = ")
listOf(19, 23, 23, 29, 26).forEachIndexed { index, expected -> verify(expected, solver.part2(testData[index])) }
compute({ solver.part2(realData.first()) }, "$prefix.part2 = ")
}
| 0 |
Kotlin
| 0 | 0 |
0bba96129354c124aa15e9041f7b5ad68adc662b
| 1,291 |
adventofcode
|
MIT License
|
src/main/kotlin/day3.kt
|
Arch-vile
| 572,557,390 | false |
{"Kotlin": 132454}
|
package day3
import aoc.utils.intersect
import aoc.utils.readInput
import aoc.utils.splitMiddle
fun part1(): Int {
return readInput("day3-input.txt")
.map { it.toCharArray().toList() }
.map { it.splitMiddle()}
.map { it.first.intersect(it.second) }
.map { it.first() }
.sumOf { priority(it) }
}
fun part2(): Int {
return readInput("day3-input.txt")
.map { it.toCharArray().toList() }
.windowed(3,3)
.map{ intersect(it) }
.map { it.first() }
.sumOf { priority(it) }
}
fun priority(it: Char): Int {
val v = it.toInt()
if(v < 97) {
return v - 38
} else {
return v - 96
}
}
| 0 |
Kotlin
| 0 | 0 |
e737bf3112e97b2221403fef6f77e994f331b7e9
| 697 |
adventOfCode2022
|
Apache License 2.0
|
year2022/src/cz/veleto/aoc/year2022/Day16.kt
|
haluzpav
| 573,073,312 | false |
{"Kotlin": 164348}
|
package cz.veleto.aoc.year2022
import cz.veleto.aoc.core.AocDay
class Day16(config: Config) : AocDay(config) {
private val inputRegex = Regex("""^Valve ([A-Z]+) has flow rate=([0-9]+); tunnels? leads? to valves? (.+)$""")
override fun part1(): String {
val valves = parseValves()
val startValve = valves.first { it.name == "AA" }
var paths = listOf(
Path(
actions = listOf(Action.Move(from = startValve, to = startValve)),
releasedPressure = 0,
)
)
val minutes = 30
for (minute in 1..minutes) {
if (config.log) println("Minute $minute, considering ${paths.size} paths")
paths = paths.flatMap { path ->
val openValves = path.actions.filterIsInstance<Action.OpenValve>().map { it.valve }
val newPressure = path.releasedPressure + openValves.sumOf { it.flow }
val currentValve = path.actions.filterIsInstance<Action.Move>().last().to
val canOpenCurrentValve = currentValve !in openValves && currentValve.flow > 0
val justCameFrom = path.actions.last().let { if (it is Action.Move) it.from else null }
buildList {
for (leadsToIndex in currentValve.leadsTo) {
val leadsToValve = valves[leadsToIndex]
if (leadsToValve == justCameFrom) continue
this += Path(
actions = path.actions + Action.Move(from = currentValve, to = leadsToValve),
releasedPressure = newPressure
)
}
if (canOpenCurrentValve) {
this += Path(
actions = path.actions + Action.OpenValve(currentValve),
releasedPressure = newPressure,
)
}
}
}
if (minute > 5) {
// totally legit pruning 👌 😅
val maxPressure = paths.maxOf { it.releasedPressure }
paths = paths.filter { it.releasedPressure > maxPressure / 2 }
}
}
return paths.maxOf { it.releasedPressure }.toString()
}
override fun part2(): String {
val valves = parseValves()
val startValve = valves.first { it.name == "AA" }
var actionNodes = listOf(
ActionNodePair(
me = ActionNode(action = ActionNode.Action.Move, from = null, valve = startValve),
elephant = ActionNode(action = ActionNode.Action.Move, from = null, valve = startValve),
releasedPressure = 0,
),
)
val minutes = 26
for (minute in 1..minutes) {
if (config.log) println("Minute $minute, considering ${actionNodes.size} nodes")
actionNodes = actionNodes.flatMap { actionNodePair ->
val openValves: List<Valve> = buildList {
var n: ActionNode? = actionNodePair.me
while (n != null) {
if (n.action == ActionNode.Action.Open) this += n.valve
n = n.from
}
n = actionNodePair.elephant
while (n != null) {
if (n.action == ActionNode.Action.Open) this += n.valve
n = n.from
}
}
val newPressure = actionNodePair.releasedPressure + openValves.sumOf { it.flow }
buildList {
val appendableActorActionNodes: List<List<ActionNode>> = listOf(
actionNodePair.me,
actionNodePair.elephant
).map { actionNode ->
buildList {
val currentValve = listOf(actionNode, actionNode.from)
.firstNotNullOf { if (it?.action == ActionNode.Action.Move) it.valve else null }
val canOpenCurrentValve = currentValve !in openValves && currentValve.flow > 0
val justCameFrom = actionNode.from?.valve
for (leadsToIndex in currentValve.leadsTo) {
val leadsToValve = valves[leadsToIndex]
if (leadsToValve == justCameFrom) continue
this += ActionNode(action = ActionNode.Action.Move, from = actionNode, valve = leadsToValve)
}
if (canOpenCurrentValve) this += ActionNode(
action = ActionNode.Action.Open,
from = actionNode,
valve = currentValve,
)
}
}
for (myActionNode in appendableActorActionNodes[0]) {
for (elephantActionNode in appendableActorActionNodes[1]) {
val bothOpeningSameValve = myActionNode.action == ActionNode.Action.Open
&& elephantActionNode.action == ActionNode.Action.Open
&& myActionNode.valve == elephantActionNode.valve
if (bothOpeningSameValve) continue
this += ActionNodePair(
me = myActionNode,
elephant = elephantActionNode,
releasedPressure = newPressure,
)
}
}
}
}
if (minute > 5) {
// totally legit pruning 👌 😅 I totally not spend an hour tuning 🤣
val maxPressure = actionNodes.maxOf { it.releasedPressure }
val minPressureToPassCoef = (0.03 * minute + 0.35).coerceIn(0.0..0.82)
val minPressureToPass = maxPressure * minPressureToPassCoef
actionNodes = actionNodes.filter { it.releasedPressure > minPressureToPass }
if (config.log) println("\tpruned with coef $minPressureToPassCoef")
}
}
return actionNodes.maxOf { it.releasedPressure }.toString()
}
private fun parseValves(): List<Valve> = input.map { line ->
val (name, flow, leadsTos) = inputRegex.matchEntire(line)!!.destructured
Valve(
name = name,
flow = flow.toInt(),
) to leadsTos.split(", ")
}.toMap().let { valvesToLeadsToNames ->
valvesToLeadsToNames.keys.map { valve ->
valve.copy(
leadsTo = valvesToLeadsToNames[valve]!!.map { leadsToName ->
valvesToLeadsToNames.keys.indexOfFirst { it.name == leadsToName }
},
)
}
}
private data class Valve(
val name: String,
val flow: Int,
val leadsTo: List<Int> = emptyList(),
)
private sealed interface Action {
data class Move(
val from: Valve,
val to: Valve,
) : Action {
override fun toString(): String = "move to ${to.name}"
}
data class OpenValve(
val valve: Valve,
) : Action {
override fun toString(): String = "open ${valve.name}"
}
}
private data class Path(
val actions: List<Action>,
val releasedPressure: Int,
)
private data class ActionNode(
val action: Action,
val from: ActionNode?,
val valve: Valve,
) {
override fun toString(): String = when (action) {
Action.Move -> "move to ${valve.name}"
Action.Open -> "open ${valve.name}"
}
enum class Action {
Move, Open
}
}
private data class ActionNodePair(
val me: ActionNode,
val elephant: ActionNode,
val releasedPressure: Int,
)
}
| 0 |
Kotlin
| 0 | 1 |
32003edb726f7736f881edc263a85a404be6a5f0
| 8,169 |
advent-of-pavel
|
Apache License 2.0
|
src/Day12.kt
|
floblaf
| 572,892,347 | false |
{"Kotlin": 28107}
|
fun main() {
data class Coordinate(
val value: Char,
val x: Int,
val y: Int,
var d1: Int = 0,
var d2: Int = 0
) {
fun canAccess(coordinate: Coordinate): Boolean {
return coordinate.value - this.value <= 1
}
}
val input = readInput("Day12")
.map { it.toList() }
lateinit var start: Coordinate
lateinit var end: Coordinate
val width = input[0].size
val height = input.size
val grid = MutableList(height) { mutableListOf<Coordinate>() }
input.forEachIndexed { i, chars ->
chars.forEachIndexed { j, c ->
grid[i].add(Coordinate(
value = when (c) {
'S' -> 'a'
'E' -> 'z'
else -> c
},
x = i,
y = j
).also {
when (c) {
'S' -> start = it
'E' -> end = it
}
})
}
}
fun getAccessibleCoordinates(coordinate: Coordinate): List<Coordinate> {
val x = coordinate.x
val y = coordinate.y
return buildList {
if (x >= 1) add(grid[x - 1][y])
if (x < height - 1) add(grid[x + 1][y])
if (y >= 1) add(grid[x][y - 1])
if (y < width - 1) add(grid[x][y + 1])
}.filter { coordinate.canAccess(it) }
}
fun search(starts: List<Coordinate>, end: Coordinate, distanceOperation: (current : Coordinate, previous: Coordinate) -> Unit) {
val queue = ArrayDeque(starts)
val visited = mutableListOf(*starts.toTypedArray())
while(queue.isNotEmpty()) {
val current = queue.removeFirst()
getAccessibleCoordinates(current)
.filter { it !in visited }
.forEach {
distanceOperation.invoke(it, current)
visited.add(it)
if (it == end) {
return
}
queue.addLast(it)
}
}
}
search(listOf(start), end) { current, previous -> current.d1 = previous.d1 + 1 }
search(listOf(start) + grid.flatten().filter { it.value == 'a' }, end) { current, previous -> current.d2 = previous.d2 + 1 }
println(end.d1)
println(end.d2)
}
| 0 |
Kotlin
| 0 | 0 |
a541b14e8cb401390ebdf575a057e19c6caa7c2a
| 2,376 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/arrays/NumberOfIslands.kt
|
ghonix
| 88,671,637 | false | null |
package arrays
import java.util.LinkedList
import java.util.Queue
class NumberOfIslands {
data class Coordinate(val row: Int, val col: Int)
fun numIslands(grid: Array<CharArray>): Int {
val visited = HashSet<Coordinate>()
var islandsFound = 0
for (row in grid.indices) {
for (col in grid[row].indices) {
val current = grid[row][col]
if (current == '0' || visited.contains(Coordinate(row, col))) {
continue
}
exploreIterative(grid, row, col, visited)
islandsFound++
}
}
return islandsFound
}
private fun exploreRecursive(grid: Array<CharArray>, row: Int, col: Int, visited: java.util.HashSet<Coordinate>) {
if (visited.contains(Coordinate(row, col))) {
return
}
visited.add(Coordinate(row, col))
val dr = arrayOf(0, 1, 0, -1)
val dc = arrayOf(1, 0, -1, 0)
for (i in dr.indices) {
val newRow = row + dr[i]
val newCol = col + dc[i]
if (isValid(grid, newRow, newCol)) {
exploreRecursive(grid, newRow, newCol, visited)
}
}
}
private fun exploreIterative(grid: Array<CharArray>, row: Int, col: Int, visited: java.util.HashSet<Coordinate>) {
val queue: Queue<Coordinate> = LinkedList()
queue.add(Coordinate(row, col))
while (queue.isNotEmpty()) {
val current = queue.poll()
if (visited.contains(current)) {
continue
}
visited.add(current)
val dr = arrayOf(0, 1, 0, -1)
val dc = arrayOf(1, 0, -1, 0)
for (i in dr.indices) {
val newRow = current.row + dr[i]
val newCol = current.col + dc[i]
if (isValid(grid, newRow, newCol)) {
queue.add(Coordinate(newRow, newCol))
}
}
}
}
private fun isValid(grid: Array<CharArray>, row: Int, col: Int): Boolean {
return row >= 0 && row < grid.size && col >= 0 && col < grid[row].size && grid[row][col] == '1'
}
}
fun main() {
println(
NumberOfIslands().numIslands(
arrayOf(
charArrayOf('1', '1', '0', '0', '0'),
charArrayOf('1', '1', '0', '0', '0'),
charArrayOf('0', '0', '1', '0', '0'),
charArrayOf('0', '0', '0', '1', '1')
)
)
)
}
| 0 |
Kotlin
| 0 | 2 |
25d4ba029e4223ad88a2c353a56c966316dd577e
| 2,629 |
Problems
|
Apache License 2.0
|
src/main/kotlin/days/Day3.kt
|
MaciejLipinski
| 317,582,924 | true |
{"Kotlin": 60261}
|
package days
class Day3 : Day(3) {
override fun partOne(): Any {
val tobogganMap = inputList.map { mapLineFrom(it) }
val width = tobogganMap[0].size
var treeCount = 0
for (i in tobogganMap.indices) {
val y = i
val x =
if (i == 0) {
0
} else if (3 * i < width) {
3 * i
} else {
(3 * i).rem(width)
}
if (tobogganMap[y][x]) treeCount++
}
return treeCount
}
override fun partTwo(): Any {
val tobogganMap = inputList.map { mapLineFrom(it) }
val width = tobogganMap[0].size
val pathsYX = listOf(1 to 1, 1 to 3, 1 to 5, 1 to 7, 2 to 1)
var treeCount = 0
var result = 1L
for (path in pathsYX) {
val yStep = path.first
val xStep = path.second
for (i in tobogganMap.indices step yStep) {
val y = i
val x =
if (i == 0) {
0
} else if (xStep * i < width) {
if (xStep >= yStep) {
xStep * i
} else {
xStep * i / yStep
}
} else {
(if (xStep >= yStep) {
xStep * i
} else {
xStep * i / yStep
}).rem(width)
}
if (tobogganMap[y][x]) treeCount++
}
result *= treeCount
treeCount = 0
}
return result
}
private fun mapLineFrom(inputLine: String) = inputLine.map { it == '#' }
}
| 0 |
Kotlin
| 0 | 0 |
1c3881e602e2f8b11999fa12b82204bc5c7c5b51
| 1,921 |
aoc-2020
|
Creative Commons Zero v1.0 Universal
|
01/src/commonMain/kotlin/Main.kt
|
daphil19
| 725,415,769 | false |
{"Kotlin": 131380}
|
expect fun getLines(inputOrPath: String): List<String>
fun main() {
val lines = getLines(INPUT_FILE)
part1(lines)
part2(lines)
}
fun part1(lines: List<String>) {
println(lines.map { line -> line.toCharArray().filter { it.isDigit() } }
.sumOf { "${it.first()}${it.last()}".toLong() })
}
fun part2(lines: List<String>) {
val numbers = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9",
)
val r = Regex("(?=(one|two|three|four|five|six|seven|eight|nine|[0-9]))")
println(lines.sumOf { line ->
// find all the matches that exist in the line
// since we are using a lookahead, we get nested arrays and blank values
// flatMap handles the arrays, filter the values
val matches = r.findAll(line).flatMap { it.groupValues }.filter { it.isNotBlank() }
val first = matches.first().let { numbers[it] ?: it }
val last = matches.last().let { numbers[it] ?: it }
"$first$last".toLong()
})
}
| 0 |
Kotlin
| 0 | 0 |
70646b330cc1cea4828a10a6bb825212e2f0fb18
| 1,145 |
advent-of-code-2023
|
Apache License 2.0
|
src/Day01.kt
|
Xacalet
| 576,909,107 | false |
{"Kotlin": 18486}
|
/**
* ADVENT OF CODE 2022 (https://adventofcode.com/2022/)
*
* Solution to day 1 (https://adventofcode.com/2022/day/1)
*
*/
fun main() {
data class Elf(val calories: List<Int>)
fun part1(elves: List<Elf>): Int {
return elves.maxOfOrNull { it.calories.sum() } ?: 0
}
fun part2(elves: List<Elf>): Int {
return elves.map { it.calories.sum() }.sortedDescending().take(3).sum()
}
val elves = readInput("day01_dataset").split("\n\n").map { line ->
Elf(line.split("\n").map(Integer::parseInt))
}
part1(elves).println()
part2(elves).println()
}
| 0 |
Kotlin
| 0 | 0 |
5c9cb4650335e1852402c9cd1bf6f2ba96e197b2
| 608 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/io/tree/BinarySearchTreeFromPreOrderTraversal.kt
|
jffiorillo
| 138,075,067 | false |
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
|
package io.tree
import io.models.TreeNode
import io.utils.runTests
class BinarySearchTreeFromPreOrderTraversal {
fun execute(A: IntArray, bound: Int = Int.MAX_VALUE, index: Int = 0): Pair<Int, TreeNode?> {
if (index == A.size || A[index] > bound) return index to null
val root = TreeNode(A[index])
val (newIndex, treeNode) = execute(A, root.`val`, index + 1)
root.left = treeNode
val (rightIndex, right) = execute(A, bound, newIndex)
root.right = right
return rightIndex to root
}
fun executeAnotherApproach(input: IntArray): TreeNode? =
if (input.isEmpty()) null else TreeNode(input.first()).also { create(input, it, it, 1, false) }
private fun create(input: IntArray, node: TreeNode, father: TreeNode, index: Int, isRightRoot: Boolean): Int = when {
index == input.size -> index
input[index] < node.`val` -> {
val rightIndex = create(input, TreeNode(input[index]).also { node.left = it }, node, index + 1, isRightRoot)
create(input, node, father, rightIndex, isRightRoot)
}
node == father -> create(input, TreeNode(input[index]).also { node.right = it }, father, index + 1, isRightRoot || node == father)
node.`val` < father.`val` && input[index] > father.`val` -> index
else -> create(input, TreeNode(input[index]).also { node.right = it }, father, index + 1, isRightRoot || node == father)
}
}
fun main() {
runTests(listOf(
intArrayOf(8, 5, 1, 7, 10, 12) to
TreeNode(8,
left = TreeNode(5, TreeNode(1), TreeNode(7)),
right = TreeNode(10, right = TreeNode(12))),
intArrayOf(8) to TreeNode(8),
intArrayOf(8, 15, 10, 17) to
TreeNode(8,
right = TreeNode(15,
left = TreeNode(10), right = TreeNode(17))),
intArrayOf(15, 13, 12, 18) to
TreeNode(15,
left = TreeNode(13, left = TreeNode(12)),
right = TreeNode(18))
)) { (input, value) -> value to BinarySearchTreeFromPreOrderTraversal().execute(input).second }
}
| 0 |
Kotlin
| 0 | 0 |
f093c2c19cd76c85fab87605ae4a3ea157325d43
| 2,040 |
coding
|
MIT License
|
src/main/kotlin/dev/shtanko/algorithms/exercises/MaxPowerOfTwo.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.exercises
import kotlin.math.pow
/**
* Greatest power of two
*/
class MaxPowerOfTwo {
/**
* @param n the number.
*/
fun perform(n: Int): Int {
val powers = getPowers()
if (n == 0) return 0
if (powers.contains(n)) {
return n
}
for (p in 1 until powers.size) {
if (n < powers[p]) {
return powers[p - 1]
}
}
return 0
}
/**
* Decompose [n] into the sum of powers of 2
* @param n the number.
*/
fun decompose(n: Int): List<Int> {
val data = mutableListOf<Int>()
var j = n
while (j != 0) {
val powerOf2 = MaxPowerOfTwo().perform(j)
data.add(powerOf2)
j -= powerOf2
}
return data
}
}
fun getPowers(power: Double = 2.0): List<Int> {
val powers = mutableListOf<Int>()
var value: Int
var i = 0
while (true) {
value = power.pow(i).toInt()
if (value >= Int.MAX_VALUE) {
break
}
powers.add(value)
i++
}
return powers
}
| 4 |
Kotlin
| 0 | 19 |
776159de0b80f0bdc92a9d057c852b8b80147c11
| 1,754 |
kotlab
|
Apache License 2.0
|
src/main/kotlin/org/eln2/mc/data/SegmentTree.kt
|
age-series
| 248,378,503 | false |
{"Kotlin": 641936}
|
package org.eln2.mc.data
/**
* Represents the numeric range of a segment.
* @param min The lower boundary of this segment.
* @param max The upper boundary of this segment.
* [min] must be smaller than [max].
* */
data class ClosedInterval(val min: Double, val max: Double) {
val range get() = min..max
init {
if (min >= max) {
error("Invalid interval $min -> $max")
}
}
fun contains(point: Double) = point in range
}
data class SegmentTreeNode<T>(
val range: ClosedInterval,
val data: T?,
private val l: SegmentTreeNode<T>?,
private val r: SegmentTreeNode<T>?,
) {
constructor(range: ClosedInterval, segment: T?) : this(range, segment, null, null)
/**
* @return True if this segment's [range] contains the [point]. Otherwise, false.
* */
fun contains(point: Double): Boolean {
return range.contains(point)
}
/**
* Recursively queries until a leaf node containing [point] is found.
* @param point A point contained within a segment. If this segment does not contain the point, an error will be produced.
* @return The data value associated with the leaf node that contains [point]. An error will be produced if segment continuity is broken (parent contains point but the child nodes do not).
* */
fun query(point: Double): T? {
if (!contains(point)) {
return null
}
val left = l
val right = r
if (left != null && left.contains(point)) {
return left.query(point)
}
if (right != null && right.contains(point)) {
return right.query(point)
}
return data
}
}
class SegmentTree<T>(private val root: SegmentTreeNode<T>) {
fun queryOrNull(point: Double): T? {
if (!root.contains(point)) {
return null
}
return root.query(point)
}
/**
* Finds the segment with the specified range. Time complexity is O(log n)
* */
fun query(point: Double): T {
return root.query(point) ?: error("$point not found")
}
}
class SegmentTreeBuilder<TSegment> {
private data class PendingSegment<T>(val segment: T, val range: ClosedInterval)
private val pending = ArrayList<PendingSegment<TSegment>>()
/**
* Inserts a segment into the pending set. If its range is not sorted with the previously inserted segments,
* [sort] must be called before attempting to [build].
* */
fun insert(segment: TSegment, range: ClosedInterval) {
pending.add(PendingSegment(segment, range))
}
/**
* Sorts the segments by range.
* */
fun sort() {
pending.sortBy { it.range.min }
}
/**
* Builds a [SegmentTree] from the pending set.
* If segment continuity is broken, an error will be produced.
* */
fun build(): SegmentTree<TSegment> {
if (pending.isEmpty()) {
error("Tried to build empty segment tree")
}
/* if (pending.size > 1) {
for (i in 1 until pending.size) {
val previous = pending[i - 1]
val current = pending[i]
if (previous.range.max != current.range.min) {
error("Segment tree continuity error")
}
}
}*/
return SegmentTree(buildSegment(0, pending.size - 1))
}
private fun buildSegment(leftIndex: Int, rightIndex: Int): SegmentTreeNode<TSegment> {
if (leftIndex == rightIndex) {
val data = pending[leftIndex]
return SegmentTreeNode(data.range, data.segment)
}
val mid = leftIndex + (rightIndex - leftIndex) / 2
return SegmentTreeNode(
ClosedInterval(pending[leftIndex].range.min, pending[rightIndex].range.max),
data = null,
l = buildSegment(leftIndex, mid),
r = buildSegment(mid + 1, rightIndex)
)
}
}
| 49 |
Kotlin
| 20 | 53 |
86d843f49c3e23cba8ad256d45476069bf1459dd
| 3,987 |
ElectricalAge2
|
MIT License
|
src/main/kotlin/me/grison/aoc/y2016/Day03.kt
|
agrison
| 315,292,447 | false |
{"Kotlin": 267552}
|
package me.grison.aoc.y2016
import me.grison.aoc.*
class Day03 : Day(3, 2016) {
override fun title() = "Squares With Three Sides"
override fun partOne() = triangles(inputList.map { it.allInts() })
override fun partTwo() = inputList.map { it.allInts() }.let { h ->
val vertical = listOf(h.map { it[0] } + h.map { it[1] } + h.map { it[2] })
triangles(vertical, true)
}
private fun validTriangle(sides: List<Int>): Boolean {
val (a, b, c) = sides.sorted()
return a + b > c
}
private fun triangles(candidates: List<List<Int>>, part2: Boolean = false): Int {
return when (part2) {
false -> candidates.count { validTriangle(it) }
else -> {
val flattened = candidates.flatten()
(0 until (flattened.size - 2) step 3)
.map { flattened.subList(it, it + 3) }.count { validTriangle(it) }
}
}
}
}
| 0 |
Kotlin
| 3 | 18 |
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
| 958 |
advent-of-code
|
Creative Commons Zero v1.0 Universal
|
LeetCode/Maximum Compatibility Score Sum/main.kt
|
thedevelopersanjeev
| 112,687,950 | false | null |
import kotlin.math.max
class Solution {
var students = Array(0) { IntArray(0) }
var mentors = Array(0) { IntArray(0) }
var dp = IntArray(257) { -1 }
fun solve(i: Int, mask: Int): Int {
if (i == students.size) return 0
if (dp[mask] != -1) return dp[mask]
var (ans, one) = listOf(0, 1)
for (j in students.indices) {
if (mask.and(one.shl(j)) == 0) {
var curr = 0
for (k in students[0].indices) {
if (students[i][k] == mentors[j][k]) ++curr
}
ans = max(ans, curr + solve(i + 1, mask.or(one.shl(j))))
}
}
dp[mask] = ans
return ans
}
fun maxCompatibilitySum(s: Array<IntArray>, m: Array<IntArray>): Int {
students = s
mentors = m
dp = IntArray(257) { -1 }
return solve(0, 0)
}
}
| 0 |
C++
| 58 | 146 |
610520cc396fb13a03c606b5fb6739cfd68cc444
| 899 |
Competitive-Programming
|
MIT License
|
command-channel/src/main/kotlin/dev/gimme/command/channel/manager/commandcollection/CommandCollection.kt
|
gimme
| 315,114,245 | false |
{"Kotlin": 143111, "Java": 18235}
|
package dev.gimme.command.channel.manager.commandcollection
import dev.gimme.command.Command
import dev.gimme.command.CommandSearchResult
/**
* Represents a collection of commands.
*/
interface CommandCollection : Collection<Command<*>> {
/** Returns all commands in this collection. */
val commands: Set<Command<*>>
/** Adds the given [command] to this collection. */
fun add(command: Command<*>)
/** Adds the given [commands] to this collection. */
fun addAll(commands: Iterable<Command<*>>) = commands.forEach(this::add)
/**
* Returns the command from this collection at the [path], or null if no command at that [path] was found.
*/
fun get(path: List<String>): Command<*>?
/** Returns if this collection contains a command at the [path]. */
fun contains(path: List<String>): Boolean = get(path) != null
/**
* Searches for the command or node with the longest matching sub-set from the start of the [path] and returns the
* result.
*/
fun find(path: List<String>): CommandSearchResult
override fun iterator(): Iterator<Command<*>> = commands.iterator()
override val size: Int get() = commands.size
override fun isEmpty(): Boolean = commands.isEmpty()
override fun contains(element: Command<*>): Boolean = commands.contains(element)
override fun containsAll(elements: Collection<Command<*>>): Boolean = commands.containsAll(elements)
}
| 0 |
Kotlin
| 0 | 0 |
66557fea569474ca2dc5b0135e5df669160db35a
| 1,447 |
command
|
MIT License
|
src/main/kotlin/g0701_0800/s0756_pyramid_transition_matrix/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g0701_0800.s0756_pyramid_transition_matrix
// #Medium #Depth_First_Search #Breadth_First_Search #Bit_Manipulation
// #2023_03_07_Time_268_ms_(100.00%)_Space_34.2_MB_(100.00%)
class Solution {
private fun dfs(c: CharArray, i: Int, l: Int, map: Array<IntArray>): Boolean {
if (l == 1) {
return true
}
if (i == l - 1) {
return dfs(c, 0, l - 1, map)
}
val save = c[i]
var p = 'A'
var v = map[c[i].code - 'A'.code][c[i + 1].code - 'A'.code]
while (v != 0) {
if (v and 1 != 0) {
c[i] = p
if (dfs(c, i + 1, l, map)) {
return true
}
}
v = v shr 1
p++
}
c[i] = save
return false
}
fun pyramidTransition(bottom: String, allowed: List<String>): Boolean {
val map = Array(7) { IntArray(7) }
for (s in allowed) {
map[s[0].code - 'A'.code][s[1].code - 'A'.code] =
map[s[0].code - 'A'.code][s[1].code - 'A'.code] or (1 shl s[2].code - 'A'.code)
}
return dfs(bottom.toCharArray(), 0, bottom.length, map)
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 1,207 |
LeetCode-in-Kotlin
|
MIT License
|
src/main/kotlin/days/Day2Solution.kt
|
yigitozgumus
| 434,108,608 | false |
{"Kotlin": 17835}
|
package days
import BaseSolution
import java.io.File
const val FORWARD = "forward"
const val DOWN = "down"
const val UP = "up"
data class Command(val direction: String, val amount: Int)
data class Location(var horizontal: Int, var depth: Int)
data class LocationWithAim(var aim: Int, var horizontal: Int, var depth: Int)
fun Location.updateLocation(command: Command) {
when(command.direction) {
FORWARD -> this.horizontal += command.amount
DOWN -> this.depth += command.amount
UP -> this.depth -= command.amount
}
}
fun LocationWithAim.updateLocation(command: Command) {
when(command.direction) {
FORWARD -> {
this.horizontal += command.amount
this.depth += this.aim * command.amount
}
UP -> this.aim -= command.amount
DOWN -> this.aim += command.amount
}
}
class Day2Solution(inputList: List<String>): BaseSolution(inputList) {
private fun createCommandList() = inputList
.map { it.split(" ") }
.map { Command(it[0], it[1].toInt()) }
override fun part1() {
val commandList = createCommandList()
val location = Location(0,0)
commandList.forEach { location.updateLocation(it) }
println(location.depth * location.horizontal)
}
override fun part2() {
val location = LocationWithAim(0,0,0)
createCommandList().forEach { location.updateLocation(it) }
println(location.depth * location.horizontal)
}
}
| 0 |
Kotlin
| 0 | 0 |
c0f6fc83fd4dac8f24dbd0d581563daf88fe166a
| 1,493 |
AdventOfCode2021
|
MIT License
|
Stage_5/src/main/kotlin/Main.kt
|
rafaelnogueiradev
| 670,374,961 | false | null |
package cinema
const val STANDARD: Int = 10
const val DISCOUNT: Int = 8
const val B_SYMBOL: Char = 'B'
const val S_SYMBOL: Char = 'S'
const val SMALL_ROOM: Int = 60
enum class Cinema(var number: Int) {
ROW(7), SEATS(8),
TOTAL_SEATS(ROW.number * SEATS.number),
SELECT_ROW(0), SELECT_SEAT(0),
PURCHASED_TICKET(0), CURRENT_INCOME(0),
TOTAL_INCOME(0),
}
var mappingSeats = MutableList(Cinema.ROW.number) { MutableList(Cinema.SEATS.number) { S_SYMBOL } }
fun userInput() {
println("Enter the number of rows:")
Cinema.ROW.number = readln().toInt()
println("Enter the number of seats in each row:")
Cinema.SEATS.number = readln().toInt()
Cinema.TOTAL_SEATS.number = Cinema.ROW.number * Cinema.SEATS.number
mappingSeats = MutableList(Cinema.ROW.number) { MutableList(Cinema.SEATS.number) { S_SYMBOL } }
if (Cinema.TOTAL_SEATS.number <= SMALL_ROOM) {
Cinema.TOTAL_INCOME.number = Cinema.TOTAL_SEATS.number * STANDARD
} else {
val frontHalf = (Cinema.ROW.number / 2) * Cinema.SEATS.number * STANDARD
val backHalf = ((Cinema.ROW.number / 2) + (Cinema.ROW.number % 2)) * Cinema.SEATS.number * DISCOUNT
Cinema.TOTAL_INCOME.number = frontHalf + backHalf
}
seatsPreview(mappingSeats)
}
fun buyTicket() {
try {
println("Enter a row number:")
Cinema.SELECT_ROW.number = readln().toInt()
println("Enter a seat number in that row:")
Cinema.SELECT_SEAT.number = readln().toInt()
println("Ticket price: $${ticketPrice()}")
if (mappingSeats[Cinema.SELECT_ROW.number - 1][Cinema.SELECT_SEAT.number - 1] == B_SYMBOL) {
throw Exception()
} else {
mappingSeats[Cinema.SELECT_ROW.number - 1][Cinema.SELECT_SEAT.number - 1] = B_SYMBOL
}
Cinema.PURCHASED_TICKET.number += 1
} catch (e: IndexOutOfBoundsException) {
println("Wrong input!")
buyTicket()
} catch (e: Exception) {
println("That ticket has already been purchased")
buyTicket()
}
Cinema.CURRENT_INCOME.number += ticketPrice()
}
fun seatsPreview(mappingSeats: MutableList<MutableList<Char>>) {
print("Cinema:\n ")
(1..mappingSeats[0].size).forEach { print("$it ") }
println()
for (i in 1..mappingSeats.size) {
print("$i ")
println(mappingSeats[i - 1].joinToString(separator = " "))
}
}
fun ticketPrice(): Int {
val ticketPrice =
if (Cinema.TOTAL_SEATS.number <= SMALL_ROOM || Cinema.SELECT_ROW.number <= mappingSeats.size / 2) {
STANDARD
} else {
DISCOUNT
}
return ticketPrice
}
fun main() {
userInput()
cinema@ while (true) {
println(
"""
1. Show the seats
2. Buy a ticket
0. Exit
""".trimIndent()
)
when (readln()) {
"1" -> seatsPreview(mappingSeats)
"2" -> buyTicket()
"0" -> break@cinema
}
}
}
| 0 |
Kotlin
| 0 | 1 |
b9a8d8960ff35bd8b77a198ab9abd7ff83b6e97f
| 2,996 |
Cinema-Room-Manager-Kotlin
|
MIT License
|
src/main/kotlin/com/hj/leetcode/kotlin/problem1470/Solution2.kt
|
hj-core
| 534,054,064 | false |
{"Kotlin": 619841}
|
package com.hj.leetcode.kotlin.problem1470
/**
* LeetCode page: [1470. Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/);
*/
class Solution2 {
/* Complexity:
* Time O(n) and Space O(1);
*/
fun shuffle(nums: IntArray, n: Int): IntArray {
require(nums.size == n * 2)
shuffleButNegativeValues(nums, n)
restoreValuesBackToPositive(nums)
return nums
}
/**
* Require [nums] contains positive values only.
*/
private fun shuffleButNegativeValues(nums: IntArray, n: Int) {
for (i in nums.indices) {
var finalIndex = getFinalIndex(i, n)
while (nums[i] > 0) {
nums[i] = -nums[i]
nums.swap(i, finalIndex)
finalIndex = getFinalIndex(finalIndex, n)
}
}
}
private fun getFinalIndex(initialIndex: Int, n: Int): Int {
return if (initialIndex < n) initialIndex * 2 else (initialIndex - n) * 2 + 1
}
private fun IntArray.swap(index: Int, withIndex: Int) {
this[index] = this[withIndex].also { this[withIndex] = this[index] }
}
private fun restoreValuesBackToPositive(nums: IntArray) {
for (i in nums.indices) {
nums[i] = -nums[i]
}
}
}
| 1 |
Kotlin
| 0 | 1 |
14c033f2bf43d1c4148633a222c133d76986029c
| 1,288 |
hj-leetcode-kotlin
|
Apache License 2.0
|
src/main/kotlin/twentytwentytwo/Day17.kt
|
JanGroot
| 317,476,637 | false |
{"Kotlin": 80906}
|
package twentytwentytwo
import twentytwentytwo.Structures.Point2d
import kotlin.math.floor
fun main() {
val input = {}.javaClass.getResource("input-17.txt")!!.readText().trim();
val test = {}.javaClass.getResource("input-17-1.txt")!!.readText();
val dayTest = Day17(test)
//println(dayTest.part1())
//println(dayTest.part2())
val day = Day17(input)
//println(day.part1())
println(day.part2())
}
class Day17(private val input: String) {
val shapes = listOf("underscore", "plus", "corner", "pipe", "square")
val cave = Cave(gas = input)
fun part1(): Int {
val cave = Cave(gas = input)
(0 until 2022).forEach {
var factory = ShapeFactory(y = cave.top() + 4)
val shape = when (shapes[it % shapes.size]) {
"underscore" -> factory.underScore()
"plus" -> factory.plus()
"corner" -> factory.corner()
"pipe" -> factory.pipe()
"square" -> factory.square()
else -> {
null
}
}
cave.drop(shape!!)
}
println(cave.counter)
return cave.top()
}
fun part2(): Int {
val cave = Cave(gas = input)
(0 until 1000000).forEach {
var factory = ShapeFactory(y = cave.top() + 4)
val shape = when (shapes[(it % shapes.size).toInt()]) {
"underscore" -> factory.underScore()
"plus" -> factory.plus()
"corner" -> factory.corner()
"pipe" -> factory.pipe()
"square" -> factory.square()
else -> {
null
}
}
cave.drop(shape!!, it)
}
println(cave.counter)
return cave.top()
}
}
data class ShapeFactory(val x: Int = 2, val y: Int) {
fun underScore() = setOf(Point2d(x, y), Point2d(x + 1, y), Point2d(x + 2, y), Point2d(x + 3, y))
fun plus() = setOf(
Point2d(x + 1, y),
Point2d(x, y + 1),
Point2d(x + 1, y + 1),
Point2d(x + 2, y + 1),
Point2d(x + 1, y + 2)
)
fun corner() = setOf(
Point2d(x, y), Point2d(x + 1, y), Point2d(x + 2, y), Point2d(x + 2, y + 1), Point2d(x + 2, y + 2)
)
fun pipe() = setOf(Point2d(x, y), Point2d(x, y + 1), Point2d(x, y + 2), Point2d(x, y + 3))
fun square() = setOf(Point2d(x, y), Point2d(x + 1, y), Point2d(x, y + 1), Point2d(x + 1, y + 1))
}
typealias Shape = Set<Point2d>
class Cave(val width: Int = 7, val gas: String) {
val stack =
mutableSetOf<Point2d>(Point2d(1, 0), Point2d(2, 0), Point2d(3, 0), Point2d(4, 0), Point2d(5, 0), Point2d(6, 0))
var move = 0
var counter = 0
var lastPacket = 0
var lastHeigth =0
var deltaP = 0
var deltaH = 0
var countdown = 100000000000;
fun drop(shape: Shape, i: Int = 0) {
var ds = shape
val instruction = gas[move]
counter++
when (instruction) {
'<' -> ds = ds.left()
'>' -> ds = ds.right()
}
move = (move + 1) % gas.length
if(move%(gas.length * 5) == 0) {
if ((i - lastPacket) == deltaP ) {
println("current height ${top()}")
println("current blocks ${i}")
println("loop every ${deltaP}")
println("height delta: ${deltaH}")
var togo = 1000000000000 - i
println("${(togo/deltaP) * deltaP}")
countdown = i + togo%deltaP
println("height will be: ${(togo/deltaP * deltaH)} plus another ${togo%deltaP} blocks")
}
deltaP = i - lastPacket
deltaH = top() - lastHeigth
lastPacket = i
lastHeigth = top()
}
if (ds.down().any { it in stack }) {
stack += ds
if(countdown == i.toLong()) {
println(top())
}
} else drop(ds.down(), i)
}
fun top(): Int = stack.maxOf { it.y }
fun Shape.left() = if (any { it.x == 0 } || this.map{it.move("L")}.any{ it in stack}) this else this.map { it.move("L") }.toSet() // also check bound in stack
fun Shape.right() = if (any { it.x == width - 1 }|| this.map{it.move("R")}.any{ it in stack}) this else this.map { it.move("R") }.toSet() //also check bound in stack
fun Shape.down() = this.map { it.move("D") }.toSet()
}
| 0 |
Kotlin
| 0 | 0 |
04a9531285e22cc81e6478dc89708bcf6407910b
| 4,482 |
aoc202xkotlin
|
The Unlicense
|
day16/Part1.kt
|
anthaas
| 317,622,929 | false | null |
import java.io.File
fun main(args: Array<String>) {
val input = File("input.txt").bufferedReader().use { it.readText() }.split("\n\n")
val rules = input[0].split("\n").map {
it.split(":")[1].split(" or ")
.map { it.split('-').let { (low, high) -> low.trim().toInt() to high.trim().toInt() } }
}
val result = input[2].split("\n").subList(1,input[2].split("\n").size)
.map { it.split(",").map { when(checkIfAnyRule(it.toInt(), rules)) {
true -> 0
else -> it.toInt()
} }.sum() }.sum()
println(result)
}
private fun checkIfAnyRule(input: Int, rules: List<List<Pair<Int, Int>>>): Boolean {
return rules.map { it.map { input in it.first .. it.second }.any { it } }.any { it }
}
| 0 |
Kotlin
| 0 | 0 |
aba452e0f6dd207e34d17b29e2c91ee21c1f3e41
| 762 |
Advent-of-Code-2020
|
MIT License
|
kotlin/780.Max Chunks To Make Sorted(最多能完成排序的块).kt
|
learningtheory
| 141,790,045 | false |
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
|
/**
<p>Given an array <code>arr</code> that is a permutation of <code>[0, 1, ..., arr.length - 1]</code>, we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.</p>
<p>What is the most number of chunks we could have made?</p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr = [4,3,2,1,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr = [1,0,2,3,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
</pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>arr</code> will have length in range <code>[1, 10]</code>.</li>
<li><code>arr[i]</code> will be a permutation of <code>[0, 1, ..., arr.length - 1]</code>.</li>
</ul>
<p> </p><p>数组<code>arr</code>是<code>[0, 1, ..., arr.length - 1]</code>的一种排列,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。</p>
<p>我们最多能将数组分成多少块?</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> arr = [4,3,2,1,0]
<strong>输出:</strong> 1
<strong>解释:</strong>
将数组分成2块或者更多块,都无法得到所需的结果。
例如,分成 [4, 3], [2, 1, 0] 的结果是 [3, 4, 0, 1, 2],这不是有序的数组。
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> arr = [1,0,2,3,4]
<strong>输出:</strong> 4
<strong>解释:</strong>
我们可以把它分成两块,例如 [1, 0], [2, 3, 4]。
然而,分成 [1, 0], [2], [3], [4] 可以得到最多的块数。
</pre>
<p><strong>注意:</strong></p>
<ul>
<li><code>arr</code> 的长度在 <code>[1, 10]</code> 之间。</li>
<li><code>arr[i]</code>是 <code>[0, 1, ..., arr.length - 1]</code>的一种排列。</li>
</ul>
<p>数组<code>arr</code>是<code>[0, 1, ..., arr.length - 1]</code>的一种排列,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。</p>
<p>我们最多能将数组分成多少块?</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> arr = [4,3,2,1,0]
<strong>输出:</strong> 1
<strong>解释:</strong>
将数组分成2块或者更多块,都无法得到所需的结果。
例如,分成 [4, 3], [2, 1, 0] 的结果是 [3, 4, 0, 1, 2],这不是有序的数组。
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> arr = [1,0,2,3,4]
<strong>输出:</strong> 4
<strong>解释:</strong>
我们可以把它分成两块,例如 [1, 0], [2, 3, 4]。
然而,分成 [1, 0], [2], [3], [4] 可以得到最多的块数。
</pre>
<p><strong>注意:</strong></p>
<ul>
<li><code>arr</code> 的长度在 <code>[1, 10]</code> 之间。</li>
<li><code>arr[i]</code>是 <code>[0, 1, ..., arr.length - 1]</code>的一种排列。</li>
</ul>
**/
class Solution {
fun maxChunksToSorted(arr: IntArray): Int {
}
}
| 0 |
Python
| 1 | 3 |
6731e128be0fd3c0bdfe885c1a409ac54b929597
| 3,501 |
leetcode
|
MIT License
|
src/main/kotlin/day19/BeaconScanner.kt
|
Arch-vile
| 433,381,878 | false |
{"Kotlin": 57129}
|
package day19
import utils.Point
import utils.read
import utils.splitAfter
fun main() {
val data = read("./src/main/resources/day19Input.txt")
.splitAfter("")
.map {
if(it.last() == "")
it.drop(1).dropLast(1)
else
it.drop(1)
}
.map { it.map {
val parts = it.split(",")
Point(parts[0].toLong(), parts[1].toLong(), parts[2].toLong())
} }
data
.forEach {
val distances = allPairs(it).map { it.first.distance(it.second) }
.map { it.toInt() }
.sorted()
.take(20)
println(distances)
}
}
fun allPairs(it: List<Point>): List<Pair<Point, Point>> {
val pairs = mutableListOf<Pair<Point,Point>>()
for(i in it.indices-1) {
for(j in (i+1 until it.size)) {
pairs.add(Pair(it[i],it[j]))
}
}
return pairs.toList()
}
| 0 |
Kotlin
| 0 | 0 |
4cdafaa524a863e28067beb668a3f3e06edcef96
| 944 |
adventOfCode2021
|
Apache License 2.0
|
2022/src/test/kotlin/Day10.kt
|
jp7677
| 318,523,414 | false |
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
|
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
private enum class Op { NOOP, ADDX }
private data class Cycle(val during: Int, val after: Int)
class Day10 : StringSpec({
"puzzle part 01" {
val cycles = getCycles()
val signalStrength = listOf(20, 60, 100, 140, 180, 220).sumOf {
cycles[it - 1] * it
}
signalStrength shouldBe 14920
}
"puzzle part 02" {
val screen = getCycles()
.chunked(40)
.map {
it.mapIndexed { centerOfSprite, x ->
if (x in (centerOfSprite - 1..centerOfSprite + 1)) '#' else '.'
}.joinToString("")
}
screen[0] shouldBe "###..#..#..##...##...##..###..#..#.####."
screen[1] shouldBe "#..#.#..#.#..#.#..#.#..#.#..#.#..#....#."
screen[2] shouldBe "###..#..#.#....#..#.#....###..#..#...#.."
screen[3] shouldBe "#..#.#..#.#....####.#....#..#.#..#..#..."
screen[4] shouldBe "#..#.#..#.#..#.#..#.#..#.#..#.#..#.#...."
screen[5] shouldBe "###...##...##..#..#..##..###...##..####."
}
})
private fun getCycles() = getPuzzleInput("day10-input.txt")
.map { it.split(" ") }
.map {
when (it.first()) {
"noop" -> Op.valueOf(it.first().uppercase()) to 0
"addx" -> Op.valueOf(it.first().uppercase()) to it.last().toInt()
else -> throw IllegalArgumentException()
}
}
.fold(listOf(Cycle(1, 1))) { acc, it ->
val x = acc.last().after
acc + when (it.first) {
Op.NOOP -> listOf(Cycle(x, x))
Op.ADDX -> listOf(Cycle(x, x), Cycle(x, x + it.second))
}
}
.drop(1)
.map { it.during }
| 0 |
Kotlin
| 1 | 2 |
8bc5e92ce961440e011688319e07ca9a4a86d9c9
| 1,743 |
adventofcode
|
MIT License
|
src/main/kotlin/cc/stevenyin/algorithms/_01_binary_search/BinarySearchWhile.kt
|
StevenYinKop
| 269,945,740 | false |
{"Kotlin": 107894, "Java": 9565}
|
package cc.stevenyin.algorithms._01_binary_search
/**
* Binary search to find the index of target in a sorted array.
*
* @param array The sorted array to search.
* @param target The value to search for.
* @return The index of target if found, or the negation of the insertion point otherwise.
*/
fun <T: Comparable<T>> binarySearch(array: Array<T>, target: T): Int {
var low = 0
var high = array.size - 1
while (low < high) {
val midIndex = (low + high) / 2
val mid = array[midIndex]
when {
mid < target -> low = midIndex + 1
mid > target -> high = midIndex - 1
else -> return midIndex
}
}
return -low - 1 // Not found, would insert at -low-1
}
fun main() {
val testData = arrayOf(10, 20, 30, 50, 80, 99, 100)
assert(binarySearch(testData, 2) == -1)
assert(binarySearch(testData, 10) == 0)
assert(binarySearch(testData, 100) == 6)
assert(binarySearch(testData, 101) == -1)
assert(binarySearch(testData, 98) == -1)
}
| 0 |
Kotlin
| 0 | 1 |
748812d291e5c2df64c8620c96189403b19e12dd
| 1,038 |
kotlin-demo-code
|
MIT License
|
Algorithm/coding_interviews/Kotlin/Questions26.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() {
// 构造父树
val father = BinaryTreeNode(8)
val b = BinaryTreeNode(8)
val c = BinaryTreeNode(7)
val d = BinaryTreeNode(9)
val e = BinaryTreeNode(2)
val f = BinaryTreeNode(4)
val g = BinaryTreeNode(7)
father.mLeft = b
father.mRight = c
b.mLeft = d
b.mRight = e
e.mLeft = f
e.mRight = g
// 构造子树
val son = BinaryTreeNode(8)
val h = BinaryTreeNode(9)
val i = BinaryTreeNode(2)
val j = BinaryTreeNode(4)
val k = BinaryTreeNode(7)
son.mLeft = h
son.mRight = i
i.mLeft = j
i.mRight = k
println(hasSubtree(father, son))
}
fun <T> hasSubtree(father: BinaryTreeNode<T>, son: BinaryTreeNode<T>): Boolean {
// 判断一个树的及其子树是否是另一个树的父树
fun hasSubtreeSon(father: BinaryTreeNode<T>, son: BinaryTreeNode<T>): Boolean {
var boo = false
if (father.mValue == son.mValue) {
if (father.mLeft != null && son.mLeft != null) {
boo = hasSubtreeSon(father.mLeft!!, son.mLeft!!)
} else if (son.mLeft == null) {
boo = true
}
if (boo) {
if (father.mRight != null && son.mRight != null) {
boo = hasSubtreeSon(father.mRight!!, son.mRight!!)
} else if (son.mRight == null) {
boo = true
}
}
}
return boo
}
var boo = hasSubtreeSon(father, son)
if (boo) {
return boo
} else if (father.mLeft != null) {
boo = hasSubtree(father.mLeft!!, son)
}
if (boo) {
return boo
}
if (father.mRight != null) {
boo = hasSubtree(father.mRight!!, son)
}
return boo
}
| 0 |
HTML
| 0 | 2 |
2a989fe85941f27b9dd85b3958514371c8ace13b
| 1,575 |
awesome-cs
|
Apache License 2.0
|
src/test/kotlin/boti996/lileto/tests/helpers/DataHelpers.kt
|
boti996
| 223,049,715 | false | null |
package boti996.lileto.tests.helpers
// Lileto null value
internal const val liletoNullValue = "-"
/**
* Alias for simple testcases.
* [Pair]'s first element is a [String] in Lileto language.
* [Pair]'s second element is the expected result [String].
*/
internal typealias testcase = Pair<String, String>
internal typealias testcases = List<testcase>
internal fun testcase.getKeyType() = this.first::class
internal fun testcase.getValueType() = this.second::class
/**
* Store the literals of Lileto brackets
* @param literals opening and closing characters
*/
internal enum class BracketType(private val literals: Pair<Char, Char>) {
TEXT(Pair('"', '"')),
TEMPLATE(Pair('<', '>')),
SPECIAL_CHAR(Pair('$', '$')),
COMMAND(Pair('!', '!')),
CONTAINER(Pair('[', ']')),
COMMENT(Pair('.', '.'));
fun open() = "{${literals.first}"
fun close() = "${literals.second}}"
}
/**
* Store the literals of Lileto special characters
* @param values Lileto literal and the resolved values
*/
internal enum class SpecialCharacter(private val values: Pair<String, Char>) {
ENTER (Pair("e", '\n')),
TAB (Pair("t", '\t')),
SPACE (Pair("s", ' ')),
O_R_BRACKET (Pair("orb", '(')),
C_R_BBRACKET(Pair("crb", ')')),
EQUALS_SIGN (Pair("eq", '=')),
PLUS_SIGN (Pair("pl", '+')),
O_C_BRACKET (Pair("ocb", '{')),
C_C_BRACKET (Pair("ccb", '}')),
POINT (Pair("pe", '.')),
COMMA (Pair("co", ',')),
SEMICOLON (Pair("sc", ';')),
COLON (Pair("cl", ':')),
VBAR (Pair("pi", '|')),
LT_SIGN (Pair("ls", '<')),
GT_SIGN (Pair("gt", '>')),
QUESTION_M (Pair("qm", '?')),
EXCLAM_M (Pair("dm", '!'));
fun literal() = values.first
fun character() = values.second.toString()
}
/**
* Store bracket with it's content
* @param bracket type of bracket
*/
internal data class BracketWithContent(val bracket: BracketType, val content: Any) {
fun open() = bracket.open()
fun close() = bracket.close()
}
/**
* Convert an [Array] of [BracketType] and [Any] type of content
* into a [List] of [BracketWithContent]
* @param brackets data to convert
*/
internal fun bracketListOf(brackets: List<Pair<BracketType, Any>>)
: List<BracketWithContent> = brackets.map {
BracketWithContent(
bracket = it.first,
content = it.second
)
}
/**
* Concatenate a [List] of [Any] type of data into a [String] and return it in [Pair] with the expected [String]
* @param input data to concatenate in Lileto language format
* @param expected expected output of Lileto in plain text
*/
internal fun buildTestCaseEntry(input: List<Any>,
expected: String)
: testcase {
return Pair(input.joinToString(separator = ""), expected)
}
| 0 |
Kotlin
| 0 | 0 |
190fbe56e0862956b45bbd62ff888da16a78891a
| 2,833 |
lileto_tests
|
MIT License
|
src/main/kotlin/day10/part1/main.kt
|
TheMrMilchmann
| 225,375,010 | false | null |
/*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package day10.part1
import utils.*
import kotlin.math.*
fun main() {
val input = readInputText("/day10/input.txt")
val data = input.lineSequence().mapIndexed { y, line ->
line.mapIndexed { x, c ->
if (c == '#') Vec(x, y) else null
}
}.flatten().filterNotNull().toList()
println(run(data))
}
private fun run(data: List<Vec>): Int {
fun gcd(a: Int, b: Int): Int {
var r = abs(b)
var oldR = abs(a)
while (r != 0) {
val quotient = oldR / r
val tmpR = r
r = oldR - quotient * r
oldR = tmpR
}
return oldR
}
return data.map { station ->
data.asSequence()
.filter { it != station }
.map { Vec(it.x - station.x, it.y - station.y) }
.map {
when {
it.x == 0 -> Vec(0, it.y.sign)
it.y == 0 -> Vec(it.x.sign, 0)
else -> {
val gcd = gcd(it.x, it.y)
if (gcd >= 0) Vec(it.x / gcd, it.y / gcd) else it
}
}
}.distinct()
.count()
}.max()!!
}
private data class Vec(val x: Int, val y: Int)
| 0 |
Kotlin
| 0 | 1 |
9d6e2adbb25a057bffc993dfaedabefcdd52e168
| 2,371 |
AdventOfCode2019
|
MIT License
|
src/Day04.kt
|
DevHexs
| 573,262,501 | false |
{"Kotlin": 11452}
|
fun main(){
fun part1(): Int{
val list = mutableListOf<String>()
var countRepeatWork = 0
for (i in readInput("Day04")){
for (j in i.split(",")){
val v = j.split('-').map { it.toInt() }
var rangeText = ""
for (k in v[0].rangeTo(v[1]) ){
rangeText += " $k "
}
list.add(rangeText)
}
}
for (i in 0 until list.size - 1 step 2){
if (list[i] in list[i+1] || list[i+1] in list[i]) {
countRepeatWork++
}
}
return countRepeatWork
}
fun part2(): Int{
val listRange = mutableListOf<List<Int>>()
var countRepeatWork = 0
for (i in readInput("Day04")){
for (j in i.split(",")){
val v = j.split('-').map { it.toInt() }
val listValue = mutableListOf<Int>()
for (k in v[0].rangeTo(v[1]) ){
listValue.add(k)
}
listRange.add(listValue)
}
}
for (i in 0 until listRange.size - 1 step 2){
if (listRange[i].intersect(listRange[i+1].toSet()).isNotEmpty()){
countRepeatWork++
}
}
return countRepeatWork
}
println(part1())
println(part2())
}
| 0 |
Kotlin
| 0 | 0 |
df0ff2ed7c1ebde9327cd1a102499ac5467b73be
| 1,397 |
AdventOfCode-2022-Kotlin
|
Apache License 2.0
|
src/main/java/com/barneyb/aoc/aoc2022/day23/UnstableDiffusion.kt
|
barneyb
| 553,291,150 | false |
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
|
package com.barneyb.aoc.aoc2022.day23
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toSlice
import com.barneyb.util.HashSet
import com.barneyb.util.Vec2
fun main() {
Solver.execute(
::parse,
::openSpacesAfterTenRounds, // 3,684
::firstNoOpRound, // 862
)
}
internal fun parse(input: String) =
HashSet<Vec2>().apply {
input.toSlice()
.trim()
.lines()
.forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
if (c == '#')
add(Vec2(x, y))
}
}
}
internal fun openSpacesAfterTenRounds(elves: HashSet<Vec2>): Int {
var game = Game(elves)
repeat(10) { game = game.tick() }
return game.emptySpaceCount
}
internal fun firstNoOpRound(elves: HashSet<Vec2>): Int {
var game = Game(elves)
// println("{\"rounds\":[")
while (true) {
val next = game.tickWithMotionCount()
game = next.first
if (next.second == 0)
break
}
// println("], \"bounds\": [${game.bounds.let { b -> "${b.x1},${b.y1},${b.width},${b.height}" }}]}")
return game.rounds
}
| 0 |
Kotlin
| 0 | 0 |
8b5956164ff0be79a27f68ef09a9e7171cc91995
| 1,194 |
aoc-2022
|
MIT License
|
libraries/stdlib/src/kotlin/OrderingJVM.kt
|
udalov
| 10,645,710 | false |
{"Java": 9931656, "Kotlin": 2142480, "JavaScript": 942412, "C++": 613791, "C": 193807, "Objective-C": 22634, "Shell": 12589, "Groovy": 1267}
|
package kotlin
import java.util.Comparator
/**
* Helper method for implementing [[Comparable]] methods using a list of functions
* to calculate the values to compare
*/
inline fun <T : Any> compareBy(a: T?, b: T?, vararg functions: T.() -> Comparable<*>?): Int {
require(functions.size > 0)
if (a === b) return 0
if (a == null) return - 1
if (b == null) return 1
for (fn in functions) {
val v1 = a.fn()
val v2 = b.fn()
val diff = compareValues(v1, v2)
if (diff != 0) return diff
}
return 0
}
/**
* Compares the two values which may be [[Comparable]] otherwise
* they are compared via [[#equals()]] and if they are not the same then
* the [[#hashCode()]] method is used as the difference
*/
public inline fun <T : Comparable<*>> compareValues(a: T?, b: T?): Int {
if (a === b) return 0
if (a == null) return - 1
if (b == null) return 1
return (a as Comparable<Any?>).compareTo(b)
}
/**
* Creates a comparator using the sequence of functions used to calculate a value to compare on
*/
public inline fun <T> comparator(vararg functions: T.() -> Comparable<*>?): Comparator<T> {
return FunctionComparator<T>(*functions)
}
private class FunctionComparator<T>(vararg val functions: T.() -> Comparable<*>?): Comparator<T> {
public override fun toString(): String {
return "FunctionComparator${functions.toList()}"
}
public override fun compare(o1: T, o2: T): Int {
return compareBy<T>(o1, o2, *functions)
}
public override fun equals(obj: Any?): Boolean {
return this == obj
}
}
/**
* Creates a comparator using the sequence of functions used to calculate a value to compare on
*/
public inline fun <T> comparator(fn: (T,T) -> Int): Comparator<T> {
return Function2Comparator<T>(fn)
}
private class Function2Comparator<T>(val compareFn: (T,T) -> Int): Comparator<T> {
public override fun toString(): String {
return "Function2Comparator${compareFn}"
}
public override fun compare(a: T, b: T): Int {
if (a === b) return 0
if (a == null) return - 1
if (b == null) return 1
return (compareFn)(a, b)
}
public override fun equals(obj: Any?): Boolean {
return this == obj
}
}
| 0 |
Java
| 1 | 6 |
3958b4a71d8f9a366d8b516c4c698aae80ecfe57
| 2,291 |
kotlin-objc-diploma
|
Apache License 2.0
|
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/TheBreadth-FirstSearch.kt
|
betulnecanli
| 568,477,911 | false |
{"Kotlin": 167849}
|
/*
The Breadth-First Search (BFS) coding pattern is a popular technique for traversing or processing data structures
in a level-by-level manner.
It is commonly used with trees, graphs, and other structures where you want to visit all the neighbors at the current
depth before moving on to the next level.
*/
//1. Binary Tree Level Order Traversal
import java.util.*
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun levelOrderTraversal(root: TreeNode?): List<List<Int>> {
val result = mutableListOf<List<Int>>()
if (root == null) {
return result
}
val queue: Queue<TreeNode> = LinkedList()
queue.offer(root)
while (queue.isNotEmpty()) {
val levelSize = queue.size
val currentLevel = mutableListOf<Int>()
for (i in 0 until levelSize) {
val currentNode = queue.poll()
currentLevel.add(currentNode.`val`)
currentNode.left?.let { queue.offer(it) }
currentNode.right?.let { queue.offer(it) }
}
result.add(currentLevel)
}
return result
}
fun main() {
val root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right?.left = TreeNode(15)
root.right?.right = TreeNode(7)
val result = levelOrderTraversal(root)
println("Level Order Traversal: $result")
}
//2. Minimum Depth of a Binary Tree
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun minDepth(root: TreeNode?): Int {
if (root == null) {
return 0
}
val queue: Queue<TreeNode> = LinkedList()
queue.offer(root)
var depth = 1
while (queue.isNotEmpty()) {
val levelSize = queue.size
for (i in 0 until levelSize) {
val currentNode = queue.poll()
if (currentNode.left == null && currentNode.right == null) {
return depth
}
currentNode.left?.let { queue.offer(it) }
currentNode.right?.let { queue.offer(it) }
}
depth++
}
return depth
}
fun main() {
val root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right?.left = TreeNode(15)
root.right?.right = TreeNode(7)
val result = minDepth(root)
println("Minimum Depth of the Binary Tree: $result")
}
//3. Connect Level Order Siblings
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
var next: TreeNode? = null
}
fun connectLevelOrderSiblings(root: TreeNode?) {
if (root == null) {
return
}
val queue: Queue<TreeNode> = LinkedList()
queue.offer(root)
while (queue.isNotEmpty()) {
val levelSize = queue.size
var prevNode: TreeNode? = null
for (i in 0 until levelSize) {
val currentNode = queue.poll()
if (prevNode != null) {
prevNode.next = currentNode
}
prevNode = currentNode
currentNode.left?.let { queue.offer(it) }
currentNode.right?.let { queue.offer(it) }
}
}
}
fun main() {
val root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left?.left = TreeNode(4)
root.left?.right = TreeNode(5)
root.right?.left = TreeNode(6)
root.right?.right = TreeNode(7)
connectLevelOrderSiblings(root)
// The 'next' pointers are now connected level by level
println("Next pointers connected: ${root.next?.`val`}, ${root.left?.next?.`val`}, ${root.right?.next?.`val`}")
}
/*
Binary Tree Level Order Traversal:
The levelOrderTraversal function performs a BFS traversal of a binary tree, processing nodes level by level.
It uses a queue to enqueue and dequeue nodes at each level.
Minimum Depth of a Binary Tree:
The minDepth function calculates the minimum depth of a binary tree using BFS.
It traverses the tree level by level, and when it encounters the first leaf node, it returns the depth.
Connect Level Order Siblings:
The connectLevelOrderSiblings function connects the 'next' pointers of nodes at the same level in a binary tree.
It uses BFS to traverse the tree level by level and connects the 'next' pointers accordingly.
*/
| 2 |
Kotlin
| 2 | 40 |
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
| 4,282 |
Kotlin-Data-Structures-Algorithms
|
Apache License 2.0
|
inference/inference-ir-trees/src/commonMain/kotlin/io/kinference/trees/TreeSplit.kt
|
JetBrains-Research
| 244,400,016 | false |
{"Kotlin": 2252927, "Python": 4777, "JavaScript": 2402, "Dockerfile": 683}
|
package io.kinference.trees
enum class TreeSplitType {
BRANCH_GT,
BRANCH_GTE,
BRANCH_LT,
BRANCH_LEQ
}
sealed class TreeSplitter(val featureIds: IntArray, val nodeSplitValues: FloatArray) {
abstract fun split(input: FloatArray, srcIdx: Int, splitIdx: Int): Int
class GTTreeSplitter(featureIds: IntArray, nodeSplitValues: FloatArray): TreeSplitter(featureIds, nodeSplitValues) {
override fun split(input: FloatArray, srcIdx: Int, splitIdx: Int): Int {
return if (input[srcIdx + featureIds[splitIdx]] > nodeSplitValues[splitIdx]) 1 else 0
}
}
class GTETreeSplitter(featureIds: IntArray, nodeSplitValues: FloatArray): TreeSplitter(featureIds, nodeSplitValues) {
override fun split(input: FloatArray, srcIdx: Int, splitIdx: Int): Int {
return if (input[srcIdx + featureIds[splitIdx]] >= nodeSplitValues[splitIdx]) 1 else 0
}
}
class LTTreeSplitter(featureIds: IntArray, nodeSplitValues: FloatArray): TreeSplitter(featureIds, nodeSplitValues) {
override fun split(input: FloatArray, srcIdx: Int, splitIdx: Int): Int {
return if (input[srcIdx + featureIds[splitIdx]] < nodeSplitValues[splitIdx]) 1 else 0
}
}
class LEQTreeSplitter(featureIds: IntArray, nodeSplitValues: FloatArray): TreeSplitter(featureIds, nodeSplitValues) {
override fun split(input: FloatArray, srcIdx: Int, splitIdx: Int): Int {
return if (input[srcIdx + featureIds[splitIdx]] <= nodeSplitValues[splitIdx]) 1 else 0
}
}
companion object {
fun get(splitType: TreeSplitType, featureIds: IntArray, nodeSplitValues: FloatArray): TreeSplitter {
return when (splitType) {
TreeSplitType.BRANCH_GT -> GTTreeSplitter(featureIds, nodeSplitValues)
TreeSplitType.BRANCH_GTE -> GTETreeSplitter(featureIds, nodeSplitValues)
TreeSplitType.BRANCH_LT -> LTTreeSplitter(featureIds, nodeSplitValues)
TreeSplitType.BRANCH_LEQ -> LEQTreeSplitter(featureIds, nodeSplitValues)
}
}
}
}
| 7 |
Kotlin
| 6 | 126 |
95a58a192b6fa48d1f4ac1f2cc08658e2361756d
| 2,113 |
kinference
|
Apache License 2.0
|
src/day01/Day01.kt
|
iulianpopescu
| 572,832,973 | false |
{"Kotlin": 30777}
|
package day01
import readFile
private const val DAY = "01"
private const val DAY_TEST = "day${DAY}/Day${DAY}_test"
private const val DAY_INPUT = "day${DAY}/Day${DAY}"
fun main() {
fun sumTopCalories(input: String, limit: Int = 1) = input
.split("\n\n")
.asSequence()
.map { backpack ->
val calories = backpack.split("\n")
calories.map { it.toInt() }
}
.map { it.sum() }
.sortedDescending()
.take(limit)
.sum()
fun part1(input: String) = sumTopCalories(input)
fun part2(input: String) = sumTopCalories(input, 3)
// test if implementation meets criteria from the description, like:
val testInput = readFile(DAY_TEST)
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readFile(DAY_INPUT)
println(part1(input)) // 73211
println(part2(input)) // 213958
}
| 0 |
Kotlin
| 0 | 0 |
4ff5afb730d8bc074eb57650521a03961f86bc95
| 912 |
AOC2022
|
Apache License 2.0
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumAbsDifference.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
fun IntArray.minimumAbsDifference(): List<List<Int>> {
sort()
val list = this.toList()
val min = this[1] - first()
return list.windowed(2).filter {
it[1] - it[0] == min
}
}
fun IntArray.minimumAbsDifference2(): List<List<Int>> {
val res: MutableList<List<Int>> = ArrayList()
sort()
var min = Int.MAX_VALUE
for (i in 0 until size - 1) {
val diff = this[i + 1] - this[i]
if (diff < min) {
min = diff
res.clear()
res.add(listOf(this[i], this[i + 1]))
} else if (diff == min) {
res.add(listOf(this[i], this[i + 1]))
}
}
return res
}
| 4 |
Kotlin
| 0 | 19 |
776159de0b80f0bdc92a9d057c852b8b80147c11
| 1,305 |
kotlab
|
Apache License 2.0
|
src/day01/Day01.kt
|
mahmoud-abdallah863
| 572,935,594 | false |
{"Kotlin": 16377}
|
package day01
import assertEquals
import readInput
import readTestInput
import java.lang.Integer.max
fun main() {
fun part1(input: List<String>): Int {
var maxCalories = 0
var caloriesSum = 0
input.forEach { line ->
if (line.isBlank()){
maxCalories = max(maxCalories, caloriesSum)
caloriesSum = 0
}else {
caloriesSum += line.trim().toInt()
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
val cachedData = mutableListOf<Int>()
var currentSum = 0
input.forEach { line ->
if (line.isBlank()) {
cachedData.add(currentSum)
currentSum = 0
}else {
currentSum += line.trim().toInt()
}
}
cachedData.add(currentSum)
cachedData.sortDescending()
return cachedData.take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput()
assertEquals(part1(testInput), 24000)
assertEquals(part2(testInput), 45000)
val input = readInput()
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
f6d1a1583267e9813e2846f0ab826a60d2d1b1c9
| 1,244 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-06.kt
|
ferinagy
| 432,170,488 | false |
{"Kotlin": 787586}
|
package com.github.ferinagy.adventOfCode.aoc2021
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputText
fun main() {
val input = readInputText(2021, "06-input")
val test1 = readInputText(2021, "06-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: String): Long {
return simulateLanternFish(input, 80)
}
private fun part2(input: String): Long {
return simulateLanternFish(input, 256)
}
private fun simulateLanternFish(input: String, generations: Int): Long {
val array = Array(9) { 0L }
input.split(",")
.map { it.toInt() }
.forEach { array[it]++ }
repeat(generations) {
val born = array[0]
for (i in 1 .. array.lastIndex) {
array[i-1] = array[i]
}
array[array.lastIndex] = 0
array[6] += born
array[8] += born
}
return array.sum()
}
| 0 |
Kotlin
| 0 | 1 |
f4890c25841c78784b308db0c814d88cf2de384b
| 1,051 |
advent-of-code
|
MIT License
|
src/main/kotlin/leetcode/kotlin/array/easy/121. Best Time to Buy and Sell Stock.kt
|
sandeep549
| 251,593,168 | false | null |
package leetcode.kotlin.array.easy
import kotlin.math.max
fun main() {
println(maxProfit2(intArrayOf(7, 1, 5, 3, 6, 4)))
println(maxProfit2(intArrayOf(7, 6, 4, 3, 1)))
println(maxProfit3(intArrayOf(7, 1, 5, 3, 6, 4)))
println(maxProfit3(intArrayOf(7, 6, 4, 3, 1)))
}
/**
* Try with buy stock on each day and check the profit if we sell it on
* every right side of it, retaining max profit found so far
*/
private fun maxProfit(prices: IntArray): Int {
var max = 0
for (i in 0..prices.size - 2) {
for (j in i + 1..prices.size - 1) {
max = max(max, prices[j] - prices[i])
}
}
return max
}
private fun maxProfit2(prices: IntArray): Int {
var maxendinghere = 0
var maxsofar = 0
for (i in 1..prices.lastIndex) {
maxendinghere += prices[i] - prices[i - 1]
maxendinghere = max(0, maxendinghere)
maxsofar = max(maxsofar, maxendinghere)
}
return maxsofar
}
/**
* Iterate from left to right, try selling at every point retaining max profit found so far,
* and min found so far.
*/
private fun maxProfit3(arr: IntArray): Int {
if (arr.isEmpty()) return 0
var min = arr[0]
var ans = 0
for (i in 1..arr.lastIndex) {
ans = Math.max(ans, arr[i] - min)
min = Math.min(min, arr[i])
}
return ans
}
| 0 |
Kotlin
| 0 | 0 |
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
| 1,336 |
kotlinmaster
|
Apache License 2.0
|
y2022/src/main/kotlin/adventofcode/y2022/Day07.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2022
import adventofcode.io.AdventSolution
object Day07 : AdventSolution(2022, 7, "No Space Left On Device") {
override fun solvePartOne(input: String): Long {
return parse(input).values.filter { it <= 100_000 }.sum()
}
override fun solvePartTwo(input: String): Long {
val directorySizes = parse(input)
val required = directorySizes.getValue("") - 40_000_000
return directorySizes.values.filter { it >= required }.min()
}
private fun parse(input: String): Map<String, Long> {
val directories = mutableSetOf("")
var currentPath = ""
val files = mutableMapOf<String, Long>()
input.lineSequence().forEach { line ->
when {
line == "$ ls" -> {}
line == "$ cd /" -> currentPath = ""
line == "$ cd .." -> currentPath = currentPath.substringBeforeLast('/')
line.startsWith("$ cd") -> currentPath = currentPath + '/' + line.substringAfterLast(' ')
line.startsWith("dir") -> directories += currentPath + '/' + line.substringAfterLast(' ')
else -> files[currentPath + '/' + line.substringAfter(' ')] = line.substringBefore(' ').toLong()
}
}
return directories.associateWith { dir ->
files.asSequence().filter { it.key.startsWith(dir) }.sumOf { it.value }
}
}
}
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 1,421 |
advent-of-code
|
MIT License
|
src/main/kotlin/com/ginsberg/advent2019/Day20.kt
|
tginsberg
| 222,116,116 | false | null |
/*
* Copyright (c) 2019 by <NAME>
*/
/**
* Advent of Code 2019, Day 20 - Donut Maze
* Problem Description: http://adventofcode.com/2019/day/20
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day20/
*/
package com.ginsberg.advent2019
import java.util.ArrayDeque
class Day20(input: List<String>) {
private val maze: Set<Point2D> = parseMaze(input)
private val portalData = linkPortals(input)
private val portals: Map<Point2D, Point2D> = portalData.first
private val begin: Point2D = portalData.second
private val end: Point2D = portalData.third
private val outwardX = setOf(2, input.first().length - 3)
private val outwardY = setOf(2, input.size - 3)
fun solvePart1(): Int =
bfs()
fun solvePart2(): Int =
bfsLeveled()
private fun bfs(): Int {
val discovered = mutableSetOf<Point2D>().apply {
add(begin)
}
val queue = ArrayDeque<MutableList<Point2D>>().apply {
add(mutableListOf(begin))
}
while (queue.isNotEmpty()) {
val here = queue.pop()
if (here.first() == end) {
return here.size - 1
}
here.first().neighborsWithPortals().forEach { neighbor ->
if (neighbor !in discovered) {
discovered.add(neighbor)
queue.addLast(here.copyOf().also { it.add(0, neighbor) })
}
}
}
throw IllegalStateException("No path to end")
}
private fun bfsLeveled(): Int {
val discovered = mutableSetOf<Pair<Point2D, Int>>().apply {
add(begin to 0)
}
val queue = ArrayDeque<MutableList<Pair<Point2D, Int>>>().apply {
add(mutableListOf(begin to 0))
}
while (queue.isNotEmpty()) {
val path = queue.pop()
if (path.first() == end to 0) {
return path.size - 1
}
path.first().neighborsWithPortalsAndLevels().filterNot { it in discovered }.forEach { neighbor ->
discovered.add(neighbor)
queue.addLast(path.copyOf().also { it.add(0, neighbor) })
}
}
throw IllegalStateException("No path to end")
}
private fun Point2D.neighborsWithPortals(): List<Point2D> {
val neighbors = this.neighbors().filter { it in maze }
return (neighbors + portals[this]).filterNotNull()
}
private fun Pair<Point2D, Int>.neighborsWithPortalsAndLevels(): List<Pair<Point2D, Int>> {
val neighbors = this.first.neighbors().filter { it in maze }.map { Pair(it, this.second) }.toMutableList()
portals[this.first]?.let {
val levelDiff = if (this.first.x in outwardX || this.first.y in outwardY) -1 else 1
neighbors.add(it to this.second + levelDiff)
}
return neighbors.filter { it.second >= 0 }
}
private fun parseMaze(input: List<String>): Set<Point2D> =
input.mapIndexed { y, row ->
row.mapIndexedNotNull { x, c -> if (c == '.') Point2D(x, y) else null }
}.flatten().toSet()
private fun linkPortals(input: List<String>): Triple<Map<Point2D, Point2D>, Point2D, Point2D> {
val linked = mutableMapOf<Point2D, Point2D>()
val unlinked = mutableMapOf<String, Point2D>()
input.forEachIndexed { y, row ->
row.forEachIndexed { x, c ->
if (c in letters) {
val at = Point2D(x, y)
var name: String? = null
var portal: Point2D? = null
when {
input.getOrNull(at.south()) in letters && at.north() in maze -> {
name = "$c${input.getOrNull(at.south())}"
portal = at.north()
}
input.getOrNull(at.south()) in letters && at.south().south() in maze -> {
name = "$c${input.getOrNull(at.south())}"
portal = at.south().south()
}
input.getOrNull(at.east()) in letters && at.west() in maze -> {
name = "$c${input.getOrNull(at.east())}"
portal = at.west()
}
input.getOrNull(at.east()) in letters && at.east().east() in maze -> {
name = "$c${input.getOrNull(at.east())}"
portal = at.east().east()
}
}
if (name != null && portal != null) {
if (name in unlinked) {
linked[portal] = unlinked[name]!!
linked[unlinked[name]!!] = portal
unlinked.remove(name)
} else {
unlinked[name] = portal
}
}
}
}
}
return Triple(linked, unlinked["AA"]!!, unlinked["ZZ"]!!)
}
companion object {
val letters = 'A'..'Z'
}
}
| 0 |
Kotlin
| 2 | 23 |
a83e2ecdb6057af509d1704ebd9f86a8e4206a55
| 5,233 |
advent-2019-kotlin
|
Apache License 2.0
|
DiagonalDifference.kt
|
Rxfa
| 540,482,211 | false |
{"Kotlin": 8429}
|
import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import kotlin.collections.*
import kotlin.comparisons.*
import kotlin.io.*
import kotlin.jvm.*
import kotlin.jvm.functions.*
import kotlin.jvm.internal.*
import kotlin.ranges.*
import kotlin.sequences.*
import kotlin.text.*
/*
* Hackerrank - Diagonal Difference
* https://www.hackerrank.com/challenges/diagonal-difference/problem
*/
fun diagonalDifference(arr: Array<Array<Int>>): Int {
var primaryDiagonal = 0
var secondaryDiagonal = 0
var counter = 0
for(line in 1..arr.size){
primaryDiagonal += arr[counter][counter]
secondaryDiagonal += arr[counter][(arr.size - 1) - counter]
counter++
}
return Math.abs(primaryDiagonal - secondaryDiagonal)
}
fun main(args: Array<String>) {
val n = readLine()!!.trim().toInt()
val arr = Array<Array<Int>>(n, { Array<Int>(n, { 0 }) })
for (i in 0 until n) {
arr[i] = readLine()!!.trimEnd().split(" ").map{ it.toInt() }.toTypedArray()
}
val result = diagonalDifference(arr)
println(result)
}
| 0 |
Kotlin
| 0 | 2 |
5ba1a7e707a62a63398a138b22c0b186f136bab7
| 1,233 |
kotlin-basics
|
MIT License
|
kotlin/275.H-Index II(H指数 II).kt
|
learningtheory
| 141,790,045 | false |
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
|
/**
<p>Given an array of citations <strong>sorted in ascending order </strong>(each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.</p>
<p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: "A scientist has index <i>h</i> if <i>h</i> of his/her <i>N</i> papers have <b>at least</b> <i>h</i> citations each, and the other <i>N − h</i> papers have <b>no more than</b> <i>h </i>citations each."</p>
<p><b>Example:</b></p>
<pre>
<b>Input:</b> <code>citations = [0,1,3,5,6]</code>
<b>Output:</b> 3
<strong>Explanation: </strong><code>[0,1,3,5,6] </code>means the researcher has <code>5</code> papers in total and each of them had
received 0<code>, 1, 3, 5, 6</code> citations respectively.
Since the researcher has <code>3</code> papers with <b>at least</b> <code>3</code> citations each and the remaining
two with <b>no more than</b> <code>3</code> citations each, her h-index is <code>3</code>.</pre>
<p><strong>Note:</strong></p>
<p>If there are several possible values for <em>h</em>, the maximum one is taken as the h-index.</p>
<p><strong>Follow up:</strong></p>
<ul>
<li>This is a follow up problem to <a href="/problems/h-index/description/">H-Index</a>, where <code>citations</code> is now guaranteed to be sorted in ascending order.</li>
<li>Could you solve it in logarithmic time complexity?</li>
</ul>
<p>给定一位研究者论文被引用次数的数组(被引用次数是非负整数),数组已经按照<strong>升序排列</strong>。编写一个方法,计算出研究者的 <em>h</em> 指数。</p>
<p><a href="https://baike.baidu.com/item/h-index/3991452?fr=aladdin">h 指数的定义</a>: “一位有 <em>h</em> 指数的学者,代表他(她)的<em> N</em> 篇论文中<strong>至多</strong>有<em> h </em>篇论文,分别被引用了<strong>至少</strong> <em>h</em> 次,其余的 <em>N - h </em>篇论文每篇被引用次数<strong>不多于 </strong><em>h </em>次。"</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> <code>citations = [0,1,3,5,6]</code>
<strong>输出:</strong> 3
<strong>解释: </strong>给定数组表示研究者总共有 <code>5</code> 篇论文,每篇论文相应的被引用了 0<code>, 1, 3, 5, 6</code> 次。
由于研究者有 <code>3 </code>篇论文每篇<strong>至少</strong>被引用了 <code>3</code> 次,其余两篇论文每篇被引用<strong>不多于</strong> <code>3</code> 次,所以她的<em> h </em>指数是 <code>3</code>。</pre>
<p><strong>说明:</strong></p>
<p>如果 <em>h </em>有多有种可能的值 ,<em>h</em> 指数是其中最大的那个。</p>
<p><strong>进阶:</strong></p>
<ul>
<li>这是 <a href="/problems/h-index/description/">H指数</a> 的延伸题目,本题中的 <code>citations</code> 数组是保证有序的。</li>
<li>你可以优化你的算法到对数时间复杂度吗?</li>
</ul>
<p>给定一位研究者论文被引用次数的数组(被引用次数是非负整数),数组已经按照<strong>升序排列</strong>。编写一个方法,计算出研究者的 <em>h</em> 指数。</p>
<p><a href="https://baike.baidu.com/item/h-index/3991452?fr=aladdin">h 指数的定义</a>: “一位有 <em>h</em> 指数的学者,代表他(她)的<em> N</em> 篇论文中<strong>至多</strong>有<em> h </em>篇论文,分别被引用了<strong>至少</strong> <em>h</em> 次,其余的 <em>N - h </em>篇论文每篇被引用次数<strong>不多于 </strong><em>h </em>次。"</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> <code>citations = [0,1,3,5,6]</code>
<strong>输出:</strong> 3
<strong>解释: </strong>给定数组表示研究者总共有 <code>5</code> 篇论文,每篇论文相应的被引用了 0<code>, 1, 3, 5, 6</code> 次。
由于研究者有 <code>3 </code>篇论文每篇<strong>至少</strong>被引用了 <code>3</code> 次,其余两篇论文每篇被引用<strong>不多于</strong> <code>3</code> 次,所以她的<em> h </em>指数是 <code>3</code>。</pre>
<p><strong>说明:</strong></p>
<p>如果 <em>h </em>有多有种可能的值 ,<em>h</em> 指数是其中最大的那个。</p>
<p><strong>进阶:</strong></p>
<ul>
<li>这是 <a href="/problems/h-index/description/">H指数</a> 的延伸题目,本题中的 <code>citations</code> 数组是保证有序的。</li>
<li>你可以优化你的算法到对数时间复杂度吗?</li>
</ul>
**/
class Solution {
fun hIndex(citations: IntArray): Int {
}
}
| 0 |
Python
| 1 | 3 |
6731e128be0fd3c0bdfe885c1a409ac54b929597
| 4,890 |
leetcode
|
MIT License
|
leetcode2/src/leetcode/longest-univalue-path.kt
|
hewking
| 68,515,222 | false | null |
package leetcode
import leetcode.structure.TreeNode
/**
* 687. 最长同值路径
* https://leetcode-cn.com/problems/longest-univalue-path/
* @program: leetcode
* @description: ${description}
* @author: hewking
* @create: 2019-10-25 10:36
* 给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。
注意:两个节点之间的路径长度由它们之间的边数表示。
示例 1:
输入:
5
/ \
4 5
/ \ \
1 1 5
输出:
2
示例 2:
输入:
1
/ \
4 5
/ \ \
4 4 5
输出:
2
注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-univalue-path
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
object LongestUnivaluePath {
class Solution {
private var ans = 0
/**
* 思路:
* 1. 递归情形:有左右节点,并且子节点的值跟root.value 做判断
* 2. 基准情形:root == null
*
* /**
解题思路类似于124题, 对于任意一个节点, 如果最长同值路径包含该节点, 那么只可能是两种情况:
1. 其左右子树中加上该节点后所构成的同值路径中较长的那个继续向父节点回溯构成最长同值路径
2. 左右子树加上该节点都在最长同值路径中, 构成了最终的最长同值路径
需要注意因为要求同值, 所以在判断左右子树能构成的同值路径时要加入当前节点的值作为判断依据
**/
*/
fun longestUnivaluePath(root: TreeNode?): Int {
root?:return 0
arrowLength(root)
return ans
}
fun arrowLength(root: TreeNode?): Int {
root?:return 0
val leftLen = arrowLength(root?.left)
val rightLen = arrowLength(root?.right)
val leftUniValue = if (root.left != null && root.left.`val` == root.`val`) 1 + leftLen else 0
val rightUniValue = if (root.right != null && root.right.`val` == root.`val`) 1 + rightLen else 0
// leftLen + rightLen 因为最长通值路径可以不经过根节点
ans = Math.max(ans,leftUniValue + rightUniValue)
return Math.max(leftUniValue,rightUniValue)
}
}
}
| 0 |
Kotlin
| 0 | 0 |
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
| 2,462 |
leetcode
|
MIT License
|
src/main/day08/Part2.kt
|
ollehagner
| 572,141,655 | false |
{"Kotlin": 80353}
|
package day08
import common.Direction
import common.Grid
import common.Point
import readInput
fun main() {
val input = readInput("day08/input.txt")
val grid = Grid(input.map { row -> row.chunked(1).map { it.toInt() } })
val maxView = grid.allPoints()
.maxOfOrNull { grid.allviews(it) }
println("Day 8 part 2 max view value: $maxView")
}
fun Grid<Int>.allviews(position: Point): Int {
return listOf(Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT)
.map { direction -> view(position, direction) }
.reduce { a, b -> a * b}
}
fun Grid<Int>.view(position: Point, direction: Direction): Int {
if(!hasValue(position.move(direction))) {
return 0;
}
val height = valueOf(position)
return generateSequence(position) { newPosition -> newPosition.move(direction) }
.drop(1)
.takeWhile { hasValue(it) }
.fold(Pair(0, true)){ countAndContinue, point ->
if(countAndContinue.second) {
Pair(countAndContinue.first + 1, valueOf(point) < height)
} else {
countAndContinue
}
}.first
}
| 0 |
Kotlin
| 0 | 0 |
6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1
| 1,155 |
aoc2022
|
Apache License 2.0
|
src/main/kotlin/g0001_0100/s0043_multiply_strings/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g0001_0100.s0043_multiply_strings
// #Medium #String #Math #Simulation #Data_Structure_II_Day_8_String #Programming_Skills_II_Day_4
// #Level_2_Day_2_String #2023_07_05_Time_165_ms_(96.72%)_Space_36.1_MB_(67.21%)
class Solution {
private fun getIntArray(s: String): IntArray {
val chars = s.toCharArray()
val arr = IntArray(chars.size)
for (i in chars.indices) {
arr[i] = chars[i] - '0'
}
return arr
}
private fun convertToStr(res: IntArray, i: Int): String {
var index = i
val chars = StringBuffer()
while (index < res.size) {
chars.append(res[index].toString())
index++
}
return chars.toString()
}
fun multiply(num1: String, num2: String): String {
val arr1 = getIntArray(num1)
val arr2 = getIntArray(num2)
val res = IntArray(arr1.size + arr2.size)
var index = arr1.size + arr2.size - 1
for (i in arr2.indices.reversed()) {
var k = index--
for (j in arr1.indices.reversed()) {
res[k] += arr2[i] * arr1[j]
k--
}
}
index = arr1.size + arr2.size - 1
var carry = 0
for (i in index downTo 0) {
val temp = res[i] + carry
res[i] = temp % 10
carry = temp / 10
}
var i = 0
while (i < res.size && res[i] == 0) {
i++
}
return if (i > index) {
"0"
} else {
convertToStr(res, i)
}
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 1,594 |
LeetCode-in-Kotlin
|
MIT License
|
app/src/main/kotlin/kotlinadventofcode/2023/2023-05.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
import java.math.BigInteger
class `2023-05` : Day {
override fun runPartOneNoUI(input: String): String {
val (seeds, maps) = parseResourceMaps(input)
val mapsBySource = maps.associateBy { it.source }
return seeds.map { getLocationForSeed(it, mapsBySource) }.minOf { it.value }.toString()
}
override fun runPartTwoNoUI(input: String): String {
val (seeds, maps) = parseResourceMaps(input)
val mapsBySource = maps.associateBy { it.source }
return seeds
.map { it.value }
.windowed(2, 2)
.flatMap{ getLocationsForRanges(ResourceType.SEED, setOf(it[0]..it[0] + it[1]), mapsBySource).second }
.minOf { it.start }
.toString()
}
private val locationsBySeed: MutableMap<Resource, Resource> = mutableMapOf()
private fun getLocationForSeed(seed: Resource, mapsBySource: Map<ResourceType, ResourceMap>): Resource {
if (seed.type == ResourceType.LOCATION) return seed
locationsBySeed[seed]?.let { return it }
val location = getLocationForSeed(mapsBySource[seed.type]!!.map(seed), mapsBySource)
locationsBySeed[seed] = location
return location
}
private fun getLocationsForRanges(
sourceType: ResourceType,
ranges: Set<ClosedRange<BigInteger>>,
mapsBySource: Map<ResourceType, ResourceMap>
): Pair<ResourceType, Set<ClosedRange<BigInteger>>> {
val map = mapsBySource[sourceType]!!
val destinationType = map.destination
val destinationRanges = ranges.flatMap { map.mapRange(it) }.toSet()
return if (destinationType == ResourceType.LOCATION) {
Pair(destinationType, destinationRanges)
} else {
getLocationsForRanges(destinationType, destinationRanges, mapsBySource)
}
}
enum class ResourceType {
SEED, SOIL, FERTILIZER, WATER, LIGHT, TEMPERATURE, HUMIDITY, LOCATION;
}
data class Resource(val type: ResourceType, val value: BigInteger)
data class ResourceMap(val source: ResourceType, val destination: ResourceType, val ranges: List<MapRange>) {
fun map(resource: Resource): Resource {
if (resource.type != source) throw IllegalArgumentException()
val range = ranges.firstOrNull { it.sourceStart <= resource.value && resource.value < it.sourceStart + it.length }
?: return Resource(destination, resource.value)
val offset = resource.value - range.sourceStart
return Resource(destination, range.destinationStart + offset)
}
fun mapRange(range: ClosedRange<BigInteger>): Set<ClosedRange<BigInteger>> {
var unmappedRanges = setOf(range)
val result = mutableSetOf<ClosedRange<BigInteger>>()
for (mapRange in ranges) {
val newUnmappedRanges = mutableSetOf<ClosedRange<BigInteger>>()
for (unmappedRange in unmappedRanges) {
val (mappedRange, remainingRange) = mapRange(unmappedRange, mapRange)
mappedRange?.let { result.add(it) }
newUnmappedRanges += remainingRange
}
unmappedRanges = newUnmappedRanges
}
result += unmappedRanges
return result
}
private data class MapRangeResult(val mappedRange: ClosedRange<BigInteger>?, val remainingRange: Set<ClosedRange<BigInteger>>)
private fun mapRange(sourceRange: ClosedRange<BigInteger>, mapRange: MapRange): MapRangeResult {
fun ClosedRange<BigInteger>.intersection(other: ClosedRange<BigInteger>): ClosedRange<BigInteger>? {
val start = maxOf(this.start, other.start)
val end = minOf(this.endInclusive, other.endInclusive)
return if (start <= end) start..end else null
}
val intersection = sourceRange.intersection(mapRange.sourceRange)
?: return MapRangeResult(null, setOf(sourceRange))
val mappedRange =
mapRange.destinationStart + intersection.start - mapRange.sourceStart..mapRange.destinationStart + intersection.endInclusive - mapRange.sourceStart
val remainingRange = mutableSetOf<ClosedRange<BigInteger>>()
if (sourceRange.start < intersection.start) {
remainingRange.add(sourceRange.start..intersection.start - BigInteger.ONE)
}
if (sourceRange.endInclusive > intersection.endInclusive) {
remainingRange.add(mapRange.sourceStart + mapRange.length..sourceRange.endInclusive)
}
return MapRangeResult(mappedRange, remainingRange)
}
}
data class MapRange(val destinationStart: BigInteger, val sourceStart: BigInteger, val length: BigInteger) {
val sourceRange = sourceStart..sourceStart + length - BigInteger.ONE
}
private fun parseResourceMaps(input: String): Pair<List<Resource>, List<ResourceMap>> {
val grammar = object : Grammar<Pair<List<Resource>,List<ResourceMap>>>() {
// tokens
val seedsLit by literalToken("seeds: ")
val newlineLit by literalToken("\n")
val colonLit by literalToken(":")
val spaceLit by literalToken(" ")
val dashLit by literalToken("-")
val seedLit by literalToken("seed")
val soilLit by literalToken("soil")
val fertilizerLit by literalToken("fertilizer")
val waterLit by literalToken("water")
val lightLit by literalToken("light")
val temperatureLit by literalToken("temperature")
val humidityLit by literalToken("humidity")
val locationLit by literalToken("location")
val mapLit by literalToken("map")
val toLit by literalToken("to")
val positiveIntRegex by regexToken("\\d+")
// parsers
val positiveInt by positiveIntRegex use { text.toBigInteger() }
val seedResource by positiveInt map { Resource(ResourceType.SEED, it) }
val seeds by skip(seedsLit) and separatedTerms(seedResource, spaceLit)
val seed by seedLit use { ResourceType.SEED }
val soil by soilLit use { ResourceType.SOIL }
val fertilizer by fertilizerLit use { ResourceType.FERTILIZER }
val water by waterLit use { ResourceType.WATER }
val light by lightLit use { ResourceType.LIGHT }
val temperature by temperatureLit use { ResourceType.TEMPERATURE }
val humidity by humidityLit use { ResourceType.HUMIDITY }
val location by locationLit use { ResourceType.LOCATION }
val resource by (seed or soil or fertilizer or water or light or temperature or humidity or location)
val range by (positiveInt and skip(spaceLit) and positiveInt and skip(spaceLit) and positiveInt) map { MapRange(it.t1, it.t2, it.t3) }
val ranges by separatedTerms(range, newlineLit)
val resourceMap by (resource and skip(dashLit) and skip(toLit) and skip(dashLit) and resource and skip(spaceLit) and
skip(mapLit) and skip(colonLit) and skip(newlineLit) and ranges) map { ResourceMap(it.t1, it.t2, it.t3) }
val resourceMaps by separatedTerms(resourceMap, newlineLit and newlineLit)
override val rootParser by (seeds and skip(zeroOrMore(newlineLit)) and resourceMaps) map { Pair(it.t1, it.t2) }
}
return grammar.parseToEnd(input)
}
override val defaultInput = """seeds: 3943078016 158366385 481035699 103909769 3553279107 15651230 3322093486 189601966 2957349913 359478652 924423181 691197498 2578953067 27362630 124747783 108079254 1992340665 437203822 2681092979 110901631
seed-to-soil map:
2702707184 1771488746 32408643
1838704579 89787943 256129587
3308305769 3945110092 140077818
3628160213 4264964536 30002760
3481822196 4118626519 146338017
2314039806 0 23017018
2094834166 23017018 66770925
13529560 2374830476 266694587
1360948085 2280951884 93878592
2337056824 1405838386 365650360
2735115827 1389537903 16300483
2161605091 1122407194 152434715
2944685788 3581490111 363619981
3448383587 4085187910 33438609
293095451 1923371965 152989927
555976625 1361056107 28481796
0 2076361892 13529560
4055868219 3342391034 239099077
3658162973 2944685788 397705246
446085378 2641525063 109891247
584458421 685760755 436646439
1647644147 2089891452 191060432
1528169571 1832460171 90911794
1619081365 1803897389 28562782
280224147 1348184803 12871304
1021104860 345917530 339843225
1454826677 1274841909 73342894
soil-to-fertilizer map:
370579153 1660655546 474809840
1390384163 3890794774 29044725
3933903064 3062217622 43562309
2579648014 2135465386 381757066
3905615715 3862507425 28287349
4053211235 382332912 208377334
3718132574 4107484155 187483141
3977465373 306587050 75745862
1866333065 230994048 75593002
1268904151 2940737610 121480012
3646057320 3790432171 72075254
845388993 2517222452 423515158
2291172026 769577840 288475988
4261588569 3919839499 33378727
2112304432 590710246 178867594
1419428888 1213751369 446904177
2961405080 3105779931 684652240
230994048 3967899050 139585105
2097623608 3953218226 14680824
1941926067 1058053828 155697541
fertilizer-to-water map:
0 1551952886 33233684
961721436 932763195 63696624
2767354703 3875238046 18117484
3717194106 2676555200 188038931
799543557 483022915 162177879
2428347038 3081230279 28566103
2872288153 3519235797 218585862
215425000 1162608123 279396952
1473270503 411403786 71619129
2762028477 2930057227 5326226
3263853515 2169144956 62130350
3330983617 2935383453 10086546
2522376237 2231275306 106924906
2757818051 2103190872 4210426
3090874015 3187643516 172979500
2785472187 2530367956 37190043
1365587214 49710602 107683289
554985341 330919476 80484310
3639346972 3109796382 77847134
1964878739 1442005075 21531118
2098191120 3737821659 137416387
1832452033 298110266 32809210
2456913141 2864594131 65463096
1025418060 1606654056 340169154
2277580887 2475812485 29651215
2416229303 2107401298 12117735
33233684 176973083 62797441
157085258 239770524 58339742
2307232102 2567557999 108997201
1915168137 0 49710602
2235607507 3893355530 41973380
1865261243 1502045992 49906894
3905233037 3935328910 231121478
494821952 157393891 19579192
514401144 996459819 40584197
4136354515 3360623016 158612781
3503586692 2945469999 135760280
635469651 1463536193 38509799
2629301143 4166450388 128516908
2822662230 2119519033 49625923
3325983865 2098191120 4999752
3341070163 2338200212 137612273
3478682436 2505463700 24904256
96031125 1971548655 36328688
1986409857 1585186570 21467486
673979450 1037044016 125564107
1544889632 645200794 287562401
132359813 1946823210 24725445
water-to-light map:
3326310943 1150412752 87200223
4257088620 4233111242 37878676
3994159838 4060724644 54228568
3876001808 4114953212 90976210
2886658207 1485800780 134153427
3966978018 4205929422 27181820
4048388406 3874470488 149045901
528406865 502600485 237825862
111547576 1241598488 111964267
3068561383 1485461466 339314
3168255879 3056441319 158055064
3504257503 1453325844 32135622
2109734789 3372472386 240074722
3068900697 403245303 99355182
2027101388 740426347 82633401
1219093087 1970502974 808008301
3643122008 1951548756 18954218
2603944924 279757237 123488066
766232727 0 10960493
3712182589 4270989918 1531320
3536393125 2778511275 106728883
3482397575 1237612975 3985513
777193220 1763962961 71462615
1117452579 1680930659 83032302
3413511166 3214496383 46428427
2432743763 2885240158 171201161
0 3260924810 111547576
3486383088 1835425576 17874415
3672475952 3703073187 39706637
848655835 10960493 268796744
4197434307 4023516389 37208255
3459939593 823059748 22457982
2727432990 1853299991 98248765
4234642562 4272521238 22446058
3713713909 3672475952 30597235
2351588880 1353562755 81154883
223511843 845517730 304895022
3744311144 3742779824 131690664
1200484881 1434717638 18608206
3020811634 3612547108 47749749
2349809511 3660296857 1779369
2825681755 1619954207 60976452
light-to-temperature map:
252460180 3718023854 80580651
3778113118 1519654737 306188725
333040831 2573805517 96168275
4084301843 3798604505 210665453
1694244932 1825843462 379128459
1487313708 2669973792 206931224
429209106 2876905016 268167573
3133421217 3610326681 107697173
1486370741 3145072589 942967
697376679 3146015556 464311125
2152115592 836439718 249469053
3241118390 214400336 17576418
214400336 1164650972 38059844
2073373391 1085908771 78742201
1161687804 2248952614 324682937
3258694808 231976754 268511965
3527206773 1312729085 206925652
3133251251 2573635551 169966
2930227394 4091943439 203023857
2484258126 790765872 45673846
2639950241 500488719 290277153
2529931972 1202710816 110018269
2401584645 4009269958 82673481
3734132425 2204971921 43980693
temperature-to-humidity map:
168091833 268406932 76258451
3449803430 2843367435 19310453
2007621581 1615073306 528954706
1947960540 798304921 59661041
3469113883 3441273912 247683303
3980335429 3688957215 155495519
1382488646 1289756018 231480201
1613968847 2144028012 203484286
3030343754 2862677888 310561319
311459258 1257812898 31943120
3716797186 4024477040 263538243
743249314 734822904 63482017
2843367435 4288015283 6952013
244350284 201297958 67108974
806731331 549427536 185395368
33679712 344665383 134412121
1817453133 1521236219 93837087
2850319448 3844452734 180024306
1193424657 2347512298 189063989
992126699 0 201297958
3340905073 3173239207 108898357
343402378 857965962 399846936
0 479077504 33679712
4135830948 3282137564 159136348
1911290220 512757216 36670320
humidity-to-location map:
1586270647 2666237958 31388199
1639118951 2401662894 243114959
673413244 1218441073 9004417
4189219561 4197782169 97185127
339701505 993997384 224443689
2088925654 1227445490 16145987
3048450614 2034241441 196558736
3245009350 3057456069 37064056
1990947272 217743214 23964128
755791330 433456361 436687719
3750378482 1243591477 29460651
1347952933 3094520125 238317714
682417661 3593572644 73373669
1891967948 3494593320 98979324
2746577216 1325573050 27089148
90823161 3346797254 147796066
238619227 1933159163 101082278
2884769306 269775053 163681308
564145194 0 109268050
2014911400 1273052128 12916400
2773666364 1295702566 29870484
0 903174223 90823161
4286404688 3841991082 8562608
1617658846 2644777853 21460105
2714916854 3748178771 31660362
2275934358 3332837839 13959415
2027827800 870144080 33030143
3841991082 4158641967 39140202
3881131284 3850553690 308088277
3390548570 2697626157 359829912
1882233910 1285968528 9734038
2105071641 2230800177 170862717
1192479049 1777685279 155473884
2803536848 3666946313 81232458
2289893773 1352662198 425023081
2060857943 241707342 28067711
3282073406 109268050 108475164"""
}
| 0 |
Kotlin
| 0 | 3 |
26ef6b194f3e22783cbbaf1489fc125d9aff9566
| 15,091 |
kotlinadventofcode
|
MIT License
|
pagination/common/src/commonMain/kotlin/dev/inmo/micro_utils/pagination/Pagination.kt
|
InsanusMokrassar
| 295,712,640 | false |
{"Kotlin": 1002757, "Python": 2464, "Shell": 1071}
|
package dev.inmo.micro_utils.pagination
import dev.inmo.micro_utils.common.intersect
import kotlin.math.ceil
import kotlin.math.floor
/**
* Base interface of pagination
*
* If you want to request something, you should use [SimplePagination]. If you need to return some result including
* pagination - [PaginationResult]
*/
interface Pagination : ClosedRange<Int> {
/**
* Started with 0.
* Number of page inside of pagination. Offset can be calculated as [page] * [size]
*/
val page: Int
/**
* Can be 0, but can't be < 0
* Size of current page. Offset can be calculated as [page] * [size]
*/
val size: Int
override val start: Int
get() = page * size
override val endInclusive: Int
get() = start + size - 1
}
fun Pagination.intersect(
other: Pagination
): Pagination? = (this as ClosedRange<Int>).intersect(other as ClosedRange<Int>) ?.let {
PaginationByIndexes(it.first, it.second)
}
/**
* Logical shortcut for comparison that page is 0
*/
inline val Pagination.isFirstPage
get() = page == 0
/**
* First number in index of objects. It can be used as offset for databases or other data sources
*/
val Pagination.firstIndex: Int
get() = start
/**
* Last number in index of objects. In fact, one [Pagination] object represent data in next range:
*
* [[firstIndex], [lastIndex]]; That means, that for [Pagination] with [Pagination.size] == 10 and [Pagination.page] == 1
* you will retrieve [Pagination.firstIndex] == 10 and [Pagination.lastIndex] == 19. Here [Pagination.lastIndexExclusive] == 20
*/
val Pagination.lastIndexExclusive: Int
get() = endInclusive + 1
/**
* Last number in index of objects. In fact, one [Pagination] object represent data in next range:
*
* [[firstIndex], [lastIndex]]; That means, that for [Pagination] with [Pagination.size] == 10 and [Pagination.page] == 1
* you will retrieve [Pagination.firstIndex] == 10 and [Pagination.lastIndex] == 19.
*/
val Pagination.lastIndex: Int
get() = endInclusive
/**
* Calculates pages count for given [datasetSize]
*/
fun calculatePagesNumber(datasetSize: Long, pageSize: Int): Int {
return ceil(datasetSize.toDouble() / pageSize).toInt()
}
/**
* Calculates pages count for given [datasetSize]. As a fact, it is shortcut for [calculatePagesNumber]
* @return calculated page number which can be correctly used in [PaginationResult] as [PaginationResult.page] value
*/
fun calculatePagesNumber(pageSize: Int, datasetSize: Long): Int = calculatePagesNumber(datasetSize, pageSize)
/**
* Calculates pages count for given [datasetSize]
*/
fun calculatePagesNumber(datasetSize: Int, pageSize: Int): Int =
calculatePagesNumber(
datasetSize.toLong(),
pageSize
)
/**
* @return calculated page number which can be correctly used in [PaginationResult] as [PaginationResult.page] value
*/
fun calculatePage(firstIndex: Int, resultsSize: Int): Int = if (resultsSize > 0) {
floor(firstIndex.toFloat() / resultsSize).toInt()
} else {
0
}
| 9 |
Kotlin
| 2 | 27 |
f2857ee2becf3fa5b51978f25360dc153dff342b
| 3,050 |
MicroUtils
|
Apache License 2.0
|
archive/src/main/kotlin/com/grappenmaker/aoc/year16/Day10.kt
|
770grappenmaker
| 434,645,245 | false |
{"Kotlin": 409647, "Python": 647}
|
package com.grappenmaker.aoc.year16
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.product
import kotlin.math.max
import kotlin.math.min
private const val outputMask = 0xff0000
fun PuzzleSet.day10() = puzzle {
val insns = inputLines.map { l ->
val parts = l.split(" ")
val nums = parts.mapNotNull { it.toIntOrNull() }
when {
l.startsWith("bot") -> GiveInstruction(
nums[0],
nums[1] or if (parts[5] == "output") outputMask else 0,
nums[2] or if (parts[10] == "output") outputMask else 0,
)
l.startsWith("value") -> ValueInstruction(nums[1], nums[0])
else -> error("Unexpected insn $l")
}
}
val bots = insns
.filterIsInstance<ValueInstruction>().groupBy { it.index }
.mapValues { (_, values) -> values.map { it.value }.toMutableList() }.toMutableMap()
.withDefault { mutableListOf() }
fun MutableMap<Int, MutableList<Int>>.bot(index: Int) = getOrPut(index) { mutableListOf() }
val rules = insns.filterIsInstance<GiveInstruction>()
while (true) {
val toApply = rules.filter { (idx) -> bots.bot(idx).size == 2 }
if (toApply.isEmpty()) break
toApply.forEach { (index, lowTo, highTo) ->
val current = bots.bot(index)
val (a, b) = current
val low = min(a, b)
val high = max(a, b)
if (low == 17 && high == 61) partOne = index.s()
bots.bot(lowTo).also { assert(it.size < 2) } += low
bots.bot(highTo).also { assert(it.size < 2) } += high
current.clear()
}
}
partTwo = (0..2).map { bots.bot(it or outputMask).single() }.product().s()
}
sealed interface BotInstruction
data class GiveInstruction(val index: Int, val lowTo: Int, val highTo: Int) : BotInstruction
data class ValueInstruction(val index: Int, val value: Int) : BotInstruction
| 0 |
Kotlin
| 0 | 7 |
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
| 1,970 |
advent-of-code
|
The Unlicense
|
src/main/kotlin/no/uib/inf273/operators/MaximizeSimilarity.kt
|
elgbar
| 237,403,030 | false |
{"Kotlin": 141160}
|
package no.uib.inf273.operators
import no.uib.inf273.Logger
import no.uib.inf273.processor.Solution
/**
* Find the vessel with least similarity and try and maximize it.
*
* The implementation does not satisfy the quality or speed need from the custom operators.
* It reasonably quickly find what cargoes are misfit in a vessel but this does not mean that those two are actually
* a bad solution. Consider the following scenario: We have three cargoes A, B, and C.
* Destination of A is close to origin of B and destination of B is close to origin of C. This might then be an okay solution but for this operator
* A and C are very dissimilar so it tries to remove one of them, resulting in a worse solution.
*
*
*
* @author Elg
*/
object MaximizeSimilarity : Operator() {
init {
log.logLevel = Logger.TRACE
log.logLevelLocked = true //force the loglevel to be what it is now
}
override fun operate(sol: Solution) {
val subs = sol.splitToSubArray(true)
val validVessels = findVessels(sol, subs)
if (validVessels.isEmpty()) {
log.debug { "No valid vessels have two or more cargoes" }
return
}
var maxSim = 0.0
var vIndex = INVALID_VESSEL
//now find the vessel that is least similar to each other
for ((i, sub) in validVessels) {
val similarity = sol.data.getRouteSimilarityScore(i, sub)
if (maxSim < similarity) {
maxSim = similarity
vIndex = i
}
}
//TODO The maximum similarity should not be changed if it is below a certain threshold
// But is this value too low? too high? What if all cargoes are very similar? very dissimilar?
// A bad solution to this is to remove this check...
if (maxSim < 0.05) {
log.debug { "Cargoes in all vessels are so similar for this operator, nothing will be done" }
return
}
val sub = subs[vIndex]
log.debug {
"Vessel $vIndex have the least similarity: ${sol.data.getRouteSimilarityScore(vIndex, sub)} | " +
"array = ${sub.contentToString()} = ${subs[vIndex].contentToString()}"
}
//we have now selected the least similar vessel in the solution
//but how to make it more similar?
// remove the one that fit worst in the vessel? where to move that?
//For now find what caro is least similar
/**
* @return Pair of most fitting vessel and the similarity score
*/
fun findMostFittingVessel(cargo: Int): MutableList<Triple<Int, Int, Double>> {
val list = ArrayList<Triple<Int, Int, Double>>()
for ((vi, vSub) in subs.withIndex()) {
if (!sol.data.canVesselTakeCargo(vi, cargo) || vi == vIndex || sol.data.isDummyVessel(vi)) continue
val cargoes = vSub.toSet()
val avg = sol.data.getSimilarityMap(vIndex).filterKeys { (c1, c2) ->
cargoes.contains(c1) && cargoes.contains(c2) || c1 == cargo || c2 == cargo
}.values.average()
list += Triple(cargo, vi, avg)
}
return list
}
val map =
sol.data.getRouteSimilarity(vIndex, subs[vIndex]).toList().sortedByDescending { it.second }.map { it.first }
outer@
for ((cargoA, cargoB) in map) {
log.debug {
"Checking cargo $cargoA & $cargoB | array = ${sub.contentToString()} = ${subs[vIndex].contentToString()}"
}
val a = findMostFittingVessel(cargoA).apply {
addAll(findMostFittingVessel(cargoB))
sortBy { it.third }
}
for ((cargo, vi, fitness) in a) {
log.debug {
"Maybe move cargo $cargo to $vi | array = ${sub.contentToString()} = ${subs[vIndex].contentToString()}"
}
if (fitness >= maxSim) {
//the rest of the solutions are worse than this one give up on this iterator
break
}
if (moveCargo(sol, subs, orgVesselIndex = vIndex, destVesselIndex = vi, cargoId = cargo)) {
log.debug { "Successfully moved cargo to $vIndex" }
break@outer
}
}
}
}
}
| 0 |
Kotlin
| 0 | 3 |
1f76550a631527713b1eba22817e6c1215f5d84e
| 4,449 |
INF273
|
The Unlicense
|
processor/src/main/kotlin/com/misterpemodder/aoc2022/SolutionProcessor.kt
|
MisterPeModder
| 573,061,300 | false |
{"Kotlin": 87294}
|
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.misterpemodder.aoc2022
import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSFile
import com.google.devtools.ksp.validate
class SolutionProcessor(private val codeGenerator: CodeGenerator) : SymbolProcessor {
private val solutions: MutableList<Triple<Int, Int, String>> = mutableListOf()
private val dependencies: MutableSet<KSFile> = mutableSetOf()
override fun process(resolver: Resolver): List<KSAnnotated> {
val symbols =
resolver.getSymbolsWithAnnotation("com.misterpemodder.aoc2022.RegisterSolution")
val (solutionClasses, nonProcessed) = symbols.filterIsInstance<KSClassDeclaration>()
.partition(KSClassDeclaration::validate)
dependencies += solutionClasses.asSequence().mapNotNull(KSClassDeclaration::containingFile)
for (solutionClass in solutionClasses) {
val (year, day) = getAocYearAndDay(solutionClass)
solutions += Triple(year, day, solutionClass.qualifiedName!!.asString())
}
return nonProcessed
}
override fun finish() {
val packageName = "com.misterpemodder.aoc2022.generated"
val className = "Solutions"
val solutions = solutions.joinToString(separator = "\n ") { (year, day, name) ->
"solutions.put(Pair($year, $day), \"$name\")"
}
codeGenerator.createNewFile(
Dependencies(
aggregating = true,
sources = dependencies.toTypedArray()
), packageName, className
).use { file ->
file.write(
"""
package $packageName
object $className {
private val SOLUTION_NAMES_BY_YEAR_AND_DAY: Map<Pair<Int, Int>, String>;
init {
val solutions = mutableMapOf<Pair<Int, Int>, String>()
$solutions
SOLUTION_NAMES_BY_YEAR_AND_DAY = solutions
}
fun getName(year: Int, day: Int): String? = SOLUTION_NAMES_BY_YEAR_AND_DAY.get(Pair(year, day))
}""".trimIndent().toByteArray()
)
}
}
}
private fun getAocYearAndDay(classDef: KSClassDeclaration): Pair<Int, Int> {
val args =
classDef.annotations.find { it.shortName.getShortName() == "RegisterSolution" }!!.arguments
val year = args.find { it.name?.getShortName() == "year" }!!.value!! as Int
val day = args.find { it.name?.getShortName() == "day" }!!.value!! as Int
return Pair(year, day)
}
class SolutionProcessorProvider : SymbolProcessorProvider {
override fun create(environment: SymbolProcessorEnvironment) =
SolutionProcessor(environment.codeGenerator)
}
| 0 |
Kotlin
| 0 | 0 |
af1b258325a7bd036a47b5395c90bbac42bbd337
| 3,392 |
AdventOfCode2022
|
Apache License 2.0
|
src/shmp/lang/language/derivation/ChangeHistory.kt
|
ShMPMat
| 240,860,070 | false | null |
package shmp.lang.language.derivation
import shmp.lang.generator.util.GeneratorException
import shmp.lang.language.lexis.Word
import shmp.lang.language.lineUp
interface ChangeHistory {
fun printHistory(parent: Word): String
val changeDepth: Int
}
data class DerivationHistory(val derivation: Derivation, val previous: Word) : ChangeHistory {
override fun printHistory(parent: Word) =
constructChangeTree(listOf(previous), parent, derivation.dClass.toString())
override val changeDepth: Int
get() = 1 + (previous.semanticsCore.changeHistory?.changeDepth ?: 0)
}
data class CompoundHistory(val compound: Compound, val previous: List<Word>) : ChangeHistory {
override fun printHistory(parent: Word) =
constructChangeTree(previous, parent, compound.infix.toString())
override val changeDepth: Int
get() = 1 + (previous.map { it.semanticsCore.changeHistory?.changeDepth ?: 0 }.max() ?: 0)
}
private fun constructChangeTree(previousWords: List<Word>, parentWord: Word, arrowLabel: String): String {
val (maxDepthString, maxDepth) = previousWords.maxByOrNull { it.semanticsCore.changeDepth }
?.let { it.printChange() to it.semanticsCore.changeDepth }
?: throw GeneratorException("Empty word list has been given")
val indexes = getIndexes(maxDepthString)
val prefix = previousWords
.map { it.semanticsCore.changeDepth to it.printChange() }
.joinToString("\n") { (d, s) ->
s.lines().joinToString("\n") {
" ".repeat(indexes.elementAtOrNull(maxDepth - d) ?: indexes.last()) + it
}
}
val prefixWithArrows = prefix.lines().lineUp()
.joinToString("\n") { "$it ->$arrowLabel-> " }
.lines()
val (lanPrefix, commentPrefix) = prefixWithArrows.takeLast(2)
val (lanPostfix, commentPostfix) = lineUp(parentWord.toString(), parentWord.semanticsCore.toString())
return prefixWithArrows.dropLast(2).joinToString("") { "$it\n" } +
lanPrefix + lanPostfix + "\n" +
commentPrefix + commentPostfix
}
private fun getIndexes(maxDepthString: String): List<Int> {
val (oneLine) = maxDepthString.lines()
val indexes = mutableListOf(0)
var index = 0
while (true) {
index = oneLine.indexOf("->", index + 1)
index = oneLine.indexOf("->", index + 1)
if (index == -1)
break
indexes += index + 3
}
return indexes
}
private fun Word.printChange() = semanticsCore.changeHistory?.printHistory(this)
?: lineUp(toString(), semanticsCore.toString()).let { (f, s) -> "$f\n$s" }
| 0 |
Kotlin
| 0 | 1 |
4d26b0d50a1c3c6318eede8dd9678d3765902d4b
| 2,628 |
LanguageGenerator
|
MIT License
|
src/main/kotlin/org/olafneumann/regex/generator/utils/IntRange.kt
|
noxone
| 239,624,807 | false |
{"Kotlin": 246877, "HTML": 22083, "CSS": 5034, "C": 2817, "Dockerfile": 1748, "JavaScript": 220}
|
package org.olafneumann.regex.generator.utils
fun IntRange.hasIntersectionWith(other: IntRange): Boolean {
return (this.first <= other.first && this.last >= other.first)
|| (other.first <= this.first && other.last >= this.first)
}
val IntRange.length: Int get() = endInclusive - first + 1
val IntRange.center: Int get() = (first + last) / 2
fun IntRange.containsAndNotOnEdges(value: Int): Boolean =
value > this.first && value < this.last
fun IntRange.containsAndNotOnEdges(value: IntRange): Boolean =
containsAndNotOnEdges(value.first) && containsAndNotOnEdges(value.last)
fun IntRange.addPosition(index: Int): IntRange =
if (index <= first) {
IntRange(first + 1, last + 1)
} else if (index <= last) {
IntRange(first, last + 1)
} else {
this
}
fun IntRange.add(rangeToAdd: IntRange): List<IntRange> {
return if (rangeToAdd.first < this.first) {
listOf(IntRange(this.first + rangeToAdd.length, this.last + rangeToAdd.length))
} else if (rangeToAdd.first == this.first) {
(rangeToAdd.first..(rangeToAdd.last + 1))
.map { it..(this.last + rangeToAdd.length) }
} else if (rangeToAdd.first > this.first && rangeToAdd.first <= this.last) {
listOf(IntRange(this.first, this.last + rangeToAdd.length))
} else if (rangeToAdd.first == this.last + 1) {
(0..rangeToAdd.length).map { this.first..(this.last + it) }
} else {
listOf(this)
}
}
fun IntRange.remove(rangeToRemove: IntRange): List<IntRange> {
return if (rangeToRemove.last < this.first) {
listOf(IntRange(this.first - rangeToRemove.length, this.last - rangeToRemove.length))
} else if (rangeToRemove.first > this.last) {
listOf(this)
} else if (rangeToRemove.first <= this.first && rangeToRemove.last >= this.last) {
emptyList()
} else if (rangeToRemove.first >= this.first && rangeToRemove.last <= this.last) {
listOf(IntRange(this.first, this.last - rangeToRemove.length))
} else if (rangeToRemove.first <= this.first && rangeToRemove.last > this.first) {
listOf(IntRange(rangeToRemove.first, this.last - rangeToRemove.length))
} else if (rangeToRemove.first <= this.last && rangeToRemove.last > this.last) {
listOf(IntRange(this.first, rangeToRemove.first - 1))
} else {
listOf(this)
}
}
| 13 |
Kotlin
| 69 | 355 |
001cc69d2592afa70b492441e119753789494816
| 2,377 |
regex-generator
|
MIT License
|
kotlin/1851-minimum-interval-to-include-each-query.kt
|
neetcode-gh
| 331,360,188 | false |
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
|
class Solution {
fun minInterval(intervals: Array<IntArray>, _queries: IntArray): IntArray {
intervals.sortWith(compareBy( {it[0]}, { it[1]}))
val queries = _queries.withIndex().sortedBy { it.value }
val minHeap = PriorityQueue<IntArray> (compareBy( { it[0] }, { it[1] }))
val res = IntArray (queries.size)
var i = 0
queries.forEach { (idx, q) ->
while (i < intervals.size && intervals[i][0] <= q) {
val (l, r) = intervals[i]
minHeap.add(intArrayOf(r - l + 1, r))
i++
}
while (minHeap.isNotEmpty() && minHeap.peek()[1] < q)
minHeap.poll()
res[idx] = if (minHeap.isEmpty()) -1 else minHeap.peek()[0]
}
return res
}
}
| 337 |
JavaScript
| 2,004 | 4,367 |
0cf38f0d05cd76f9e96f08da22e063353af86224
| 816 |
leetcode
|
MIT License
|
src/chapter3/section5/ex24_NonOverlappingIntervalSearch.kt
|
w1374720640
| 265,536,015 | false |
{"Kotlin": 1373556}
|
package chapter3.section5
/**
* 不重叠的区间查找
* 给定对象的一组互不重叠的区间,编写一个函数接受一个对象作为参数并判断它是否存在于其中任何一个区间内
* 例如,如果对象是整数而区间为1643-2033,5532-7643,8998-10332,5666653-5669321
* 那么查询9122的结果为在第三个区间,而8122的结果不在任何区间
*
* 解:Kotlin中有自带的区间类[kotlin.ranges.IntRange],先对区间数组按起始位置排序,再对数组二分查找
*/
fun ex24_NonOverlappingIntervalSearch(rangeArray: Array<IntRange>, key: Int): IntRange? {
rangeArray.sortBy { it.first }
val index = searchInRangeArray(rangeArray, key)
return if (index == -1) null else rangeArray[index]
}
private fun searchInRangeArray(rangeArray: Array<IntRange>, key: Int): Int {
var low = 0
var high = rangeArray.size - 1
while (low <= high) {
val mid = (low + high) / 2
val midRange = rangeArray[mid]
when {
key in midRange -> return mid
key < midRange.first -> high = mid - 1
else -> low = mid + 1
}
}
return -1
}
fun main() {
val rangeArray = arrayOf(1643..2033, 5532..7643, 8998..10332, 5666653..5669321)
println(ex24_NonOverlappingIntervalSearch(rangeArray, 9122))
println(ex24_NonOverlappingIntervalSearch(rangeArray, 8122))
}
| 0 |
Kotlin
| 1 | 6 |
879885b82ef51d58efe578c9391f04bc54c2531d
| 1,402 |
Algorithms-4th-Edition-in-Kotlin
|
MIT License
|
src/main/kotlin/dev/shtanko/algorithms/exercises/StringPermutations.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.exercises
fun interface StringPermutations {
fun perform(str: String, ans: String): Array<String>
}
class StringPermutationsRecursive : StringPermutations {
val list: MutableList<String> = ArrayList()
override fun perform(str: String, ans: String): Array<String> {
if (str.isEmpty()) {
list.add(ans)
return arrayOf()
}
for (i in str.indices) {
val ch = str[i]
val ros = str.substring(0, i) + str.substring(i + 1)
perform(ros, ans + ch)
}
return list.toTypedArray()
}
}
class StringPermutationsIterative : StringPermutations {
val list: MutableList<String> = ArrayList()
override fun perform(str: String, ans: String): Array<String> {
if (str.isEmpty()) {
list.add(ans)
return arrayOf()
}
val alpha = BooleanArray(ALPHA_SIZE)
for (i in str.indices) {
val ch = str[i]
val ros = str.substring(0, i) + str.substring(i + 1)
if (!alpha[ch - 'a']) {
perform(ros, ans + ch)
}
alpha[ch - 'a'] = true
}
return list.toTypedArray()
}
companion object {
private const val ALPHA_SIZE = 26
}
}
| 4 |
Kotlin
| 0 | 19 |
776159de0b80f0bdc92a9d057c852b8b80147c11
| 1,914 |
kotlab
|
Apache License 2.0
|
src/Day10.kt
|
karloti
| 573,006,513 | false |
{"Kotlin": 25606}
|
import Instructions.*
sealed interface Instructions {
val value: Int
val cycle: Int
val total: Int
data class Noop(
override val value: Int = 0,
override val cycle: Int = cycle_++,
override val total: Int = total_,
) : Instructions
data class Addx(
override val value: Int,
override val cycle: Int = cycle_++,
override val total: Int = total_.apply { total_ += value }
) : Instructions
companion object {
private var cycle_ = 1
private var total_ = 1
}
}
fun List<String>.toInstructions(): List<Instructions> = buildList<Instructions> {
[email protected] {
if (it[0] == 'n') {
add(Noop())
} else {
add(Noop())
add(Addx(it.split(' ')[1].toInt()))
}
}
}
fun List<Instructions>.part1() = filter { (it.cycle - 20) % 40 == 0 }.take(6).sumOf { it.cycle * it.total }
fun List<Instructions>.part2() = map { if ((it.cycle - 1) % 40 - it.total in -1..1) "{}" else " " }
.chunked(40).joinToString("\n") { it.joinToString("") }
fun main() {
val instructions: List<Instructions> = readInput("Day10").toInstructions()
println(instructions.part1())
println()
println(instructions.part2())
}
| 0 |
Kotlin
| 1 | 2 |
39ac1df5542d9cb07a2f2d3448066e6e8896fdc1
| 1,281 |
advent-of-code-2022-kotlin
|
Apache License 2.0
|
src/Day01.kt
|
raneric
| 573,109,642 | false |
{"Kotlin": 13043}
|
fun main() {
fun part1(input: List<String>): Int {
var higherCal = Int.MIN_VALUE
var tempData = 0
input.map {
if (it.isNotEmpty()) {
tempData += it.toInt()
} else {
higherCal = higherCal.coerceAtLeast(tempData)
tempData = 0
}
}
return higherCal
}
fun part2(input: List<String>): Int {
val sum = ArrayList<Int>()
var tempData = 0
input.map {
if (it.isNotEmpty()) {
tempData += it.toInt()
} else {
sum.add(tempData)
tempData = 0
}
}
sum.sortDescending()
return sum.take(3).sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
9558d561b67b5df77c725bba7e0b33652c802d41
| 844 |
aoc-kotlin-challenge
|
Apache License 2.0
|
src/main/java/challenges/cracking_coding_interview/moderate/q6_smallest_difference/QuestionC.kt
|
ShabanKamell
| 342,007,920 | false | null |
package challenges.cracking_coding_interview.moderate.q6_smallest_difference
import java.util.*
object QuestionC {
private fun getClosestValue(array: IntArray, target: Int): Int {
var low = 0
var high = array.size - 1
var mid: Int
while (low <= high) {
mid = low + (high - low) / 2
if (array[mid] < target) {
low = mid + 1
} else if (array[mid] > target) {
high = mid - 1
} else {
return array[mid]
}
}
val valueA = if (low < 0 || low >= array.size) Int.MAX_VALUE else array[low]
val valueB = if (high < 0 || high >= array.size) Int.MAX_VALUE else array[high]
return if (Math.abs(valueA - target) < Math.abs(valueB - target)) valueA else valueB // return closest value
}
fun findSmallestDifference(shorter: IntArray, longer: IntArray): Int {
if (shorter.isEmpty() || longer.isEmpty()) return -1
if (shorter.size > longer.size) return findSmallestDifference(longer, shorter)
Arrays.sort(shorter)
var smallestDifference = Int.MAX_VALUE
for (target in longer) {
val closest = getClosestValue(shorter, target)
smallestDifference = Math.min(smallestDifference, Math.abs(closest - target))
}
return smallestDifference
}
@JvmStatic
fun main(args: Array<String>) {
val array1 = intArrayOf(1, 3, 15, 11, 2)
val array2 = intArrayOf(23, 127, 234, 19, 8)
val difference = findSmallestDifference(array1, array2)
println(difference)
}
}
| 0 |
Kotlin
| 0 | 0 |
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
| 1,638 |
CodingChallenges
|
Apache License 2.0
|
kotlin/05.kt
|
NeonMika
| 433,743,141 | false |
{"Kotlin": 68645}
|
class Day5 :
Day<List<Pair<Day5.Point, Day5.Point>>>("05") {
// Classes
data class Point(val x: Int, val y: Int) : Comparable<Point> {
operator fun rangeTo(other: Point) = sequence {
var cur = this@Point
yield(cur)
while (cur != other) {
cur = Point(cur.x + (other.x - cur.x).coerceIn(-1..1), cur.y + (other.y - cur.y).coerceIn(-1..1))
yield(cur)
}
}
fun sameX(otherPoint: Point) = x == otherPoint.x
fun sameY(otherPoint: Point) = y == otherPoint.y
companion object Factory {
fun fromString(str: String) = str.split(",").run { Point(get(0).toInt(), get(1).toInt()) }
}
override operator fun compareTo(other: Point): Int = when {
!sameX(other) -> x - other.x
else -> y - other.y
}
}
// Data
fun List<String>.data() =
map { it.split("->").map(String::trim).map(Point.Factory::fromString) }.map { it[0] to it[1] }
override fun dataStar1(lines: List<String>) = lines.data()
override fun dataStar2(lines: List<String>) = lines.data()
fun work(data: List<Pair<Point, Point>>, pairFilter: (Pair<Point, Point>) -> Boolean) =
data.filter(pairFilter)
.flatMap { (from, to) -> (from..to).toList() }
.groupingBy { it }.eachCount()
.count { (_, v) -> v >= 2 }
override fun star1(data: List<Pair<Point, Point>>): Number =
work(data) { it.first.sameX(it.second) || it.first.sameY(it.second) }
override fun star2(data: List<Pair<Point, Point>>): Number = work(data) { true }
}
fun main() {
Day5()()
}
| 0 |
Kotlin
| 0 | 0 |
c625d684147395fc2b347f5bc82476668da98b31
| 1,681 |
advent-of-code-2021
|
MIT License
|
src/main/kotlin/edu/rice/fset/HashFamily.kt
|
danwallach
| 362,519,139 | false | null |
package edu.rice.fset
import kotlin.math.ceil
import kotlin.math.sqrt
// We need to be able to leverage the usual hashCode() methods into a *family* of hash
// functions. This is challenging because many core Java classes have really simplistic
// hash functions. Of particular note, Integer.hashCode() just returns the same integer.
// Our solution is that we picked 14 large primes, where the high bits of those primes
// come from their position in the ordering (e.g., prime[0] starts with 0001-bits and
// prime[13] starts with 1110), and we multiply the output of the regular hashCode()
// method to get our new hash values. This means that several of these will be
// negative 32-bit signed integers.
// Why large primes? Because they're relatively prime to the modulus (2^31), we should
// be able to still generate the full set of 32-bit integers without repeats. Why a bunch
// of different large primes spread across this interval? So they'll behave differently
// from one another, while having the desired spreading behavior.
// These are used through the "familyHash" extension functions. Even familyHash1() is going
// to be preferable to the built-in hashCode() function, because even for degenerate cases
// like Integer.hashCode(), it will spread the results out.
internal fun isPrime(n: Long): Boolean {
if (n == 2L) {
return true
}
if (n and 1L == 0L) {
// any other even numbers are not prime
return false
}
var q: Long = 3
val stop = ceil(sqrt(n.toDouble())).toLong()
while (q < stop) {
if (n % q == 0L) return false
q = q + 2
}
return true
}
internal fun findPrimeAfter(start: Long): Long {
var n: Long =
if ((start and 1L) == 0L) {
start + 1
} else {
start
}
while (true) {
if (isPrime(n)) {
return n
}
n = n + 1
}
}
internal fun findOurPrimes(): List<Long> {
val startingPoints: List<Long> = (1L..14L).map {
// repeat these four bits eight times, giving us a broader distribution of starting points
(it shl 28) or (it shl 24) or (it shl 20) or (it shl 16) or
(it shl 12) or (it shl 8) or (it shl 4) or it
}
return startingPoints.map { findPrimeAfter(2_654_435_769L + it) }
}
// these values derived using the function above
internal val bigPrimes = longArrayOf(
2940766931L, 3227098129L, 3513429229L, 3799760401L,
4086091553L, 4372422701L, 4658753851L, 4945084993L, 5231416147L, 5517747349L, 5804078453L,
6090409621L, 6376740779L, 6663071941L
)
fun Any.familyHash1(): Int {
return (this.hashCode() * bigPrimes[0]).toInt()
}
fun Any.familyHash2(): IntArray {
val oHash = this.hashCode()
return intArrayOf(
(oHash * bigPrimes[6]).toInt(),
(oHash * bigPrimes[13]).toInt()
)
}
fun Any.familyHash4(): IntArray {
val oHash = this.hashCode()
return intArrayOf(
(oHash * bigPrimes[4]).toInt(),
(oHash * bigPrimes[7]).toInt(),
(oHash * bigPrimes[10]).toInt(),
(oHash * bigPrimes[13]).toInt()
)
}
fun Any.familyHash8(): IntArray {
val oHash = this.hashCode()
return intArrayOf(
(oHash * bigPrimes[0]).toInt(),
(oHash * bigPrimes[2]).toInt(),
(oHash * bigPrimes[4]).toInt(),
(oHash * bigPrimes[6]).toInt(),
(oHash * bigPrimes[7]).toInt(),
(oHash * bigPrimes[9]).toInt(),
(oHash * bigPrimes[11]).toInt(),
(oHash * bigPrimes[13]).toInt()
)
}
fun Any.familyHash14(): IntArray {
val oHash = this.hashCode()
return intArrayOf(
(oHash * bigPrimes[0]).toInt(),
(oHash * bigPrimes[1]).toInt(),
(oHash * bigPrimes[2]).toInt(),
(oHash * bigPrimes[3]).toInt(),
(oHash * bigPrimes[4]).toInt(),
(oHash * bigPrimes[5]).toInt(),
(oHash * bigPrimes[6]).toInt(),
(oHash * bigPrimes[7]).toInt(),
(oHash * bigPrimes[8]).toInt(),
(oHash * bigPrimes[9]).toInt(),
(oHash * bigPrimes[10]).toInt(),
(oHash * bigPrimes[11]).toInt(),
(oHash * bigPrimes[12]).toInt(),
(oHash * bigPrimes[13]).toInt(),
)
}
fun main() {
println("Searching for some big primes")
val primes = findOurPrimes()
println("Big primes: " + primes.joinToString(separator = ", "))
}
| 0 |
Kotlin
| 0 | 0 |
18972974f130c64762ae81d7106a1ec2fa5a51dc
| 4,375 |
fset-kotlin
|
MIT License
|
src/test/kotlin/io/noobymatze/aoc/y2022/Day14.kt
|
noobymatze
| 572,677,383 | false |
{"Kotlin": 90710}
|
package io.noobymatze.aoc.y2022
import io.noobymatze.aoc.Aoc
import kotlin.test.Test
class Day14 {
data class Pos(val row: Int, val col: Int) {
val downLeft: Pos get() = Pos(row + 1, col - 1)
val downRight: Pos get() = Pos(row + 1, col + 1)
val down: Pos get() = Pos(row + 1, col)
}
@Test
fun test() {
val rocks = Aoc.getInput(14)
.lineSequence()
.flatMap { line ->
line.split(" -> ").map {
val (col, row) = it.split(",").map(String::toInt)
Pos(row, col)
}.zipWithNext().flatMap { (from, to) ->
(minOf(from.row, to.row)..maxOf(from.row, to.row)).map {
Pos(it, from.col)
} + (minOf(from.col, to.col)..maxOf(from.col, to.col)).map {
Pos(from.row, it)
}
}.toSet()
}.toSet()
val sands = mutableSetOf<Pos>()
val start = Pos(0, 500)
println(printBoard(rocks, sands, start))
fun Pos.isBlocked(): Boolean =
this in sands || this in rocks
val maxRow = rocks.maxBy { it.row }.row
var sand = start
while (sand.row < maxRow) {
sand = when {
sand.down.isBlocked() && sand.downLeft.isBlocked() && sand.downRight.isBlocked() -> {
sands.add(sand)
start
}
sand.down.isBlocked() && sand.downLeft.isBlocked() ->
sand.downRight
sand.down.isBlocked() ->
sand.downLeft
else ->
sand.down
}
}
println(sands.size)
println(printBoard(rocks, sands, start))
}
@Test
fun test2() {
val rocks = Aoc.getInput(14)
.lineSequence()
.flatMap { line ->
line.split(" -> ").map {
val (col, row) = it.split(",").map(String::toInt)
Pos(row, col)
}.zipWithNext().flatMap { (from, to) ->
(minOf(from.row, to.row)..maxOf(from.row, to.row)).map {
Pos(it, from.col)
} + (minOf(from.col, to.col)..maxOf(from.col, to.col)).map {
Pos(from.row, it)
}
}.toSet()
}.toSet()
val sands = mutableSetOf<Pos>()
val start = Pos(0, 500)
println(printBoard(rocks, sands, start))
fun Pos.isBlocked(): Boolean =
this in sands || this in rocks
val maxRow = rocks.maxBy { it.row }.row + 2
var sand = start
while (!start.isBlocked()) {
sand = when {
sand.down.row == maxRow || (sand.down.isBlocked() && sand.downLeft.isBlocked() && sand.downRight.isBlocked()) -> {
sands.add(sand)
start
}
sand.down.isBlocked() && sand.downLeft.isBlocked() ->
sand.downRight
sand.down.isBlocked() ->
sand.downLeft
else ->
sand.down
}
}
println(sands.size)
println(printBoard(rocks, sands, start))
}
private fun printBoard(
rocks: Set<Pos>,
sands: Set<Pos>,
start: Pos,
): String {
val maxRow = rocks.maxBy { it.row }.row
val minCol = rocks.minBy { it.col }.col
val maxCol = rocks.maxBy { it.col }.col
return (0..maxRow).joinToString("\n") { row ->
(minCol..maxCol).joinToString("") { col ->
val pos = Pos(row, col)
when {
pos in rocks -> "#"
pos == start -> "+"
pos in sands -> "o"
else -> "."
}
}
}
}
}
| 0 |
Kotlin
| 0 | 0 |
da4b9d894acf04eb653dafb81a5ed3802a305901
| 3,997 |
aoc
|
MIT License
|
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[217]存在重复元素.kt
|
maoqitian
| 175,940,000 | false |
{"Kotlin": 354268, "Java": 297740, "C++": 634}
|
import java.util.*
import kotlin.collections.HashMap
//给定一个整数数组,判断是否存在重复元素。
//
// 如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
//
//
//
// 示例 1:
//
// 输入: [1,2,3,1]
//输出: true
//
// 示例 2:
//
// 输入: [1,2,3,4]
//输出: false
//
// 示例 3:
//
// 输入: [1,1,1,3,3,4,3,2,4,2]
//输出: true
// Related Topics 数组 哈希表
// 👍 338 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun containsDuplicate(nums: IntArray): Boolean {
//方法一
//一次遍历时间复杂度 O(NlogN)
if(nums.size<=1) return false
Arrays.sort(nums)
for(i in 0 until nums.size-1 ){
if(nums[i] == nums[i+1])return true
}
return false
//方法二 hashmap
val map = HashMap<Int,Int>()
for (i in nums.indices){
if(map.containsKey(nums[i])){
return true
}else{
map[nums[i]] = 1
}
}
return false
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 |
Kotlin
| 0 | 1 |
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
| 1,235 |
MyLeetCode
|
Apache License 2.0
|
src/y2023/Day24.kt
|
gaetjen
| 572,857,330 | false |
{"Kotlin": 325874, "Mermaid": 571}
|
package y2023
import io.ksmt.KContext
import io.ksmt.expr.KExpr
import io.ksmt.solver.z3.KZ3Solver
import io.ksmt.sort.KIntSort
import io.ksmt.utils.getValue
import util.generateTakes
import util.readInput
import util.timingStatistics
import java.math.BigDecimal
import java.math.RoundingMode
object Day24 {
data class Point3(
val x: Long,
val y: Long,
val z: Long
)
private fun parse(input: List<String>): List<Pair<Point3, Point3>> {
return input.map { line ->
val (p1, p2) = line.split("@").map { it.trim() }
val (x1, y1, z1) = p1.split(",").map { it.trim().toLong() }
val (x2, y2, z2) = p2.split(",").map { it.trim().toLong() }
Point3(x1, y1, z1) to Point3(x2, y2, z2)
}
}
fun part1(input: List<String>, testArea: LongRange): Int {
val parsed = parse(input)
val intersects = generateTakes(parsed, 2).filter { (stone1, stone2) ->
val pos = intersectsXY(stone1, stone2)
pos != null && testArea.contains(pos.first) && testArea.contains(pos.second)
}
return intersects.toList().size
}
fun LongRange.contains(value: BigDecimal): Boolean {
return value >= this.first.toBigDecimal() && value <= this.last.toBigDecimal()
}
fun intersectsXY(stone1: Pair<Point3, Point3>, stone2: Pair<Point3, Point3>): Pair<BigDecimal, BigDecimal>? {
val (p1, v1) = stone1
val (p2, v2) = stone2
if (v1.x.toDouble() / v1.y == v2.x.toDouble() / v2.y) {
return null
}
val m2t =
v1.x.toBigDecimal() * p1.y.toBigDecimal() + v1.y.toBigDecimal() * p2.x.toBigDecimal() - v1.x.toBigDecimal() * p2.y.toBigDecimal() - p1.x.toBigDecimal() * v1.y.toBigDecimal()
.setScale(4)
val m2b = v1.x.toBigDecimal() * v2.y.toBigDecimal() - v2.x.toBigDecimal() * v1.y.toBigDecimal()
val m2 = m2t.divide(m2b, RoundingMode.DOWN)
val m1 = (p2.x.toBigDecimal() + v2.x.toBigDecimal() * m2 - p1.x.toBigDecimal()).setScale(4)
.divide(v1.x.toBigDecimal(), RoundingMode.DOWN)
val x = p1.x.toBigDecimal() + v1.x.toBigDecimal() * m1
val y = p1.y.toBigDecimal() + v1.y.toBigDecimal() * m1
if (m1 < BigDecimal.ZERO || m2 < BigDecimal.ZERO) {
return null
}
return x to y
}
fun part2(input: List<String>): KExpr<KIntSort> {
val parsed = parse(input)
val ctx = KContext()
val (h1, h2, h3) = parsed.take(3)
with(ctx) {
val t1 by intSort
val t2 by intSort
val t3 by intSort
val x by intSort
val y by intSort
val z by intSort
val dx by intSort
val dy by intSort
val dz by intSort
val constraints = listOf(
t1 ge 0.expr,
t2 ge 0.expr,
t3 ge 0.expr,
x + dx * t1 eq h1.first.x.expr + h1.second.x.expr * t1,
x + dx * t2 eq h2.first.x.expr + h2.second.x.expr * t2,
x + dx * t3 eq h3.first.x.expr + h3.second.x.expr * t3,
y + dy * t1 eq h1.first.y.expr + h1.second.y.expr * t1,
y + dy * t2 eq h2.first.y.expr + h2.second.y.expr * t2,
y + dy * t3 eq h3.first.y.expr + h3.second.y.expr * t3,
z + dz * t1 eq h1.first.z.expr + h1.second.z.expr * t1,
z + dz * t2 eq h2.first.z.expr + h2.second.z.expr * t2,
z + dz * t3 eq h3.first.z.expr + h3.second.z.expr * t3,
).reduce { acc, expr -> acc and expr }
KZ3Solver(this).use { solver ->
solver.assert(constraints)
solver.check()
val model = solver.model()
return model.eval(x) + model.eval(y) + model.eval(z)
}
}
}
}
fun main() {
val testInput = """
18, 19, 22 @ -1, -1, -2
19, 13, 30 @ -2, 1, -2
20, 25, 34 @ -2, -2, -4
12, 31, 28 @ -1, -2, -1
20, 19, 15 @ 1, -5, -3
""".trimIndent().split("\n")
val testTestRange = 7..27L
println("------Tests------")
println(Day24.part1(testInput, testTestRange))
println(Day24.part2(testInput))
println("------Real------")
val input = readInput(2023, 24)
val testRange = 200_000_000_000_000..400_000_000_000_000
println("Part 1 result: ${Day24.part1(input, testRange)}")
println("Part 2 result: ${Day24.part2(input)}")
timingStatistics { Day24.part1(input, testRange) }
timingStatistics(minRuns = 3) { Day24.part2(input) }
}
| 0 |
Kotlin
| 0 | 0 |
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
| 4,661 |
advent-of-code
|
Apache License 2.0
|
jtransc-core/src/com/jtransc/graph/StrongComponent.kt
|
jtransc
| 51,313,992 | false | null |
package com.jtransc.graph
import java.util.*
// https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
// G = Graph
// V = Vertices (Nodes)
// E = Edges (E)
fun <T> Digraph<T>.tarjanStronglyConnectedComponentsAlgorithm() = StrongComponentGraph(this, TarjanStronglyConnectedComponentsAlgorithm(this).calculate())
// A strong component list is a disjoint set : https://en.wikipedia.org/wiki/Disjoint-set_data_structure
class StrongComponent<T>(val scgraph: StrongComponentGraph<T>, val indices: LinkedHashSet<Int>) {
val graph: Digraph<T> = scgraph.graph
val nodes: List<T> = graph.toNodes(indices)
//val inp: List<StrongComponent<T>> get() = scgraph.getInNodes(this)
val out: List<StrongComponent<T>> get() = scgraph.getOutNodes(this)
override fun toString() = graph.toNodes(indices).toString()
}
data class StrongComponentEdge<T>(val scgraph: StrongComponentGraph<T>, val fromNode:Int, val fromSC:StrongComponent<T>, val toNode:Int, val toSC:StrongComponent<T>) {
val graph: Digraph<T> = scgraph.graph
val fromNodeNode = graph.nodes[fromNode]
val toNodeNode = graph.nodes[toNode]
override fun toString() = "$fromNodeNode -> $toNodeNode"
}
class StrongComponentGraph<T>(val graph: Digraph<T>, componentsData: List<LinkedHashSet<Int>>) : AcyclicDigraph<StrongComponent<T>> {
val components = componentsData.map { StrongComponent(this, it) }
override val nodes: List<StrongComponent<T>> = components
override val nodeIndices = (0 until size).map { nodes[it] to it }.toMap()
//override fun getIn(node: Int): List<Int> = input[node]
override fun getOut(node: Int): List<Int> = output[node]
private val input = (0 until size).map { arrayListOf<Int>() }
private val output = (0 until size).map { arrayListOf<Int>() }
val outputEdges = (0 until size).map { arrayListOf<StrongComponentEdge<T>>() }
private val nodeIndexToComponents = IntArray(graph.size).let {
for (c in 0 until size) for (n in components[c].indices) it[n] = c
it
}
private fun addEdge(edge: StrongComponentEdge<T>) {
val fromSCIndex = nodeIndices[edge.fromSC]!!
val toSCIndex = nodeIndices[edge.toSC]!!
input[toSCIndex] += fromSCIndex
output[fromSCIndex] += toSCIndex
outputEdges[fromSCIndex] += edge
}
init {
// @TODO: SLOW! This information probably could be obtained directly from the algorithm!
for (inpComponent in components) {
val graph = inpComponent.graph
val set = inpComponent.indices
for (inp in set) {
for (out in graph.getOut(inp)) {
if (out !in set) {
// external link
val outComponent = findComponentWith(out)
addEdge(StrongComponentEdge(this, inp, inpComponent, out, outComponent))
}
}
}
}
}
override fun toString() = "$components : " + outputEdges.flatMap { it }.map { "($it)" }.toString()
fun findComponentWith(nodeIndex: Int): StrongComponent<T> {
return components[nodeIndexToComponents[nodeIndex]]
}
fun findComponentWith(node: T): StrongComponent<T> {
return components[nodeIndexToComponents[graph.getIndex(node)]]
}
fun findComponentIndexWith(node: T): Int {
return nodeIndexToComponents[graph.getIndex(node)]
}
}
fun <T> List<StrongComponent<T>>.toNodes(graph: Digraph<T>): List<List<T>> {
return this.map { graph.toNodes(it.indices) }
}
private class TarjanStronglyConnectedComponentsAlgorithm(val graph: DigraphSimple) {
val indices = IntArray(graph.size) { UNDEFINED }
val lowlinks = IntArray(graph.size) { UNDEFINED }
val onStackList = BooleanArray(graph.size) { false }
// @TODO: Use type aliases when kotlin accept them!
var Int.index: Int get() = indices[this]; set(value) { indices[this] = value }
var Int.lowlink: Int get() = lowlinks[this]; set(value) { lowlinks[this] = value }
var Int.onStack: Boolean get() = onStackList[this]; set(value) { onStackList[this] = value }
fun Int.successors(): List<Int> = graph.getOut(this)
var index = 0
var S = Stack<Int>()
val output = arrayListOf<LinkedHashSet<Int>>()
fun calculate(): List<LinkedHashSet<Int>> {
for (v in 0 until graph.size) {
if (v.index == UNDEFINED) strongconnect(v)
}
return output
}
fun strongconnect(v: Int) {
// Set the depth index for v to the smallest unused index
v.index = index
v.lowlink = index
index++
S.push(v)
v.onStack = true
// Consider successors of v
for (w in v.successors()) {
if (w.index == UNDEFINED) {
// Successor w has not yet been visited; recurse on it
strongconnect(w)
v.lowlink = Math.min(v.lowlink, w.lowlink)
} else if (w.onStack) {
// Successor w is in stack S and hence in the current SCC
v.lowlink = Math.min(v.lowlink, w.index)
}
}
// If v is a root node, pop the stack and generate an SCC
if (v.lowlink == v.index) {
//start a new strongly connected component
//println("start a new strongly connected component")
val strongComponent = LinkedHashSet<Int>()
do {
val w = S.pop()
w.onStack = false
strongComponent += w
//println("add w to current strongly connected component")
} while (w != v)
output += strongComponent
//println("output the current strongly connected component")
}
}
}
| 59 |
Java
| 66 | 619 |
6f9a2166f128c2ce5fb66f9af46fdbdbcbbe4ba4
| 5,138 |
jtransc
|
Apache License 2.0
|
src/main/kotlin/com/hj/leetcode/kotlin/problem460/Solution.kt
|
hj-core
| 534,054,064 | false |
{"Kotlin": 619841}
|
package com.hj.leetcode.kotlin.problem460
/**
* LeetCode page: [460. LFU Cache](https://leetcode.com/problems/lfu-cache/);
*/
class LFUCache(private val capacity: Int) {
private val values = hashMapOf<Int, Int>() // entry(key, value)
private val useCounts = hashMapOf<Int, Int>() // entry(key, useCount)
private val keyGroupsByUseCount = hashMapOf<Int, LinkedHashSet<Int>>() // entry(useCount, keyGroup)
private var minCount = 0
/* Complexity for N calls:
* Time O(N) and Space O(1);
*/
fun get(key: Int): Int {
return values[key]
?.also { increaseUseCount(key) }
?: -1
}
private fun increaseUseCount(key: Int) {
require(values.containsKey(key))
val oldCount = checkNotNull(useCounts[key])
val newCount = oldCount + 1
useCounts[key] = newCount
val oldGroup = checkNotNull(keyGroupsByUseCount[oldCount])
oldGroup.remove(key)
if (oldGroup.isEmpty()) {
keyGroupsByUseCount.remove(oldCount)
if (oldCount == minCount) minCount++
}
val newGroup = keyGroupsByUseCount.computeIfAbsent(newCount) { LinkedHashSet() }
newGroup.add(key)
}
/* Complexity for N calls:
* Time O(N) and Space O(N);
*/
fun put(key: Int, value: Int) {
if (values.containsKey(key)) {
update(key, value)
} else {
putNew(key, value)
}
}
private fun update(key: Int, newValue: Int) {
require(values.containsKey(key))
values[key] = newValue
increaseUseCount(key)
}
private fun putNew(key: Int, value: Int) {
require(!values.containsKey(key))
ensureCapacity(key)
values[key] = value
useCounts[key] = 1
keyGroupsByUseCount
.computeIfAbsent(1) { LinkedHashSet() }
.add(key)
minCount = 1
}
private fun ensureCapacity(key: Int) {
val hasSpace = values.containsKey(key) || values.size < capacity
if (hasSpace) return
val minCountKeyGroup = checkNotNull(keyGroupsByUseCount[minCount])
val keyToPop = minCountKeyGroup.first()
values.remove(keyToPop)
useCounts.remove(keyToPop)
minCountKeyGroup.remove(keyToPop)
if (minCountKeyGroup.isEmpty()) {
keyGroupsByUseCount.remove(minCount)
}
}
}
| 1 |
Kotlin
| 0 | 1 |
14c033f2bf43d1c4148633a222c133d76986029c
| 2,414 |
hj-leetcode-kotlin
|
Apache License 2.0
|
src/test/kotlin/days/Day2Test.kt
|
nicopico-dev
| 726,255,944 | false |
{"Kotlin": 37616}
|
package days
import days.Day2.Color.Blue
import days.Day2.Color.Green
import days.Day2.Color.Red
import days.Day2.Game
import days.Day2.Hypothesis
import io.kotest.assertions.assertSoftly
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class Day2Test {
private val Int.red get() = Red to this
private val Int.green get() = Green to this
private val Int.blue get() = Blue to this
//region Part 1
@Test
fun `parse input to extract a game`() {
val actual = Day2.parseInput("Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green")
actual shouldBe Game(
id = 1,
takes = listOf(
mapOf(
3.blue,
4.red,
),
mapOf(
1.red,
2.green,
6.blue,
),
mapOf(
2.green,
)
)
)
}
@Test
fun `check hypothesis to tell if a game is possible`() {
val hypothesis = Hypothesis(
red = 12,
green = 13,
blue = 14,
)
val game1 = Day2.parseInput("Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green")
val game3 = Day2.parseInput("Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red")
assertSoftly {
(hypothesis isPossibleWith game1) shouldBe true
(hypothesis isPossibleWith game3) shouldBe false
}
}
@Test
fun partOne() {
val day = Day2()
day.partOne() shouldBe 8
}
//endregion
//region Part 2
@Test
fun `getMinimumHypothesis compute the minimum hypothesis for a game`() {
val game1 = Day2.parseInput("Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green")
val game3 = Day2.parseInput("Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red")
assertSoftly {
game1.getMinimumHypothesis() shouldBe Hypothesis(red = 4, green = 2, blue = 6)
game3.getMinimumHypothesis() shouldBe Hypothesis(red = 20, green = 13, blue = 6)
}
}
@Test
fun `the power of an hypothesis is all colors multiplied together`() {
assertSoftly {
Hypothesis(red = 4, green = 2, blue = 6).power shouldBe 48
Hypothesis(red = 1, green = 3, blue = 4).power shouldBe 12
}
}
@Test
fun partTwo() {
val day = Day2()
day.partTwo() shouldBe 2286
}
//endregion
}
| 0 |
Kotlin
| 0 | 0 |
1a13c8bd3b837c1ce5b13f90f326f0277249d23e
| 2,574 |
aoc-2023
|
Creative Commons Zero v1.0 Universal
|
kotlin/src/com/s13g/aoc/aoc2022/Day5.kt
|
shaeberling
| 50,704,971 | false |
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
|
package com.s13g.aoc.aoc2022
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 5: Supply Stacks ---
* https://adventofcode.com/2022/day/5
*/
class Day5 : Solver {
override fun solve(lines: List<String>): Result {
val re = """move (\d+) from (\d+) to (\d+)$""".toRegex()
val stacks = parseStacks(lines)
for (line in lines.filter { it.contains("move") }) {
val (num, from, to) = re.find(line)!!.destructured
for (i in 0..1) {
val rem =
(1..num.toInt()).map { stacks[i][from.toInt() - 1].removeLast() }
.toList()
stacks[i][to.toInt() - 1].addAll(if (i == 0) rem else rem.asReversed())
}
}
return Result(
stacks[0].map { it.last() }.joinToString(""),
stacks[1].map { it.last() }.joinToString("")
)
}
private fun parseStacks(lines: List<String>): List<List<MutableList<Char>>> {
val stacks = (0..8).map { mutableListOf<Char>() }.toList()
for (row in 7 downTo 0) {
(0..8)
.map { stackNo -> Pair(stackNo, lines[row][stackNo * 4 + 1]) }
.filter { it.second != ' ' }
.forEach { stacks[it.first].add(it.second) }
}
return listOf(stacks, stacks.map { it.toMutableList() }.toList())
}
}
| 0 |
Kotlin
| 1 | 2 |
7e5806f288e87d26cd22eca44e5c695faf62a0d7
| 1,245 |
euler
|
Apache License 2.0
|
src/main/java/challenges/cracking_coding_interview/linked_list/sum_lists/SumListsA.kt
|
ShabanKamell
| 342,007,920 | false | null |
package challenges.cracking_coding_interview.linked_list.sum_lists
import challenges.data_structure.LinkedListNode
object SumListsA {
private fun addLists(l1: LinkedListNode, l2: LinkedListNode): LinkedListNode? {
return addLists(l1, l2, 0)
}
private fun addLists(l1: LinkedListNode?, l2: LinkedListNode?, carry: Int): LinkedListNode? {
if (l1 == null && l2 == null && carry == 0) {
return null
}
val result = LinkedListNode()
var value = carry
if (l1 != null) {
value += l1.data
}
if (l2 != null) {
value += l2.data
}
result.data = value % 10
// Recurse
if (l1 != null || l2 != null) {
val more = addLists(
l1?.next,
l2?.next,
if (value >= 10) 1 else 0
)
result.next = more
}
return result
}
private fun linkedListToInt(node: LinkedListNode?): Int {
var value = 0
if (node!!.next != null) {
value = 10 * linkedListToInt(node.next)
}
return value + node.data
}
@JvmStatic
fun main(args: Array<String>) {
val lA1 = LinkedListNode(9, null, null)
val lA2 = LinkedListNode(9, null, lA1)
val lA3 = LinkedListNode(9, null, lA2)
val lB1 = LinkedListNode(1, null, null)
val lB2 = LinkedListNode(0, null, lB1)
val lB3 = LinkedListNode(0, null, lB2)
val list3 = addLists(lA1, lB1)
println(" " + lA1.printForward())
println("+ " + lB1.printForward())
println("= " + list3!!.printForward())
val l1 = linkedListToInt(lA1)
val l2 = linkedListToInt(lB1)
val l3 = linkedListToInt(list3)
print("$l1 + $l2 = $l3\n")
print(l1.toString() + " + " + l2 + " = " + (l1 + l2))
}
}
| 0 |
Kotlin
| 0 | 0 |
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
| 1,895 |
CodingChallenges
|
Apache License 2.0
|
src/main/kotlin/domain/graphs/Graphs.kt
|
alexaldev
| 424,953,645 | false |
{"Kotlin": 12995}
|
package domain.graphs
import domain.TrianglesCounter
import domain.TrianglesCounterAlgorithm
import java.util.concurrent.ConcurrentHashMap
import java.util.stream.Stream
abstract class Graph {
abstract fun generateMetrics(): List<GraphMetrics>
abstract fun addEdge(sourceV: Int, destinationV: Int)
abstract fun removeEdge(v: Int, u: Int): Boolean
abstract fun neighbours(v: Int): Set<Int>
abstract fun isEdge(v1: Int, v2: Int): Boolean
abstract fun vertices(): Stream<Int>
abstract fun degree(v: Int): Int
abstract fun backedDataStructureDescription(): String
enum class Type {
ADJ_MAP, ADJ_MATRIX
}
}
sealed class GraphMetrics(val name: String, val value: Double) {
data class NumOfVertices(val count: Int) : GraphMetrics("|V|", count.toDouble())
data class NumOfEdges(val count: Int) : GraphMetrics("|E|", count.toDouble())
data class NumOfTotalTriangles(val count: Int) : GraphMetrics("Total count of triangles", count.toDouble())
}
// ---------- Implementations -----------------
class GraphWithAdjMatrix(private val numOfVertices: Int) : Graph() {
private val matrix = MutableList(numOfVertices) { MutableList(numOfVertices) {0} }
private val verticesCount: Int by lazy { numOfVertices }
private val edgesCount: Int by lazy {
matrix.sumOf { row -> row.count { it == 1 } }
}
override fun generateMetrics(): List<GraphMetrics> {
return listOf(
GraphMetrics.NumOfVertices(verticesCount),
GraphMetrics.NumOfEdges(edgesCount)
)
}
override fun addEdge(sourceV: Int, destinationV: Int) {
matrix[sourceV][destinationV] = 1
}
override fun backedDataStructureDescription(): String {
TODO("Not yet implemented")
}
override fun removeEdge(v: Int, u: Int): Boolean {
val edgeExists = (matrix[v][u] == 1)
return if (edgeExists) {
matrix[v][u] = 0
true
} else {
false
}
}
override fun neighbours(v: Int): Set<Int> {
TODO("Not yet implemented.")
}
override fun isEdge(v1: Int, v2: Int): Boolean {
TODO("Not yet implemented")
}
override fun vertices(): Stream<Int> {
TODO("Not yet implemented")
}
override fun degree(v: Int): Int {
TODO("Not yet implemented")
}
}
class GraphWithMap(trianglesCounter: TrianglesCounter = TrianglesCounter(TrianglesCounterAlgorithm.Naive)) : Graph() {
private val adjacencyMap: HashMap<Int, HashSet<Int>> = HashMap()
private val verticesCount: Int by lazy {
adjacencyMap.size
}
private val edgesCount: Int by lazy {
adjacencyMap
.values
.fold(0) { acc, hashSet -> acc + hashSet.size } / 2
}
override fun addEdge(sourceV: Int, destinationV: Int) {
adjacencyMap
.computeIfAbsent(sourceV) { HashSet() }
.add(destinationV)
adjacencyMap
.computeIfAbsent(destinationV) { HashSet() }
.add(sourceV)
}
override fun toString(): String = StringBuffer().apply {
for (key in adjacencyMap.keys) {
append("$key -> ")
append(adjacencyMap[key]?.joinToString(", ", "[", "]\n"))
}
}.toString()
override fun generateMetrics(): List<GraphMetrics> {
return listOf(
GraphMetrics.NumOfVertices(verticesCount),
GraphMetrics.NumOfEdges(edgesCount)
)
}
override fun backedDataStructureDescription() = """
|This graph is represented by an adjacency hashmap.
|It keeps in-memory a hashmap with this structure:
|[V] -> [neighbour1, neighnour2,...]
|...
|...
""".trimMargin()
override fun removeEdge(v: Int, u: Int) = adjacencyMap[v]?.remove(u) ?: false
override fun neighbours(v: Int): Set<Int> = adjacencyMap[v] ?: emptySet()
override fun isEdge(v1: Int, v2: Int): Boolean {
TODO("Not yet implemented")
}
override fun vertices(): Stream<Int> {
return adjacencyMap.keys.stream()
}
override fun degree(v: Int): Int {
TODO("Not yet implemented")
}
}
| 0 |
Kotlin
| 0 | 0 |
f0dfaca21728493bd2a99cd9048e6f3f9e596f63
| 4,201 |
GraphTriangleDetection
|
Apache License 2.0
|
src/Day6.kt
|
syncd010
| 324,790,559 | false | null |
class Day6: Day {
private fun convert(input: List<String>) : Map<String, String> {
return input.map { it.split(")") }.associate { Pair(it[1], it[0]) }
}
/**
* Assuming [map] is a path map, returns the path from [from] to [to]
*/
private fun getMapPath(map: Map<String, String>, from: String, to: String): List<String> {
var tmp = from
val path = mutableListOf<String>()
do {
path.add(tmp)
tmp = map[tmp] ?: error("Incorrect map")
} while (tmp != to)
return path
}
override fun solvePartOne(input: List<String>): Int {
val orbits = convert(input)
return orbits.keys.map { getMapPath(orbits, it, "COM").size }.sum()
}
override fun solvePartTwo(input: List<String>): Int {
val orbits = convert(input)
val youPath = getMapPath(orbits, "YOU", "COM").toSet()
val santaPath = getMapPath(orbits, "SAN", "COM").toSet()
val common = (youPath union santaPath) subtract (youPath intersect santaPath)
return common.size - 2
}
}
| 0 |
Kotlin
| 0 | 0 |
11c7c7d6ccd2488186dfc7841078d9db66beb01a
| 1,121 |
AoC2019
|
Apache License 2.0
|
kold-examples/src/main/kotlin/com/github/kold/examples/SubFieldsValidation.kt
|
kotlin-kold
| 256,402,175 | false | null |
package com.github.kold.examples
import com.github.kold.context.combineFields
import com.github.kold.context.default
import com.github.kold.context.validateElements
import com.github.kold.context.validationContext
import com.github.kold.data.KoldData
import com.github.kold.validated.Validated
object SubFieldsValidation {
fun validateUser(input: KoldData): Validated<User> =
input.validationContext {
combineFields(
require("name").validateValue { it.string() },
opt("password").validateOption { it.string() },
require("age").validateValue { it.long() },
opt("score").validateOption { it.double() },
require("phoneNumbers").validateValue {
it.list().validateElements { el ->
el.notNull().obj().flatMap { data -> validatePhoneNumber(data) }
}
},
require("settings").validateValue {
it.obj().flatMap { data -> validateSettings(data) }
}
) { name, password, age, score, phoneNumbers, settings ->
User(name, password, age.toInt(), score, phoneNumbers, settings)
}
}
fun validatePhoneNumber(input: KoldData): Validated<PhoneNumber> =
input.validationContext {
combineFields(
opt("type").validateOption { type -> type.string() },
require("value").validateValue { value -> value.string() },
require("index").validateValue { value -> value.int() }
) { type, value, index ->
PhoneNumber(type, value, index)
}
}
fun validateSettings(input: KoldData): Validated<Settings> =
input.validationContext {
combineFields(
require("verified").validateValue { it.bool() },
opt("tags").validateOption {
it.list().validateElements { el -> el.notNull().string() }
}.default(emptyList()),
opt("language").validateOption { it.string() }
) { verified, tags, language ->
Settings(verified, tags, language)
}
}
data class User(
val name: String,
val password: String?,
val age: Int,
val score: Double?,
val phoneNumbers: List<PhoneNumber>,
val settings: Settings
)
data class Settings(
val verified: Boolean,
val tags: List<String>,
val language: String?
)
data class PhoneNumber(
val type: String?,
val value: String,
val index: Int
)
private val validInput = mapOf(
"name" to "Jack",
"password" to "<PASSWORD>",
"age" to 42,
"score" to 0.9,
"phoneNumbers" to listOf("+123", "+456"),
"flags" to listOf(123, null, 456),
"attributes" to null
).let { KoldData.fromMap(it) }
private val invalidInput1 = mapOf(
"password" to "<PASSWORD>",
"age" to 42,
"score" to "0.9"
).let { KoldData.fromMap(it) }
private val invalidInput2 = mapOf(
"password" to "<PASSWORD>",
"age" to 42,
"score" to "0.9",
"phoneNumbers" to listOf(
mapOf("type" to "some", "value" to "123"), 123, 456, null)
).let { KoldData.fromMap(it) }
}
| 0 |
Kotlin
| 0 | 1 |
ac20a24389af3f612e3ea6875f5db365a9c54620
| 3,412 |
kold
|
MIT License
|
2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day10.kt
|
codelicia
| 627,407,402 | false |
{"Kotlin": 49578, "PHP": 554, "Makefile": 293}
|
package com.codelicia.advent2021
import java.util.Stack
class Day10(private val input: List<String>) {
private val scoreTable: Map<String, Long> = mapOf(
")" to 3L,
"]" to 57L,
"}" to 1197L,
">" to 25137L,
)
private val scoreTableForIncomplete: Map<String, Long> = mapOf(
"(" to 1L,
"[" to 2L,
"{" to 3L,
"<" to 4L,
)
private val openChar = listOf("(", "[", "{", "<")
private val closeChar = listOf(")", "]", "}", ">")
fun part1(): Long {
val queue = input.map { line -> ArrayDeque(line.split("")) }
val order = ArrayDeque<String>()
var points = 0L
for (line in queue) {
for (char in line.indices) {
val lineChar = line[char]
if (lineChar.isBlank()) continue
if (openChar.contains(lineChar)) {
order.add(lineChar)
} else {
val removed = order.removeLast()
if (openChar.zip(closeChar).first { it.first == removed }.second != lineChar) {
points += scoreTable[lineChar]!!
}
}
}
}
return points
}
fun part2(): Long {
val queue = input.map { line -> ArrayDeque(line.split("")) }
val closing = Stack<Long>()
for (line in queue) {
val order = ArrayDeque<String>()
var error = false
for (char in line.indices) {
val lineChar = line[char]
if (lineChar.isBlank() || error == true) continue
if (openChar.contains(lineChar)) {
order.add(lineChar)
} else {
val removed = order.removeLast()
if (openChar.zip(closeChar).first { it.first == removed }.second != lineChar) {
error = true
continue
}
}
}
if (order.isNotEmpty() && error == false) {
order.reversed().fold(0L) { acc, s ->
(acc * 5) + scoreTableForIncomplete[s]!!
}
.also { closing.add(it) }
}
}
closing.sort()
return closing[closing.size.floorDiv(2)]
}
}
| 2 |
Kotlin
| 0 | 0 |
df0cfd5c559d9726663412c0dec52dbfd5fa54b0
| 2,377 |
adventofcode
|
MIT License
|
puzzles/src/main/kotlin/com/kotlinground/puzzles/search/binarysearch/searchrange/searchRange.kt
|
BrianLusina
| 113,182,832 | false |
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
|
package com.kotlinground.puzzles.search.binarysearch.searchrange
/**
* Searches for the left and right positions of a target in nums
*
* For the first_pos, we want to find the leftmost target. So we will do binary search on nums, and whenever we find
* a target, we search for its left side to see whether there is another target on the left while keeping track of the
* leftmost seen first_pos.
*
* Similarly, we want to find the rightmost target in nums to be last_pos. So when we see a target, we search for its
* right side and record the last_pos = current index. If the current element is not target, then ordinary binary
* search will lead us to the correct searching side.
*
* @param nums [IntArray] numbers to search
* @param target [Int] target number
* @return [IntArray] array of length 2 with 1st index as the left position and last index as the right position
*/
fun searchRange(nums: IntArray, target: Int): IntArray {
var left = 0
var right = nums.size - 1
var firstPos = -1
var lastPos = -1
while (left <= right) {
val mid = left + (right - left) / 2
if (nums[mid] == target) {
firstPos = mid
right = mid - 1
} else if (nums[mid] < target) {
left = mid + 1
} else {
right = mid - 1
}
}
left = 0
right = nums.size - 1
while (left <= right) {
val mid = left + (right - left) / 2
if (nums[mid] == target) {
lastPos = mid
left = mid + 1
} else if (nums[mid] < target) {
left = mid + 1
} else {
right = mid - 1
}
}
return intArrayOf(firstPos, lastPos)
}
| 1 |
Kotlin
| 1 | 0 |
5e3e45b84176ea2d9eb36f4f625de89d8685e000
| 1,705 |
KotlinGround
|
MIT License
|
src/main/kotlin/g2801_2900/s2830_maximize_the_profit_as_the_salesman/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g2801_2900.s2830_maximize_the_profit_as_the_salesman
// #Medium #Array #Dynamic_Programming #Sorting #Binary_Search
// #2023_12_18_Time_776_ms_(100.00%)_Space_112.8_MB_(33.33%)
import kotlin.math.max
class Solution {
fun maximizeTheProfit(n: Int, offers: List<List<Int>>): Int {
val dp = IntArray(n)
val range = HashMap<Int, MutableList<List<Int>>>()
for (l in offers) {
if (range.containsKey(l[0])) {
range[l[0]]!!.add(l)
} else {
val r: MutableList<List<Int>> = ArrayList()
r.add(l)
range[l[0]] = r
}
}
var i = 0
while (i < n) {
var temp: List<List<Int>> = ArrayList()
if (range.containsKey(i)) {
temp = range[i]!!
}
dp[i] = if ((i != 0)) max(dp[i], dp[i - 1]) else dp[i]
for (l in temp) {
dp[l[1]] =
if ((i != 0)
) max(dp[l[1]], (dp[i - 1] + l[2])) else max(
dp[l[1]],
l[2]
)
}
i++
}
return dp[n - 1]
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 1,215 |
LeetCode-in-Kotlin
|
MIT License
|
2020/src/main/kotlin/de/skyrising/aoc2020/day23/solution.kt
|
skyrising
| 317,830,992 | false |
{"Kotlin": 411565}
|
package de.skyrising.aoc2020.day23
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.ints.Int2IntMap
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap
/*
private fun move(cups: IntArray, count: Int): IntArray {
val size = cups.size
//println("-- move ${count + 1} --")
//println("cups: ${cups.contentToString()}")
val currentIndex = count % size
val pickup = Array(3) { n -> cups[(currentIndex + n + 1) % size] }
//println("pick up: ${pickup.contentToString()}")
var dest = cups[currentIndex] - 1
while (dest in pickup || dest == 0) {
dest--
if (dest <= 0) dest = size
}
//println("destination: $dest")
val newCups = IntArray(size)
var i = 0
var j = 0
var currentDest = 0
while (cups[i] in pickup) i++
while (j < size) {
if (i == currentIndex) currentDest = j
val cup = cups[i]
newCups[j++] = cup
if (cup == dest) {
newCups[j++] = pickup[0]
newCups[j++] = pickup[1]
newCups[j++] = pickup[2]
}
i = (i + if (i == currentIndex) 4 else 1) % size
}
val rotateAmount = currentDest - currentIndex
if (rotateAmount != 0) {
return IntArray(size) {
newCups[(size + it + rotateAmount) % size]
}
}
return newCups
}
*/
private fun move(cups: Int2IntMap, current: Int) {
var tmpLabel = current
val pickup = IntArray(3) {
tmpLabel = cups[tmpLabel]
tmpLabel
}
cups[current] = cups[tmpLabel]
var dest = current - 1
while (dest in pickup || dest < 1) {
dest--
if (dest < 1) dest = cups.size
}
//println("pickup: ${pickup.contentToString()}")
//println("current: $current")
//println("dest: $dest")
tmpLabel = cups[dest]
cups[dest] = pickup[0]
cups[pickup[2]] = tmpLabel
}
val test = "389125467\n"
@PuzzleName("Crab Cups")
fun PuzzleInput.part1(): Any {
val base = IntArray(chars.length - 1) { i -> chars[i] - '0' }
val cups = Int2IntOpenHashMap(base.size)
for (i in 0 until base.size - 1) cups[base[i]] = base[i + 1]
cups[base.last()] = base[0]
//println(cups)
var current = base[0]
repeat(100) {
move(cups, current)
//println(cups)
current = cups[current]
}
var i = cups[1]
val sb = StringBuilder(cups.size - 1)
while (i != 1) {
sb.append(i)
i = cups[i]
}
return sb.toString()
}
fun PuzzleInput.part2(): Any {
val base = IntArray(chars.length - 1) { i -> chars[i] - '0' }
//println(base.contentToString())
val cups = Int2IntOpenHashMap(1_000_000)
for (i in 0 until base.size - 1) cups[base[i]] = base[i + 1]
cups[base.last()] = base.size + 1
for (i in base.size + 1 until 1_000_000) cups[i] = i + 1
cups[1_000_000] = base[0]
var current = base[0]
//for ((k, v) in cups) if (v != k + 1 || k in base) println("$k, $v")
repeat(10_000_000) {
//if (it % 100_000 == 0) println("${it / 100_000}%")
move(cups, current)
current = cups[current]
}
val a = cups[1]
val b = cups[a]
//println("$a,$b")
return a.toLong() * b.toLong()
}
| 0 |
Kotlin
| 0 | 0 |
19599c1204f6994226d31bce27d8f01440322f39
| 3,192 |
aoc
|
MIT License
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumXor.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
/**
* 1829. Maximum XOR for Each Query
* @see <a href="https://leetcode.com/problems/maximum-xor-for-each-query/">Source</a>
*/
fun interface MaximumXor {
operator fun invoke(nums: IntArray, maximumBit: Int): IntArray
}
class MaximumXorOnePass : MaximumXor {
override fun invoke(nums: IntArray, maximumBit: Int): IntArray {
val n = nums.size
val res = IntArray(n)
var value = (1 shl maximumBit) - 1
for (i in nums.indices) {
value = value xor nums[i]
res[n - i - 1] = value
}
return res
}
}
| 4 |
Kotlin
| 0 | 19 |
776159de0b80f0bdc92a9d057c852b8b80147c11
| 1,221 |
kotlab
|
Apache License 2.0
|
Algorithms/src/main/kotlin/net/milosvasic/algorithms/sort/efficient/MergeSort.kt
|
milos85vasic
| 80,288,639 | false | null |
package net.milosvasic.algorithms.sort.efficient
import net.milosvasic.algorithms.sort.Sort
class MergeSort<T : Comparable<T>> : Sort<T> {
private var tmp = mutableListOf<T>()
override fun sort(elements: MutableList<T>, ascending: Boolean) {
tmp.addAll(elements)
mergeSort(elements, 0, elements.size - 1, ascending)
tmp = mutableListOf<T>()
}
private fun mergeSort(elements: MutableList<T>, start: Int, end: Int, ascending: Boolean) {
if (start < end) {
val middle = (start + end) / 2
mergeSort(elements, start, middle, ascending)
mergeSort(elements, middle + 1, end, ascending)
merge(elements, start, middle, end, ascending)
}
}
fun merge(elements: MutableList<T>, start: Int, middle: Int, end: Int, ascending: Boolean) {
var i = start
var k = start
var j = middle + 1
while (i <= middle && j <= end) {
if (ascending) {
if (elements[i] <= elements[j]) {
tmp[k++] = elements[i++]
} else {
tmp[k++] = elements[j++]
}
} else {
if (elements[i] >= elements[j]) {
tmp[k++] = elements[i++]
} else {
tmp[k++] = elements[j++]
}
}
}
while (i <= middle) {
tmp[k++] = elements[i++]
}
while (j < end) {
tmp[k++] = elements[j++]
}
for (x in start..end) {
elements[x] = tmp[x]
}
}
}
| 0 |
Kotlin
| 1 | 5 |
a2be55959035654463b4855058d07ccfb68ac4a7
| 1,629 |
Fundamental-Algorithms
|
Apache License 2.0
|
src/Day04.kt
|
andyludeveloper
| 573,249,939 | false |
{"Kotlin": 7818}
|
fun main() {
fun List<String>.toIntRows() = this.map { row ->
row.split(",", "-").map(String::toInt)
}
fun part1(input: List<String>): Int =
input.toIntRows()
.count { (a1, a2, b1, b2) -> (a1 <= b1) && (a2 >= b2) || (a1 >= b1) && (a2 >= b2) }
fun part2(input: List<String>): Int =
input.toIntRows()
.count { (a1, a2, b1, b2) -> (a1 <= b1) && (a2 >= b1) || (b1 <= a1) && (b2 >= a1) }
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
684cf9ff315f15bf29914ca25b44cca87ceeeedf
| 650 |
Kotlin-in-Advent-of-Code-2022
|
Apache License 2.0
|
year2021/day21/dice/src/main/kotlin/com/curtislb/adventofcode/year2021/day21/dice/dirac/DiracDice.kt
|
curtislb
| 226,797,689 | false |
{"Kotlin": 2146738}
|
package com.curtislb.adventofcode.year2021.day21.dice.dirac
import com.curtislb.adventofcode.common.collection.Counter
import com.curtislb.adventofcode.common.iteration.nestedLoop
/**
* A set of dice, each of which can roll any integer from 1 to [sidesCount] with equal probability.
*
* @param diceCount The number of dice that will be rolled each time.
* @param sidesCount The maximum possible result when rolling each die.
*/
class DiracDice(val diceCount: Int, val sidesCount: Int) {
/**
* A map from each possible total result to the number of outcomes that sum to it.
*/
private val outcomeCounts: Map<Int, Long> = Counter<Int>()
.apply {
val rollValues = (1..sidesCount).toList()
nestedLoop(items = rollValues, levelCount = diceCount) { rolls ->
this[rolls.sum()]++
false // Keep iterating
}
}
.toMap()
/**
* All possible values given by rolling the dice and summing the results.
*/
val possibleResults: IntRange = diceCount..(diceCount * sidesCount)
/**
* Returns the number of distinct dice roll outcomes that sum to the given [totalResult].
*/
fun countOutcomes(totalResult: Int): Long = outcomeCounts[totalResult] ?: 0L
}
| 0 |
Kotlin
| 1 | 1 |
6b64c9eb181fab97bc518ac78e14cd586d64499e
| 1,287 |
AdventOfCode
|
MIT License
|
src/commonMain/kotlin/io/github/alexandrepiveteau/graphs/internal/graphs/AdjacencyListNetwork.kt
|
alexandrepiveteau
| 630,931,403 | false |
{"Kotlin": 132267}
|
package io.github.alexandrepiveteau.graphs.internal.graphs
import io.github.alexandrepiveteau.graphs.*
/**
* An implementation of [Network] which uses an adjacency list to store the links and weights.
*
* @param neighbors the adjacency list of the graph.
* @param weights the weights of the graph.
*/
internal class AdjacencyListNetwork(
private val neighbors: Array<VertexArray>,
private val weights: Array<IntArray>,
) : Network, Graph by AdjacencyListGraph(neighbors) {
override fun successorWeight(index: Int, neighborIndex: Int): Int {
if (index < 0 || index >= size) throw IndexOutOfBoundsException()
val weights = weights[index]
if (neighborIndex < 0 || neighborIndex >= weights.size) throw IndexOutOfBoundsException()
return weights[neighborIndex]
}
override fun successorWeight(index: Int, neighbor: Vertex): Int {
if (index < 0 || index >= size) throw IndexOutOfBoundsException()
val neighbors = neighbors[index]
val neighborIndex = neighbors.binarySearch(neighbor)
if (neighborIndex < 0) throw NoSuchVertexException()
return weights[index][neighborIndex]
}
}
/** An implementation of [DirectedNetwork] which uses an adjacency list to store the links. */
internal class AdjacencyListDirectedNetwork(
private val neighbors: Array<VertexArray>,
weights: Array<IntArray>,
) : DirectedNetwork, Network by AdjacencyListNetwork(neighbors, weights) {
override fun contains(arc: Arc): Boolean {
val (u, v) = arc
if (u !in this || v !in this) return false
return neighbors[u.index].binarySearch(v) >= 0
}
}
/** An implementation of [UndirectedNetwork] which uses an adjacency list to store the links. */
internal class AdjacencyListUndirectedNetwork(
private val neighbors: Array<VertexArray>,
weights: Array<IntArray>,
) : UndirectedNetwork, Network by AdjacencyListNetwork(neighbors, weights) {
override fun contains(edge: Edge): Boolean {
val (u, v) = edge
if (u !in this || v !in this) return false
return neighbors[u.index].binarySearch(v) >= 0 || neighbors[v.index].binarySearch(u) >= 0
}
}
| 9 |
Kotlin
| 0 | 6 |
a4fd159f094aed5b6b8920d0ceaa6a9c5fc7679f
| 2,111 |
kotlin-graphs
|
MIT License
|
year2019/day06/orbits/src/main/kotlin/com/curtislb/adventofcode/year2019/day06/orbits/Universe.kt
|
curtislb
| 226,797,689 | false |
{"Kotlin": 2146738}
|
package com.curtislb.adventofcode.year2019.day06.orbits
import java.io.File
/**
* A collection of planets that may orbit one another.
*/
class Universe() {
/**
* A map from names to corresponding planets in the universe.
*/
private val planets: MutableMap<String, Planet> = mutableMapOf()
/**
* A collection of planets that may orbit one another.
*
* @param file A file containing orbital data that is used to populate the universe. Each line
* of the file should contain a string like `"A)B"`, indicating that planet B orbits planet A.
*/
constructor(file: File) : this() {
file.forEachLine { line ->
val (orbited, orbiter) = line.trim().split(')')
addOrbit(orbited, orbiter)
}
}
/**
* Makes [orbited] a parent of [orbiter] in the orbital graph, adding each planet to the
* universe if needed.
*/
fun addOrbit(orbited: String, orbiter: String) {
val parent = getOrAddPlanet(orbited)
val child = getOrAddPlanet(orbiter)
parent.children.add(child)
child.parent = parent
}
/**
* Returns the planet with [name] in the universe, creating and adding it if needed.
*/
private fun getOrAddPlanet(name: String): Planet {
return planets.getOrElse(name) {
val planet = Planet(name)
planets[name] = planet
planet
}
}
/**
* Returns the number of direct and indirect orbits involving [center] and its descendants.
*/
fun countOrbits(center: String): Int {
val root = planets[center]
return countOrbitsInternal(root, depth = 0)
}
/**
* Recursive helper function for [countOrbits].
*/
private fun countOrbitsInternal(root: Planet?, depth: Int): Int {
return if (root == null) 0 else depth + root.children.sumOf {
countOrbitsInternal(
it,
depth + 1
)
}
}
/**
* Returns the minimum number of orbital transfers required for [start] to enter the same orbit
* as [target], or `null` if this is not possible for the current orbital graph.
*/
fun findOrbitalTransferDistance(start: String, target: String): Int? {
// Both planets must be in the orbital graph.
if (start !in planets || target !in planets) {
return null
}
// If start and target are the same, no transfers are required.
if (start == target) {
return 0
}
// Search for the nearest common ancestor of start and target.
var planetA = planets[start]
var planetB = planets[target]
var stepCount = 0
val visited = mutableMapOf<String, Int>()
while (planetA != null || planetB != null) {
stepCount++
// Step to planet A's parent, checking if it's been seen in planet B's ancestral chain.
planetA = planetA?.parent
if (planetA != null) {
visited[planetA.name]?.let { return stepCount + it - 2 }
visited[planetA.name] = stepCount
}
// Step to planet B's parent, checking if it's been seen in planet A's ancestral chain.
planetB = planetB?.parent
if (planetB != null) {
visited[planetB.name]?.let { return stepCount + it - 2 }
visited[planetB.name] = stepCount
}
}
// No common ancestor found.
return null
}
}
| 0 |
Kotlin
| 1 | 1 |
6b64c9eb181fab97bc518ac78e14cd586d64499e
| 3,562 |
AdventOfCode
|
MIT License
|
src/2022/Day05.kt
|
nagyjani
| 572,361,168 | false |
{"Kotlin": 369497}
|
package `2022`
import java.io.File
import java.util.*
fun main() {
Day05().solve()
}
class Day05 {
val input1 = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent()
fun solve() {
val f = File("src/2022/inputs/day05.in")
val s = Scanner(f)
// val s = Scanner(input1)
val stacks = MutableList<MutableList<Char>>(9){mutableListOf()}
while (s.hasNextLine()) {
val line = s.nextLine()
if (line.startsWith(" 1")) {
s.nextLine()
break
}
println("$line")
val chunks = line.split("[")
var offset = chunks[0].length/4
val restOfChunks = chunks.toMutableList()
restOfChunks.removeFirst()
restOfChunks.forEach{
val c = it[0]
stacks[offset].add(c)
val t = it.split("]")
if (t.size != 2) {
throw RuntimeException()
}
println("$offset $c")
offset += t[1].length / 4 + 1
}
println("$chunks")
}
val stacks1 = stacks.map { it.reversed().toMutableList() }
println("$stacks1")
s.useDelimiter("[^\\d]")
while (s.hasNext()) {
val line = s.nextLine().trim()
val chunks = line.split(Regex("[^\\d]+"))
val n = chunks[1].toInt()
val f = chunks[2].toInt()
val t = chunks[3].toInt()
println("$f $t $n")
// for (i in 1..n) {
// stacks1[t - 1].add(stacks1[f - 1].last())
// stacks1[f - 1].removeLast()
// }
val toMove = stacks1[f - 1].takeLast(n)
stacks1[t - 1].addAll(toMove)
for (i in 1..n) {
stacks1[f - 1].removeLast()
}
println("$stacks1")
}
println("$stacks1")
val top = stacks1.map{if (it.size>0) {it.last()} else {' '}}
println("${top.joinToString("")}")
}
}
| 0 |
Kotlin
| 0 | 0 |
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
| 2,182 |
advent-of-code
|
Apache License 2.0
|
src/Day03.kt
|
vonElfvin
| 572,857,181 | false |
{"Kotlin": 11658}
|
const val UPPER = 65 - 27
const val LOWER = 96
fun main() {
fun part1(input: List<String>): Int = input.sumOf { row ->
val (left, right) = listOf(
row.substring(0, row.length / 2),
row.substring(row.length / 2)
).map(String::toCharArray)
val both = left.first { right.contains(it) }
if (both.isUpperCase()) both.code - UPPER else both.code - LOWER
}
fun part2(input: List<String>): Int = input.chunked(3).sumOf { (first, second, third) ->
val all = first.first { second.contains(it) && third.contains(it) }
if (all.isUpperCase()) all.code - UPPER else all.code - LOWER
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
6210f23f871f646fcd370ec77deba17da4196efb
| 750 |
Advent-of-Code-2022
|
Apache License 2.0
|
src/main/kotlin/top/pengcheng789/algorithms/sort/LoopQuickSort.kt
|
pengcheng789
| 100,803,477 | false | null |
/*
* copyright 2018 the original author or authors.
*
* 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 top.pengcheng789.algorithms.sort
import java.util.*
/**
*
* @author <NAME>
*/
class LoopQuickSort<T: Comparable<T>>: Sort<T> {
override fun sort(list: MutableList<T>) {
if (list.isEmpty()) {
return
}
val stack = Stack<Array<Int>>()
stack.push(arrayOf(0, list.size - 1))
do {
val range = stack.pop()
val pivotIndex = (range[0] + range[1]) shr 1
val pivotNewIndex = partition(list, range[0], range[1], pivotIndex)
if (range[0] < pivotNewIndex - 1) {
stack.push(arrayOf(range[0], pivotNewIndex - 1))
}
if (range[1] > pivotNewIndex + 1) {
stack.push(arrayOf(pivotNewIndex + 1, range[1]))
}
} while (stack.isNotEmpty())
}
private fun partition(list: MutableList<T>, left: Int,
right: Int, pivotIndex: Int): Int {
val pivotValue = list[pivotIndex]
swap(list, right, pivotIndex)
var storeIndex = left
var i = left
while (i < right) {
if (list[i] <= pivotValue) {
swap(list, i, storeIndex)
storeIndex++
}
i++
}
swap(list, storeIndex, right)
return storeIndex
}
}
| 0 |
Kotlin
| 0 | 0 |
667bca6217c81f85c7ac68830e5ed984c5c1965d
| 1,946 |
algorithms
|
Apache License 2.0
|
src/day_10.kt
|
gardnerdickson
| 152,621,962 | false | null |
import java.lang.StringBuilder
fun main(args: Array<String>) {
val input = "1113222113"
val answer1 = Day10.part1(input)
println("Part 1: $answer1")
val answer2 = Day10.part2(input)
println("Part 2: $answer2")
}
object Day10 {
private fun lookAndSay(sequence: String): String {
val digits = sequence.toCharArray().map { Character.getNumericValue(it) }
val stringBuilder = StringBuilder()
var lastDigit = -1
var currentDigit: Int
var quantity = 0
for (i in 0 until digits.size) {
currentDigit = digits[i]
if (i == digits.size - 1) {
if (currentDigit != lastDigit) {
stringBuilder.append("$quantity$lastDigit")
stringBuilder.append("1$currentDigit")
} else {
stringBuilder.append("${(quantity + 1)}$lastDigit")
}
} else if (currentDigit != lastDigit && lastDigit != -1) {
stringBuilder.append("$quantity$lastDigit")
quantity = 1
} else {
quantity++
}
lastDigit = currentDigit
}
return stringBuilder.toString()
}
fun part1(sequence: String): Int {
var nextSequence = sequence
repeat(40) {
nextSequence = lookAndSay(nextSequence)
}
return nextSequence.length
}
fun part2(sequence: String): Int {
var nextSequence = sequence
repeat(50) {
nextSequence = lookAndSay(nextSequence)
}
return nextSequence.length
}
}
| 0 |
Kotlin
| 0 | 0 |
4a23ab367a87cae5771c3c8d841303b984474547
| 1,637 |
advent-of-code-2015
|
MIT License
|
src/main/kotlin/com/hj/leetcode/kotlin/problem167/Solution.kt
|
hj-core
| 534,054,064 | false |
{"Kotlin": 619841}
|
package com.hj.leetcode.kotlin.problem167
/**
* LeetCode page: [167. Two Sum II - Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(1) where N is the size of numbers;
*/
fun twoSum(numbers: IntArray, target: Int): IntArray {
var leftIndex = 0
var rightIndex = numbers
.binarySearch(target - numbers[leftIndex])
.let { insertionIndex -> if (insertionIndex < 0) -(insertionIndex + 1) else insertionIndex }
.coerceAtMost(numbers.lastIndex)
if (rightIndex == 0) {
check(numbers[0] + numbers[1] == target) // Guaranteed by problem constraints
return intArrayOf(1, 2)
}
while (leftIndex < rightIndex) {
val currSum = numbers[leftIndex] + numbers[rightIndex]
when {
currSum < target -> leftIndex++
currSum > target -> rightIndex--
else -> return intArrayOf(leftIndex + 1, rightIndex + 1)
}
}
return intArrayOf(-1, -1)
}
}
| 1 |
Kotlin
| 0 | 1 |
14c033f2bf43d1c4148633a222c133d76986029c
| 1,140 |
hj-leetcode-kotlin
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.