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/Day01.kt | Djaler | 573,520,591 | false | {"Kotlin": 1613} | fun main() {
fun <T> List<T>.split(delimeter: T): List<List<T>> {
val result = mutableListOf<List<T>>()
var buffer = mutableListOf<T>()
for (item in this) {
if (item != delimeter) {
buffer.add(item)
} else if (buffer.isNotEmpty()) {
result.add(buffer)
buffer = mutableListOf()
}
}
return result
}
fun part1(input: List<String>): Int {
return input.split("")
.maxOf { elfSnacks -> elfSnacks.sumOf { it.toInt() } }
}
fun part2(input: List<String>): Int {
return input.split("")
.map { elfSnacks -> elfSnacks.sumOf { it.toInt() } }
.sortedDescending()
.take(3)
.sum()
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 1 | Kotlin | 0 | 0 | 451e019525a888f4bc40feb4327de07598ed07b8 | 965 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g2501_2600/s2528_maximize_the_minimum_powered_city/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2501_2600.s2528_maximize_the_minimum_powered_city
// #Hard #Array #Greedy #Binary_Search #Prefix_Sum #Sliding_Window #Queue
// #2023_07_04_Time_496_ms_(100.00%)_Space_57_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
private fun canIBeTheMinimum(power: LongArray, minimum: Long, k: Int, r: Int): Boolean {
var k = k
val n = power.size
val extraPower = LongArray(n)
for (i in 0 until n) {
if (i > 0) {
extraPower[i] += extraPower[i - 1]
}
val curPower = power[i] + extraPower[i]
val req = minimum - curPower
if (req <= 0) {
continue
}
if (req > k) {
return false
}
k -= req.toInt()
extraPower[i] += req
if (i + 2 * r + 1 < n) {
extraPower[i + 2 * r + 1] -= req
}
}
return true
}
private fun calculatePowerArray(stations: IntArray, r: Int): LongArray {
val n = stations.size
val preSum = LongArray(n)
for (i in 0 until n) {
var st = i - r
val last = i + r + 1
if (st < 0) {
st = 0
}
preSum[st] += stations[i].toLong()
if (last < n) {
preSum[last] -= stations[i].toLong()
}
}
for (i in 1 until n) {
preSum[i] += preSum[i - 1]
}
return preSum
}
fun maxPower(stations: IntArray, r: Int, k: Int): Long {
var min: Long = 0
var sum = Math.pow(10.0, 10.0).toLong() + Math.pow(10.0, 9.0).toLong()
val power = calculatePowerArray(stations, r)
var ans: Long = -1
while (min <= sum) {
val mid = min + sum shr 1
if (canIBeTheMinimum(power, mid, k, r)) {
ans = mid
min = mid + 1
} else {
sum = mid - 1
}
}
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,046 | LeetCode-in-Kotlin | MIT License |
ceria/22/src/main/kotlin/Solution.kt | VisionistInc | 317,503,410 | false | null | import java.io.File
import java.util.Queue
import java.util.LinkedList
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
private fun solution1(input :List<String>) :Int {
var p1: Queue<Int> = LinkedList<Int>(input.subList(1, input.indexOf("")).map { it.toInt() })
var p2: Queue<Int> = LinkedList<Int>(input.subList(input.indexOf("") + 2, input.size).map { it.toInt() })
while (!p1.isEmpty() && !p2.isEmpty()) {
var c1 = p1.remove()
var c2 = p2.remove()
if (c1 > c2) {
p1.add(c1)
p1.add(c2)
} else {
p2.add(c2)
p2.add(c1)
}
}
val winner = if (p1.isEmpty()) p2 else p1
var productSum = 0
for (i in winner.size downTo 1) {
productSum += winner.remove() * i
}
return productSum
}
private fun solution2(input :List<String>) :Int {
var p1: Queue<Int> = LinkedList<Int>(input.subList(1, input.indexOf("")).map { it.toInt() })
var p2: Queue<Int> = LinkedList<Int>(input.subList(input.indexOf("") + 2, input.size).map { it.toInt() })
var finalDecks = recurseCombat(p1, p2)
var winner = if (finalDecks.first.isEmpty()) finalDecks.second else finalDecks.first
var productSum = 0
for (i in winner.size downTo 1) {
productSum += winner.remove() * i
}
return productSum
}
private fun recurseCombat(player1 :Queue<Int>, player2 :Queue<Int>) :Pair<Queue<Int>, Queue<Int>> {
var p1 = player1
var p2 = player2
var previousRounds = mutableListOf<Pair<Queue<Int>, Queue<Int>>>()
while (!p1.isEmpty() && !p2.isEmpty()) {
if (previousRounds.contains(Pair(p1, p2))) {
// sudden death - p1 wins
p1.add(-1)
p2.add(-1)
break
}
// play on!
val p1C: Queue<Int> = LinkedList<Int>(p1.toIntArray().copyOf().toList())
val p2C: Queue<Int> = LinkedList<Int>(p2.toIntArray().copyOf().toList())
previousRounds.add(Pair(p1C, p2C))
var c1 = p1.remove()
var c2 = p2.remove()
if (p1.size >= c1 && p2.size >= c2) {
var p1Copy: Queue<Int> = LinkedList<Int>(p1.toIntArray().copyOf(c1).toList())
var p2Copy: Queue<Int> = LinkedList<Int>(p2.toIntArray().copyOf(c2).toList())
var decks = recurseCombat(p1Copy, p2Copy)
if (decks.first.contains(-1) && decks.second.contains(-1)) {
// both decks contain the -1 marker, so p1 automatically wins this round
p1.add(c1)
p1.add(c2)
} else {
if (decks.first.isEmpty()) {
p2.add(c2)
p2.add(c1)
} else {
p1.add(c1)
p1.add(c2)
}
}
} else {
if (c1 > c2) {
p1.add(c1)
p1.add(c2)
} else {
p2.add(c2)
p2.add(c1)
}
}
}
return Pair(p1, p2)
} | 0 | Rust | 0 | 0 | 002734670384aa02ca122086035f45dfb2ea9949 | 2,977 | advent-of-code-2020 | MIT License |
src/main/kotlin/com/colinodell/advent2023/Day21.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day21(input: List<String>) {
private val grid = input.toGrid()
private val gridSize = grid.width().also { assert(it == grid.height()) }
private val start = grid.entries.first { it.value == 'S' }.key
// Gets the value at the given position in the infinite grid
private fun get(p: Vector2) = grid[Vector2(p.x.safeMod(gridSize), p.y.safeMod(gridSize))]!!
private fun generatePlotCounts() = sequence {
var positions = listOf(start)
while (true) {
yield(positions.size)
positions = positions.flatMap { it.neighbors() }.distinct().filter { get(it) != '#' }
}
}
fun solvePart1(desiredSteps: Int) = generatePlotCounts().take(desiredSteps + 1).last()
fun solvePart2(desiredSteps: Int): Long {
val grids = desiredSteps / gridSize
val remainder = desiredSteps % gridSize
val counts = generatePlotCounts().take(gridSize * 3 + remainder).toList()
val a0 = counts[remainder].toLong()
val a1 = counts[gridSize + remainder].toLong() - counts[remainder]
val a2 = counts[gridSize * 2 + remainder].toLong() - counts[gridSize + remainder]
return a0 + (a1 * grids) + (grids * (grids - 1L) / 2L) * (a2 - a1)
}
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 1,282 | advent-2023 | MIT License |
src/main/kotlin/g1001_1100/s1080_insufficient_nodes_in_root_to_leaf_paths/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1001_1100.s1080_insufficient_nodes_in_root_to_leaf_paths
// #Medium #Depth_First_Search #Tree #Binary_Tree
// #2023_06_02_Time_271_ms_(100.00%)_Space_38.9_MB_(100.00%)
import com_github_leetcode.TreeNode
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun sufficientSubset(root: TreeNode?, limit: Int): TreeNode? {
return if (sufficientSubset(root, limit, 0, root!!.left == null && root.right == null) < limit) null else root
}
fun sufficientSubset(root: TreeNode?, limit: Int, sum: Int, isLeaf: Boolean): Int {
if (root != null) {
val leftSum = sufficientSubset(
root.left,
limit,
sum + root.`val`,
root.left == null && root.right == null
)
val rightSum = sufficientSubset(
root.right,
limit,
sum + root.`val`,
root.left == null && root.right == null
)
if (leftSum < limit) {
root.left = null
}
if (rightSum < limit) {
root.right = null
}
return leftSum.coerceAtLeast(rightSum)
}
return if (isLeaf) sum else Int.MIN_VALUE
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,436 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/LetterBoxedPuzzle.kt | Kyle-Falconer | 671,044,954 | false | null | import java.util.*
class LetterBoxedSolutionChecker(
private val puzzle: LetterBoxedPuzzle,
private val dictionary: Dictionary,
) {
private var remainingLetters: MutableSet<Char> = puzzle.sides.flatten().toSet().toMutableSet()
init {
reset()
}
fun reset() {
remainingLetters = puzzle.sides.flatten().toSet().toMutableSet()
}
fun checkWord(word: String, initialLetter: Char? = null): CheckedWordResult {
if (word.isEmpty() || !dictionary.validWord(word)) {
return InvalidWord(word, "The given word is not in the dictionary")
}
if (initialLetter != null && !puzzle.tree.containsKey(initialLetter)) {
return InvalidWord(word, "first letter '$initialLetter' not possible")
}
val letters: MutableList<Char> = word.toMutableList()
if (initialLetter != null) {
if (word.first() != initialLetter) {
return InvalidWord(word, "first letter of '$word' must match initial letter $initialLetter")
}
letters.removeFirst()
}
var possibleLetters: Set<Char> = if (initialLetter != null) {
puzzle.tree[initialLetter]!!
} else {
puzzle.sides.flatten().toSet()
}
letters.forEach { letter ->
if (possibleLetters.contains(letter)) {
possibleLetters = puzzle.tree[letter]!!
remainingLetters.remove(letter)
} else {
return InvalidWord(word, "cannot form word '$word' given current puzzle")
}
}
return ValidWord(word, remainingLetters)
}
/**
* Returns an empty list if the puzzle is solved with the given words.
*/
fun checkSolution(words: List<String>): PuzzleSolutionResult {
var firstCharacter: Char? = null
words.forEach { currentWord ->
when (val wordResult = checkWord(currentWord, firstCharacter)) {
is ValidWord -> {
firstCharacter = currentWord.last()
}
is InvalidWord -> {
return InvalidPuzzleSolution(words, wordResult.message)
}
}
}
return if (remainingLetters.isEmpty()) {
ValidPuzzleSolution(words)
} else {
IncompletePuzzleSolution(words, remainingLetters)
}
}
}
class LetterBoxedPuzzle(
val sides: List<Set<Char>>
) {
val tree: TreeMap<Char, Set<Char>> = TreeMap()
init {
checkArguments()
buildTree()
}
private fun checkArguments() {
if (sides.isEmpty()) {
throw IllegalArgumentException("cannot use an empty puzzle")
}
val sideSize = sides[0].size
if (sideSize < 2) {
throw IllegalArgumentException("sides must be at least of length 2")
}
if (sides.any { it.size != sideSize }) {
throw IllegalArgumentException("all sides must be of equal length")
}
}
private fun buildTree() {
sides.forEach { letters ->
letters.forEach { letter ->
tree[letter] = sides.flatten().toSet() - letters
}
}
}
}
| 0 | Kotlin | 0 | 0 | 32f65f18067d686bb79cf84bdbb30bc880319124 | 3,359 | LetterBoxedPuzzleSolver | Apache License 2.0 |
src/main/kotlin/org/metanalysis/srb/Graph.kt | andreihh | 119,868,171 | false | null | /*
* Copyright 2018 <NAME> <<EMAIL>>
*
* 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 org.metanalysis.srb
import org.metanalysis.srb.Graph.Companion.MAX_SIZE
import org.metanalysis.srb.Graph.Edge
import org.metanalysis.srb.Graph.Node
import org.metanalysis.srb.Graph.Subgraph
import java.util.PriorityQueue
data class Graph(
val label: String,
val nodes: Set<Node>,
val edges: List<Edge>
) {
data class Node(val label: String, val revisions: Int)
data class Edge(
val source: String,
val target: String,
val revisions: Int,
val coupling: Double
)
data class Subgraph(val nodes: Set<String>, val density: Double)
companion object {
const val MAX_SIZE: Int = 300
}
}
inline fun Graph.filterNodes(predicate: (Node) -> Boolean): Graph {
val newNodes = nodes.filter(predicate).toSet()
val newLabels = newNodes.map(Node::label).toSet()
val newEdges =
edges.filter { (u, v, _, _) -> u in newLabels && v in newLabels }
return copy(nodes = newNodes, edges = newEdges)
}
inline fun Graph.filterEdges(predicate: (Edge) -> Boolean): Graph {
return copy(edges = edges.filter(predicate))
}
fun List<Edge>.getEndpoints(): Set<String> =
flatMap { (u, v, _, _) -> listOf(u, v) }.toSet()
fun Graph.findBlobs(minDensity: Double): List<Subgraph> {
require(minDensity >= 0.0) { "Invalid blob density '$minDensity'!" }
if (nodes.size > MAX_SIZE) {
return nodes.map { (label, _) ->
Subgraph(nodes = setOf(label), density = 0.0)
}
}
val blobs = arrayListOf<Subgraph>()
for (component in findComponents()) {
findBlobs(this.intersect(component), minDensity, blobs)
}
return blobs
}
fun Graph.findAntiBlob(maxCoupling: Double, minSize: Int): Subgraph? {
require(maxCoupling >= 0.0) { "Invalid anti-blob coupling '$maxCoupling'!" }
require(minSize > 0) { "Invalid anti-blob size '$minSize'!" }
val coupling = hashMapOf<String, Double>()
for ((u, v, _, c) in edges) {
coupling[u] = (coupling[u] ?: 0.0) + c
coupling[v] = (coupling[v] ?: 0.0) + c
}
val antiBlob = hashSetOf<String>()
for ((label, _) in nodes) {
if ((coupling[label] ?: 0.0) <= maxCoupling) {
antiBlob += label
}
}
val degreeSum = edges
.filter { (u, v, _, _) -> u in antiBlob || v in antiBlob }
.sumByDouble(Edge::coupling)
fun density() = degreeSum / antiBlob.size
return if (antiBlob.size >= minSize) Subgraph(antiBlob, density()) else null
}
private class DisjointSets {
private val parent = hashMapOf<String, String>()
operator fun get(x: String): String {
var root = x
while (root in parent) {
root = parent.getValue(root)
}
return root
}
fun merge(x: String, y: String): Boolean {
val rootX = get(x)
val rootY = get(y)
if (rootX != rootY) {
parent[rootX] = rootY
}
return rootX != rootY
}
}
private fun Graph.findComponents(): List<Set<String>> {
val sets = DisjointSets()
for (edge in edges) {
sets.merge(edge.source, edge.target)
}
val components = hashMapOf<String, HashSet<String>>()
for (node in nodes) {
val root = sets[node.label]
components.getOrPut(root, ::HashSet) += node.label
}
return components.values.toList()
}
private fun findBlob(graph: Graph, minDensity: Double): Subgraph? {
val degrees = hashMapOf<String, Double>()
val edges = hashMapOf<String, HashSet<Edge>>()
val nodes = graph.nodes.map(Node::label).toHashSet()
for (edge in graph.edges) {
val (u, v, _, c) = edge
degrees[u] = (degrees[u] ?: 0.0) + c
degrees[v] = (degrees[v] ?: 0.0) + c
edges.getOrPut(u, ::HashSet) += edge
edges.getOrPut(v, ::HashSet) += edge
}
val heap = PriorityQueue<String>(nodes.size.coerceAtLeast(1)) { u, v ->
compareValues(degrees[u], degrees[v])
}
heap += nodes
var blob: Set<String>? = null
var blobDensity = 0.0
var degreeSum = degrees.values.sum()
fun density() = degreeSum / nodes.size
while (nodes.isNotEmpty()) {
if (blob == null || density() > blobDensity) {
blob = nodes.toSet()
blobDensity = density()
}
val node = heap.poll()
for (edge in edges[node].orEmpty()) {
val (u, v, _, c) = edge
val other = if (u == node) v else u
heap -= other
degrees[other] = degrees.getValue(other) - c
edges.getValue(other) -= edge
degreeSum -= 2 * c
heap += other
}
nodes -= node
degrees -= node
edges -= node
}
return if (blob == null || blobDensity < minDensity) null
else Subgraph(blob, blobDensity)
}
private operator fun Graph.minus(nodes: Set<String>): Graph {
val newNodes = this.nodes.filterNot { (label, _) -> label in nodes }
val newEdges = edges.filterNot { (u, v, _, _) -> u in nodes || v in nodes }
return copy(nodes = newNodes.toSet(), edges = newEdges)
}
private fun Graph.intersect(nodes: Set<String>): Graph {
val newNodes = this.nodes.filter { (label, _) -> label in nodes }
val newEdges = edges.filter { (u, v, _, _) -> u in nodes && v in nodes }
return copy(nodes = newNodes.toSet(), edges = newEdges)
}
private fun findBlobs(
graph: Graph,
minDensity: Double,
blobs: ArrayList<Subgraph>
) {
val blob = findBlob(graph, minDensity)
if (blob != null) {
blobs.add(blob)
val remainingGraph = graph - blob.nodes
findBlobs(remainingGraph, minDensity, blobs)
}
}
| 0 | Kotlin | 0 | 0 | 6ede80136baa23e5dca5d210f17a8a287ef14d92 | 6,300 | metanalysis-srb | Apache License 2.0 |
src/main/kotlin/clustering/ModularityCalculator.kt | loehnertz | 194,407,716 | false | null | package codes.jakob.graphenotype.clustering
import codes.jakob.graphenotype.clustering.graph.ClusterableGraph
import codes.jakob.graphenotype.clustering.graph.ClusterableVertex
import codes.jakob.graphenotype.clustering.graph.WeightedEdge
import kotlin.math.pow
object ModularityCalculator {
const val minimumModularity: Double = -1.0
const val maximumModularity: Double = +1.0
fun calculate(clusteredGraph: ClusterableGraph): Double {
val modularitySummands: ArrayList<Double> = arrayListOf()
val accumulatedEdgeWeight: Double = clusteredGraph.edges.sumByDouble { it.weight }
val clusterMap: Map<Int, List<ClusterableVertex>> = buildClusterMap(clusteredGraph)
for ((_, vertices: List<ClusterableVertex>) in clusterMap) {
val edgesStartingAndEndingInCurrentCluster: List<WeightedEdge> = clusteredGraph.edges.filter { vertices.contains(it.connectedVertices.first) && vertices.contains(it.connectedVertices.second) }
val eii: Double = (edgesStartingAndEndingInCurrentCluster.sumByDouble { it.weight } / accumulatedEdgeWeight)
val edgesEndingInCurrentCluster: List<WeightedEdge> = clusteredGraph.edges.filter { (vertices.contains(it.connectedVertices.first) || vertices.contains(it.connectedVertices.second)) }
val aiSquared: Double = (edgesEndingInCurrentCluster.sumByDouble { it.weight } / accumulatedEdgeWeight).pow(2.0)
modularitySummands += (eii - aiSquared)
}
return modularitySummands.sum()
}
private fun buildClusterMap(clusteredGraph: ClusterableGraph): Map<Int, List<ClusterableVertex>> {
val clusterMap: MutableMap<Int, ArrayList<ClusterableVertex>> = mutableMapOf()
for (vertex: ClusterableVertex in clusteredGraph.vertices) {
clusterMap.putIfAbsent(vertex.cluster!!, arrayListOf())
clusterMap.getValue(vertex.cluster!!).add(vertex)
}
return clusterMap.toMap()
}
}
| 0 | Kotlin | 0 | 0 | 06e0cbfeb760ad6efe445d337b527662235fef24 | 1,973 | Graphenotype | Apache License 2.0 |
src/main/kotlin/com/github/wakingrufus/aoc/Day5.kt | wakingrufus | 159,674,364 | false | null | package com.github.wakingrufus.aoc
class Day5 {
fun part1(input: String): Int = reduce(input).length
fun part2(input: String): Int = 'a'.rangeTo('z')
.map { reduceWithout(input, it) }
.map { it.length }
.min() ?: -1
fun part1Fast(input: String): Int = fastReduce(input).length
fun part2Fast(input: String): Int = 'a'.rangeTo('z')
.map { fastReduceWithout(input, it) }
.map { it.length }
.min() ?: -1
fun fastReduceWithout(string: String, char: Char): String =
fastReduce(string.replace(char.toString(), "", true))
fun reduceWithout(string: String, char: Char): String =
reduce(string.replace(char.toString(), "", true))
fun reduce(string: String): String {
val bufferedString = Char.MIN_LOW_SURROGATE + string + Char.MAX_HIGH_SURROGATE
val zippedData = bufferedString.toCharArray().toList().zipWithNext().zipWithNext()
val reducedString = zippedData.flatMap {
if (opposites(it.first) xor opposites(it.second)) {
listOf()
} else if (opposites(it.first) && opposites(it.second)) {
listOf(it.second.second)
} else {
listOf(it.first.second)
}
}.joinToString("")
if (reducedString.length == string.length) {
return reducedString
}
return reduce(reducedString)
}
fun fastReduce(input: String): String {
var string: String = input
var i = 0
while (i < string.length - 1) {
if (opposites(string[i] to string[i + 1])) {
string = string.removeRange(i, i + 2)
i--
if (i < 0) {
i = 0
}
} else {
i++
}
}
return string
}
fun opposites(pair: Pair<Char, Char>): Boolean =
pair.first != pair.second
&& pair.first.toString().toUpperCase() == pair.second.toString().toUpperCase()
} | 0 | Kotlin | 0 | 0 | bdf846cb0e4d53bd8beda6fdb3e07bfce59d21ea | 2,083 | advent-of-code-2018 | MIT License |
AdventOfCodeDay04/src/nativeMain/kotlin/Day04.kt | bdlepla | 451,510,571 | false | {"Kotlin": 165771} | class Day04(private val lines:List<String>) {
private val bingoNumbers = createNumbers(lines.first())
private fun createNumbers(line: String)=line.split(",").map { it.toInt() }
private fun createBingoCards(lines: List<String>): List<BingoCard> {
val input = lines.joinToString("\n").split("\n\n")
return input.map { BingoCard.create(it.split("\n")) }
}
fun solvePart1():Long {
val filteredLines = lines.dropWhile{it.isNotBlank()}.dropWhile{it.isBlank()}
val bingoCards = createBingoCards(filteredLines)
// loop through bingo numbers
// apply number to each card
// after apply, does the card have a winner?
// if so, then the results
val winner = bingoNumbers.asSequence().firstNotNullOf{ number ->
//println("playing bingo number $number")
bingoCards.firstOrNull { card ->card.play(number)}
?.let {Pair(number, it.sumOfUnselected())}
}
return winner.first.toLong() * winner.second
}
fun solvePart2():Long {
val filteredLines = lines.dropWhile{it.isNotBlank()}.dropWhile{it.isBlank()}
val bingoCards = createBingoCards(filteredLines)
// loop through bingo numbers
// apply number to each card
// after apply, does the card have a winner?
// if so, then the results
val winner = bingoNumbers.asSequence().mapNotNull{ number ->
val bingoCardInPlay = bingoCards.filter{!it.won}
//println("playing bingo number $number")
val anyWinners = bingoCardInPlay
.mapNotNull { card ->
if (card.play(number) && bingoCardInPlay.count() == 1) {
val sum = card.sumOfUnselected()
//println("We have a winner $number * $sum")
Pair(number, sum)
} else null
}
if (anyWinners.isNotEmpty()) anyWinners.first() else null
}.first()
return winner.first.toLong() * winner.second
}
} | 0 | Kotlin | 0 | 0 | 1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871 | 2,091 | AdventOfCode2021 | The Unlicense |
src/main/kotlin/kr/co/programmers/P181187.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
import kotlin.math.pow
import kotlin.math.sqrt
// https://github.com/antop-dev/algorithm/issues/502
class P181187 {
fun solution(r1: Int, r2: Int): Long {
// y가 0인 점의 개수
var count = 0L + (r2 - r1 + 1) * 4
// x 좌표만 루프
for (x in 1 until r2) {
val minY = if (x < r1) y(x, r1).toCeilInt() else 1
val maxY = y(x, r2).toFloorInt()
count += (maxY - minY + 1) * 4
}
return count
}
// 피타고라스 정리를 이용하여 y값을 구한다.
private fun y(x: Int, r: Int) = sqrt(r.pow(2) - x.pow(2))
}
// Int.제곱근
private fun Int.pow(n: Int) = this.toDouble().pow(n)
// Double -> 올림 Int
private fun Double.toCeilInt(): Int {
var v = this.toInt()
if (this - v > 0) v++
return v
}
// Double -> 내림 Int
private fun Double.toFloorInt() = this.toInt()
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 917 | algorithm | MIT License |
src/day17/Day17.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day17
import readInputAsString
private const val DAY_ID = "17"
private enum class Direction(val dx: Int, val dy: Int) {
LEFT(-1, 0),
RIGHT(1, 0),
DOWN(0, -1);
}
private data class Point(val x: Int, val y: Int) {
fun move(d: Direction): Point {
return Point(x + d.dx, y + d.dy)
}
}
private data class Rock(val pieces: Set<Point>) {
private var _minX: Int = Int.MAX_VALUE
private var _maxX: Int = Int.MIN_VALUE
private var _minY: Int = Int.MAX_VALUE
private var _maxY: Int = Int.MIN_VALUE
init {
for ((x, y) in pieces) {
_minX = minOf(_minX, x)
_maxX = maxOf(_maxX, x)
_minY = minOf(_minY, y)
_maxY = maxOf(_maxY, y)
}
}
val minX: Int = _minX
val maxX: Int = _maxX
val minY: Int = _minY
val maxY: Int = _maxY
fun move(d: Direction): Rock {
if (minX + d.dx < 0 || maxX + d.dx >= 7) {
return this
}
return Rock(pieces.mapTo(mutableSetOf()) { it.move(d) })
}
companion object {
// (x, y) stands for the left bottom corner
fun create(x: Int, y: Int, shape: Int): Rock {
val pieces = when (shape) {
// ####
0 -> setOf(Point(x, y), Point(x + 1, y), Point(x + 2, y), Point(x + 3, y))
// .#.
// ###
// .#.
1 -> setOf(Point(x + 1, y), Point(x, y + 1), Point(x + 1, y + 1), Point(x + 2, y + 1), Point(x + 1, y + 2))
// ..#
// ..#
// ###
2 -> setOf(Point(x, y), Point(x + 1, y), Point(x + 2, y), Point(x + 2, y + 1), Point(x + 2, y + 2))
// #
// #
// #
// #
3 -> setOf(Point(x, y), Point(x, y + 1), Point(x, y + 2), Point(x, y + 3))
// ##
// ##
4 -> setOf(Point(x, y), Point(x + 1, y), Point(x, y + 1), Point(x + 1, y + 1))
else -> error("Unknown shape of rock: $shape")
}
return Rock(pieces)
}
}
}
fun main() {
fun part1(input: String): Int {
val rocks = 2022
val n = input.length
var i = 0
var maxY = -1
val fallen = mutableSetOf<Point>()
repeat(rocks) { rock ->
var curr = Rock.create(2, maxY + 4, rock % 5)
while (true) {
// jet of gas pushes the rock left or right
val hor = when (val c = input[i++ % n]) {
'<' -> Direction.LEFT
'>' -> Direction.RIGHT
else -> error("Unknown direction: $c")
}
var next = curr.move(hor)
if (next.pieces.none { it in fallen }) {
curr = next
}
// then the rock falls 1 unit
next = curr.move(Direction.DOWN)
if (next.minY < 0 || next.pieces.any { it in fallen }) {
fallen += curr.pieces
maxY = maxOf(maxY, curr.maxY)
break
}
curr = next
}
}
return maxY + 1
}
fun part2(input: List<String>): Int {
TODO()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsString("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == 3068)
//check(part2(testInput) == 42)
val input = readInputAsString("day${DAY_ID}/Day${DAY_ID}")
println(part1(input))
//println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 3,676 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day06.kt | arturkowalczyk300 | 573,084,149 | false | {"Kotlin": 31119} | fun main() {
fun rotateCharArrayLeft(arr: CharArray): CharArray {
for (i in 0 until arr.size - 1) {
arr[i] = arr[i + 1]
}
return arr
}
fun findIndexEndSequenceOfNDifferentCharacters(input: String, N:Int): Int {
if (input.length < N) return -1
var sequence = CharArray(N)
var setSequence: Set<Char> = sequence.toSet()
input.forEachIndexed() { index, it ->
if (index >= N) {
setSequence = sequence.toSet()
if (setSequence.size == N) //set can't contain the same elements!
return index
else {
rotateCharArrayLeft(sequence)
sequence[sequence.lastIndex] = it
}
}
else
sequence[index] = it
}
return -1 //not found
}
fun part1(input: String): Int {
val charactersProcessed = findIndexEndSequenceOfNDifferentCharacters(input, 4)
return charactersProcessed
}
fun part2(input: String): Int {
val charactersProcessed = findIndexEndSequenceOfNDifferentCharacters(input, 14)
return charactersProcessed
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput[0]) == 7)
val input = readInput("Day06")
println(part1(input[0]))
println(part2(input[0]))
}
| 0 | Kotlin | 0 | 0 | 69a51e6f0437f5bc2cdf909919c26276317b396d | 1,471 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day08.kt | dustinlewis | 572,792,391 | false | {"Kotlin": 29162} | import kotlin.text.forEachIndexed as forEachIndexed2
fun main() {
fun part1(input: List<String>): Int {
val edgeCount = input.count() * 2 + (input.count() - 2) * 2
val topBottom = input.fold(MutableList(input.size){ "" }) { acc, element ->
element.withIndex().forEach { c -> acc[c.index] = acc[c.index] + c.value }
acc
}
var visibleInteriorCount = 0
input.forEachIndexed { rowIndex, s ->
if (rowIndex == 0 || rowIndex == input.lastIndex) return@forEachIndexed
s.forEachIndexed2 { colIndex, c ->
if (colIndex == 0 || colIndex == input.lastIndex) return@forEachIndexed2
// check left
val isVisibleLeft = !s.substring(0, colIndex).any { it >= c }
if (isVisibleLeft) {
visibleInteriorCount++
return@forEachIndexed2
}
// check right
val isVisibleRight = !s.substring(colIndex + 1, s.length).any { it >= c }
if (isVisibleRight) {
visibleInteriorCount++
return@forEachIndexed2
}
// check above
val isVisibleAbove = !topBottom[colIndex].substring(0, rowIndex).any { it >= c }
if (isVisibleAbove) {
visibleInteriorCount++
return@forEachIndexed2
}
// check below
val isVisibleBelow = !topBottom[colIndex].substring(rowIndex + 1, topBottom[colIndex].length).any { it >= c }
if (isVisibleBelow) {
visibleInteriorCount++
return@forEachIndexed2
}
}
}
return visibleInteriorCount + edgeCount
}
fun part2(input: List<String>): Int {
val topBottom = input.fold(MutableList(input.size){ "" }) { acc, element ->
element.withIndex().forEach { c -> acc[c.index] = acc[c.index] + c.value }
acc
}
val scenicScores = mutableListOf<Int>()
input.forEachIndexed { rowIndex, s ->
if (rowIndex == 0 || rowIndex == input.lastIndex) return@forEachIndexed
s.forEachIndexed2 { colIndex, c ->
if (colIndex == 0 || colIndex == input.lastIndex) return@forEachIndexed2
// calculate left score
val leftSublist = s.substring(0, colIndex).reversed()
val leftScore = (leftSublist.indexOfFirst { it >= c }.takeIf { it != -1 } ?: leftSublist.lastIndex) + 1
// calculate right score
val rightSublist = s.substring(colIndex + 1, s.length)
val rightScore = (rightSublist.indexOfFirst { it >= c }.takeIf { it != -1 } ?: rightSublist.lastIndex) + 1
// calculate top score
val topSublist = topBottom[colIndex].substring(0, rowIndex).reversed()
val topScore = (topSublist.indexOfFirst { it >= c }.takeIf { it != -1 } ?: topSublist.lastIndex) + 1
// calculate bottom score
val bottomSublist = topBottom[colIndex].substring(rowIndex + 1, topBottom[colIndex].length)
val bottomScore = (bottomSublist.indexOfFirst { it >= c }.takeIf { it != -1 } ?: bottomSublist.lastIndex) + 1
scenicScores.add(leftScore * rightScore * topScore * bottomScore)
}
}
return scenicScores.max()
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c8d1c9f374c2013c49b449f41c7ee60c64ef6cff | 3,617 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/de/huddeldaddel/euler/extensions/LongExtensions.kt | huddeldaddel | 171,357,298 | false | null | package de.huddeldaddel.euler.extensions
import de.huddeldaddel.euler.isInt
import de.huddeldaddel.euler.math.Factorizer
import de.huddeldaddel.euler.sequences.PrimeSequence
import de.huddeldaddel.euler.sequences.TriangleNumberSequence
import kotlin.math.sqrt
fun Long.getPrimeFactors(): Collection<Long> {
val result = mutableSetOf<Long>()
Factorizer().getPrimeFactors(this, result)
return result.filter { l -> l.isPrime() }
}
fun Long.isGoldbachNumber(): Boolean {
for(i in 2..this) {
if(PrimeSequence.isPrime(i)) {
val possibleSquare = sqrt((this - i) / 2.0)
if(possibleSquare.isInt()) {
return true
}
}
}
return false
}
fun Long.isPandigital(): Boolean {
val string = this.toString()
if(9 < string.length) {
return false;
}
for(i in 1..(string.length)) {
if (!string.contains(i.toString()[0])) {
return false
}
}
return true
}
fun Long.isPermutationOf(other: Long) : Boolean {
val thisString = this.toString()
return thisString.all { c -> thisString.count { it == c } == other.toString().count { it == c } }
}
fun Long.isPrime(): Boolean {
return PrimeSequence.isPrime(this)
}
fun Long.isTriangleNumber(): Boolean {
val sequence = TriangleNumberSequence()
var comp = sequence.getNext()
while(this >= comp) {
if(this == comp) {
return true
} else {
comp = sequence.getNext()
}
}
return false
}
fun Long.isTruncatable(): Boolean {
val string = this.toString()
for(i in 1 until string.length) {
val left = string.substring(i).toLong()
if(!left.isPrime())
return false
val right = string.substring(0, string.length -i).toLong()
if(!right.isPrime())
return false
}
return true
}
| 0 | Kotlin | 1 | 0 | df514adde8c62481d59e78a44060dc80703b8f9f | 1,892 | euler | MIT License |
src/Day23.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.time.measureTime
private const val EXPECTED_1 = 94
private const val EXPECTED_2 = 154
private class Day23(isTest: Boolean) : Solver(isTest) {
val field = readAsLines().map { it.toCharArray() }
val Y = field.size
val X = field[0].size
data class Point(val y : Int, val x: Int)
fun part1(): Any {
val sx = 1
val sy = 0
fun canMove(dir: Pair<Int, Int>, ch: Char): Boolean {
return when(ch) {
'#' -> false
'.' -> true
'^' -> dir.first == -1
'>' -> dir.second == 1
'v' -> dir.first == 1
'<' -> dir.second == -1
else -> error("")
}
}
fun mod(x: Point, ch: Char): Point {
return when(ch) {
'#' -> error("")
'.' -> x
'^' -> x.copy(y=x.y - 1)
'>' -> x.copy(x=x.x + 1)
'v' -> x.copy(y=x.y + 1)
'<' -> x.copy(x=x.x - 1)
else -> error("")
}
}
val steps = mutableMapOf<Point, Pair<Int, Set<Point>>>()
val q = ArrayDeque<Point>()
q.add(Point(sy, sx).also {steps[it] = 0 to setOf(it)})
var best = 0
while(!q.isEmpty()) {
val p = q.removeFirst()
val (step, visited) = steps[p]!!
//println("$p $step")
for (dir in listOf(1 to 0, 0 to 1, 0 to -1, -1 to 0)) {
val p2 = Point(p.y + dir.first, p.x + dir.second)
if (p2.x in 0..<X && p2.y in 0..<Y && canMove(dir, field[p2.y][p2.x])) {
val m = mod(p2, field[p2.y][p2.x])
if (m !in visited) {
if ((steps[p2]?.first ?: 0) < step + 1) {
q.add(m)
steps[m] = (step + if (m == p2) 1 else 2) to (visited + m)
if (m.y == Y - 1) {
best = max(best, steps[m]!!.first)
}
}
}
}
}
}
return best
}
fun part2(): Int {
for (y in 0..<Y) {
for (x in 0..<X) {
if (field[y][x] !in setOf('#', '.')) {
field[y][x] = '.'
}
}
}
val graph = mutableMapOf<Point, MutableList<Pair<Point, Int>>>()
fun addLink(a: Point, b: Point, steps: Int) {
graph.getOrPut(a) { mutableListOf() }.let {
if ((b to steps) !in it) {
it.add(b to steps)
}
}
graph.getOrPut(b) { mutableListOf() }.let {
if ((a to steps) !in it) {
it.add(a to steps)
}
}
}
fun buildGraph(sourceP: Point, comeFrom_: Point, p_: Point, steps_: Int) {
var comeFrom = comeFrom_
var p = p_
var steps = steps_
while(true) {
if (graph.contains(p)) {
addLink(p, sourceP, steps)
return
}
if (p.y == Y - 1) {
addLink(p, sourceP, steps)
return
}
val okDirs = listOf(1 to 0, 0 to 1, 0 to -1, -1 to 0).filter { dir ->
val p2 = Point(p.y + dir.first, p.x + dir.second)
if (p2 == comeFrom) {
false
} else if (p2.x in 0..<X && p2.y in 0..<Y && field[p2.y][p2.x] == '.') {
true
} else {
false
}
}
if (okDirs.size > 1) {
// This is a new sourceP
addLink(p, sourceP, steps)
okDirs.forEach { dir ->
val p2 = Point(p.y + dir.first, p.x + dir.second)
buildGraph(p, p, p2, 1)
}
return
}
val dir = okDirs.single()
//buildGraph(sourceP, p, Point(p.y + dir.first, p.x + dir.second), steps + 1)
comeFrom = p
p = Point(p.y + dir.first, p.x + dir.second)
steps++
}
}
buildGraph(Point(0, 1), Point(0, 1), Point(1, 1), 1)
val visited = HashSet<Point>()
fun longestPath(p: Point): Int {
if (p.x == X-2 && p.y == Y-1) {
return 0
}
return graph[p]!!.mapNotNull { (point, dist) ->
if (point !in visited) {
visited += point
val result = longestPath(point) + dist
visited -= point
result
} else {
null
}
}.maxOrNull() ?: -100000
}
return longestPath(Point(0, 1).also { visited.add(it) })
}
}
fun main() {
val testInstance = Day23(true)
val instance = Day23(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
measureTime {
println("part2 ANSWER: ${instance.part2()}")
}.also { println(it) }
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 5,602 | advent-of-code-2022 | Apache License 2.0 |
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/algo/sorts.kt | aquatir | 76,377,920 | false | {"Java": 674809, "Python": 143889, "Kotlin": 112192, "Haskell": 57852, "Elixir": 33284, "TeX": 20611, "Scala": 17065, "Dockerfile": 6314, "HTML": 4714, "Shell": 387, "Batchfile": 316, "Erlang": 269, "CSS": 97} | fun <T> swap(array: Array<T>, fstIndex: Int, sndIndex: Int) {
val fstValue = array[fstIndex]
array[fstIndex] = array[sndIndex]
array[sndIndex] = fstValue
}
/** Selection sort: Find the smallest -> insert it to next position */
fun <T : Comparable<T>> selectionSort(array: Array<T>) {
for (i in array.indices) {
var curMinIndex = i
for (j in (i + 1) until array.size) {
if (array[j] < array[curMinIndex]) {
curMinIndex = j
}
}
swap(array, i, curMinIndex)
}
}
/** Insertion sort: Assume everything before i is sorted.
* Add another element to sorted part -> swap elements until current element is in it's correct place */
fun <T : Comparable<T>> insertionSort(array: Array<T>) {
for (i in array.indices) {
for (j in i downTo 1) {
if (array[j] < array[j - 1]) {
swap(array, j, j - 1)
} else {
break
}
}
}
}
/** h-sort with sequence 3x+1 */
fun <T : Comparable<T>> shellSort(array: Array<T>) {
var h = 1
while (h < array.size / 3) {
h = 3 * h + 1 // 1, 4, 13, 40...
}
while (h >= 1) {
// h-sort array here with step == h
for (i in h until array.size) {
for (j in i downTo h step h) {
if (array[j] < array[j - h]) {
swap(array, j, j - h)
} else {
continue
}
}
}
h /= 3
}
}
fun <T : Comparable<T>> mergeSort(array: Array<T>) {
fun sort(array: Array<T>, auxArray: Array<T>, startIndex: Int, endIndex: Int) {
if (endIndex <= startIndex) return
val middle = startIndex + ((endIndex - startIndex) / 2)
sort(array, auxArray, startIndex = 0, endIndex = middle)
sort(array, auxArray, startIndex = middle + 1, endIndex = endIndex)
merge(array, auxArray, leftStart = 0, leftEnd = middle, rightStart = middle + 1, rightEnd = endIndex)
}
val aux = array.copyOf()
sort(array, aux, startIndex = 0, endIndex = array.lastIndex)
}
fun <T : Comparable<T>> bottomUpMergeSort(array: Array<T>) {
val aux = array.copyOf()
val n = array.size
var step = 1
while (step < n) { // this will iterate over arrays of 2, than 4, than 8, until the end
var index = 0
while (index < n - step) {
merge(
array,
aux,
leftStart = index,
leftEnd = index + step - 1,
rightStart = index + step,
rightEnd = minOf(n - 1, index + step + step - 1)
)
index += step + step
}
step += step
}
/*
* Implementation can be much shorter for language which support 3 part for-loops. It will be as simpel as
* for (step = 1; step < n; step = step + step) {
* for (i = 0; i < n - step; i += step + step) {
* merge (array, aux, i, i + step - 1, i + step, minOf(n - 1, i + step + step - 1)
* }
* }
*/
}
fun <T : Comparable<T>> merge(
array: Array<T>,
auxArray: Array<T>,
leftStart: Int,
leftEnd: Int,
rightStart: Int,
rightEnd: Int
) {
for (i in leftStart..rightEnd) {
auxArray[i] = array[i]
}
var left = leftStart
var right = rightStart
for (index in leftStart..rightEnd) {
when {
left > leftEnd -> {
array[index] = auxArray[right]
right++
}
right > rightEnd -> {
array[index] = auxArray[left]
left++
}
auxArray[left] <= auxArray[right] -> {
array[index] = auxArray[left];
left++
}
else -> {
array[index] = auxArray[right];
right++
}
}
}
}
fun <T : Comparable<T>> quickSort(array: Array<T>) {
fun partition(array: Array<T>, startLeft: Int, startRight: Int): Int {
/*
First element is used as partition element
After outer while(true) loop completes, all element to the left of startLeft will be
lower and all element to right of it will be higher.
Here we start with startLeft and startRight + 1 because the first thing we do before comparing
is ++left and --right
*/
var left = startLeft
var right = startRight + 1
while (true) {
while (array[++left] < array[startLeft]) {
if (left == startRight) {
break
}
}
while (array[startLeft] < array[--right]) {
if (right == startLeft) {
break
}
}
if (left >= right) break
swap(array, left, right)
}
swap(array, startLeft, right)
return right // right is now in place
}
fun sort(array: Array<T>, startLeft: Int, startRight: Int) {
if (startRight <= startLeft) return
val inCorrectPlaceIndex = partition(array, startLeft, startRight)
sort(array, startLeft, inCorrectPlaceIndex - 1)
sort(array, inCorrectPlaceIndex + 1, startRight)
}
array.shuffle()
sort(array, 0, array.lastIndex)
}
| 1 | Java | 3 | 6 | eac3328ecd1c434b1e9aae2cdbec05a44fad4430 | 5,378 | code-samples | MIT License |
src/main/kotlin/net/voldrich/aoc2022/Day02.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2022
import net.voldrich.BaseDay
// https://adventofcode.com/2022/day/2
fun main() {
Day02().run()
}
// Written mostly by copilot
class Day02 : BaseDay() {
enum class Type {
ROCK, PAPER, SCISSORS
}
override fun task1() : Int {
return input.lines().map {
val (val1, val2) = it.split(" ").take(2)
val elfMove = mapElfMove(val1)
val myMove = mapMyMove(val2)
calculateScore(elfMove, myMove)
}.sum()
}
override fun task2() : Int {
return input.lines().map {
val (val1, val2) = it.split(" ").take(2)
val elfMove = mapElfMove(val1)
val myMove = mapMyMove2(val2, elfMove)
calculateScore(elfMove, myMove)
}.sum()
}
private fun mapMyMove2(val2: String, elfMove: Type): Type {
return when (val2) {
// loose
"X" -> when (elfMove) {
Type.ROCK -> Type.SCISSORS
Type.PAPER -> Type.ROCK
Type.SCISSORS -> Type.PAPER
}
// draw
"Y" -> when (elfMove) {
Type.ROCK -> Type.ROCK
Type.PAPER -> Type.PAPER
Type.SCISSORS -> Type.SCISSORS
}
//win
"Z" -> when (elfMove) {
Type.ROCK -> Type.PAPER
Type.PAPER -> Type.SCISSORS
Type.SCISSORS -> Type.ROCK
}
else -> throw IllegalArgumentException("Unknown move $val2")
}
}
private fun mapMyMove(val2: String) = when {
val2 == "X" -> Type.ROCK
val2 == "Y" -> Type.PAPER
val2 == "Z" -> Type.SCISSORS
else -> throw Exception("Unknown move $val2")
}
private fun mapElfMove(val1: String) = when {
val1 == "A" -> Type.ROCK
val1 == "B" -> Type.PAPER
val1 == "C" -> Type.SCISSORS
else -> throw Exception("Unknown elf move $val1")
}
private fun calculateScore(elfMove: Type, myMove: Type): Int {
return when (elfMove) {
Type.ROCK -> {
when (myMove) {
Type.ROCK -> 1 + 3
Type.PAPER -> 2 + 6
Type.SCISSORS -> 3 + 0
}
}
Type.PAPER -> {
when (myMove) {
Type.ROCK -> 1 + 0
Type.PAPER -> 2 + 3
Type.SCISSORS -> 3 + 6
}
}
Type.SCISSORS -> {
when (myMove) {
Type.ROCK -> 1 + 6
Type.PAPER -> 2 + 0
Type.SCISSORS -> 3 + 3
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 2,771 | advent-of-code | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions55.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round0
import kotlin.math.abs
import kotlin.math.max
fun test55() {
val a = BinaryTreeNode(1)
val b = BinaryTreeNode(2)
val c = BinaryTreeNode(3)
val d = BinaryTreeNode(4)
val e = BinaryTreeNode(5)
val f = BinaryTreeNode(6)
val g = BinaryTreeNode(7)
a.left = b
a.right = c
b.left = d
b.right = e
c.right = f
e.left = g
println("二叉树的高度为:${a.treeDepth()}")
println()
println(a.isBalanced1())
println(a.isBalanced2())
c.right = null
println()
println(a.isBalanced1())
println(a.isBalanced2())
}
// 题目一:二叉树的深度
fun <T> BinaryTreeNode<T>.treeDepth(): Int {
var left = 1
left += this.left?.treeDepth() ?: 0
var right = 1
right += this.right?.treeDepth() ?: 0
return max(right, left)
}
// 题目二:判断一棵二叉树是否是平衡二叉树
fun <T> BinaryTreeNode<T>.isBalanced1(): Boolean {
val left = left?.treeDepth() ?: 0
val right = right?.treeDepth() ?: 0
if (abs(left - right) > 1)
return false
return this.left?.isBalanced1() ?: true && this.right?.isBalanced1() ?: true
}
fun <T> BinaryTreeNode<T>.isBalanced2(): Boolean = this.isBalancedCore(intArrayOf(0))
private fun <T> BinaryTreeNode<T>.isBalancedCore(depth: IntArray): Boolean {
val left = intArrayOf(0)
val right = intArrayOf(0)
if (this.left?.isBalancedCore(left) != false && this.right?.isBalancedCore(right) != false) {
if (abs(left[0] - right[0]) <= 1) {
depth[0] = 1 + if (left[0] > right[0])
left[0]
else
right[0]
return true
} else
return false
}
return false
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,568 | Algorithm | Apache License 2.0 |
src/main/kotlin/g1701_1800/s1799_maximize_score_after_n_operations/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1701_1800.s1799_maximize_score_after_n_operations
// #Hard #Array #Dynamic_Programming #Math #Bit_Manipulation #Backtracking #Bitmask #Number_Theory
// #2023_06_18_Time_347_ms_(73.17%)_Space_36.4_MB_(81.30%)
class Solution {
fun maxScore(nums: IntArray): Int {
val n = nums.size
val memo = arrayOfNulls<Int>(1 shl n)
return helper(1, 0, nums, memo)
}
private fun helper(operationNumber: Int, mask: Int, nums: IntArray, memo: Array<Int?>): Int {
val n = nums.size
if (memo[mask] != null) {
return memo[mask]!!
}
if (operationNumber > n / 2) {
return 0
}
var maxScore = Int.MIN_VALUE
for (i in 0 until n) {
if (mask and (1 shl i) == 0) {
for (j in i + 1 until n) {
if (mask and (1 shl j) == 0) {
val score = operationNumber * gcd(nums[i], nums[j])
val score2 = helper(operationNumber + 1, mask or (1 shl i) or (1 shl j), nums, memo)
maxScore = Math.max(maxScore, score + score2)
}
}
}
}
memo[mask] = maxScore
return maxScore
}
private fun gcd(a: Int, b: Int): Int {
return if (b == 0) {
a
} else gcd(b, a % b)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,373 | LeetCode-in-Kotlin | MIT License |
src/Day08.kt | felldo | 572,233,925 | false | {"Kotlin": 76496} | import kotlin.math.max
fun main() {
fun part1(testInput: List<String>): Int {
var visibleTrees = 0
//Top and bottom row
visibleTrees += testInput.first().length
visibleTrees += testInput.last().length
// Sides minus the edges
visibleTrees += testInput.size * 2 - 4
for (row in 1 until testInput.size - 1) {
for (column in 1 until testInput[row].length - 1) {
// count how many numbers are surrounded by larger numbers
val currentNum = testInput[row][column]
var visible = false
var edge = 1
while (testInput[row - edge][column] < currentNum) {
if (row - edge == 0) {
visible = true
break
}
edge++
}
edge = 1
while (testInput[row][column - edge] < currentNum) {
if (column - edge == 0) {
visible = true
break
}
edge++
}
edge = 1
while (testInput[row + edge][column] < currentNum) {
if (row + edge == testInput.size - 1) {
visible = true
break
}
edge++
}
edge = 1
while (testInput[row][column + edge] < currentNum) {
if (column + edge == testInput[row].length - 1) {
visible = true
break
}
edge++
}
if (visible) {
visibleTrees++
}
}
}
return visibleTrees
}
fun part2(input: List<String>): Int {
val trees = mutableListOf<MutableList<Int>>()
var bestView = 0
for (line in input) {
trees.add(mutableListOf())
for (i in line) {
trees.last().add(i.digitToInt())
}
}
for (r in trees.indices) {
for (c in trees[r].indices) {
val height = trees[r][c]
// Left
var left = 0
for (x in c - 1 downTo 0) {
if (trees[r][x] < height) {
left++
} else {
left++
break
}
}
// Right
var right = 0
for (x in c + 1 until trees[r].size) {
if (trees[r][x] < height) {
right++
} else {
right++
break
}
}
// Up
var up = 0
for (x in r - 1 downTo 0) {
if (trees[x][c] < height) {
up++
} else {
up++
break
}
}
// Down
var down = 0
for (x in r + 1 until trees.size) {
if (trees[x][c] < height) {
down++
} else {
down++
break
}
}
val scenic = left * right * up * down
bestView = max(bestView, scenic)
}
}
return bestView
}
val testInput = readInput("Day08")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | 0ef7ac4f160f484106b19632cd87ee7594cf3d38 | 3,817 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/d3_BinaryDiagnostic/BinaryDiagnostic.kt | aormsby | 425,644,961 | false | {"Kotlin": 68415} | package d3_BinaryDiagnostic
import util.Input
import util.Output
fun main() {
Output.day(3, "Binary Diagnostic")
val startTime = Output.startTime()
val report = Input.parseLines("/input/d3_diagnostic_report.txt")
val transposedReport = transposeMatrix(report)
val gammaStr = transposedReport.fold("") { str, cur ->
if (cur.count { it == '0' } > cur.count { it == '1' }) str + '0'
else str + '1'
}
val gamma = gammaStr.toInt(2)
val bitMask = Array(gammaStr.length) { '1' }.joinToString("")
val epsilonStr = gamma.xor(bitMask.toInt(2))
Output.part(1, "Power Consumption", gamma * epsilonStr)
Output.part(2, "Life Support Rating", getO2Rating(report) * getCO2Rating(report))
Output.executionTime(startTime)
}
fun transposeMatrix(list: List<String>): List<MutableList<Char>> {
val transposed = mutableListOf<MutableList<Char>>()
list.forEachIndexed { x, str ->
str.forEachIndexed { y, ch ->
if (transposed.size <= y) transposed.add(y, mutableListOf(ch))
else transposed[y].add(ch)
}
}
return transposed
}
fun getO2Rating(list: List<String>): Int {
var l = list
for (i in 0 until l.first().length) {
val highBit = getMostCommonBit(l.groupingBy { it[i] }.eachCount())
l = l.filter { it[i] == highBit }
if (l.size <= 1) break
}
return l.joinToString("").toInt(2)
}
fun getCO2Rating(list: List<String>): Int {
var l = list
for (i in 0 until l.first().length) {
val highBit = getMostCommonBit(l.groupingBy { it[i] }.eachCount())
l = l.filter { it[i] != highBit }
if (l.size <= 1) break
}
return l.joinToString("").toInt(2)
}
fun getMostCommonBit(countMap: Map<Char, Int>, tie: Char = '1'): Char =
when {
countMap['0'] == countMap['1'] -> tie
else -> countMap.maxByOrNull { it.value }?.key ?: tie
} | 0 | Kotlin | 1 | 1 | 193d7b47085c3e84a1f24b11177206e82110bfad | 1,927 | advent-of-code-2021 | MIT License |
src/main/kotlin/executeAgeGenderCmds.kt | sam-hoodie | 534,831,633 | false | {"Kotlin": 43732} | fun main() {
val data = parseCongressFile(true)
interpretAgeAndGenderCommand("-get house.serving.age.oldest", data)
}
fun interpretAgeAndGenderCommand(command: String, data: List<Person>) {
// -get congress.age.youngest
// -get congress.age.oldest
// -get congress.gender.prevalent
if (command.startsWith("-get congress.all.age") || command.startsWith("-get congress.historic.age")) {
println(" The age commands are incompatible with historic data files")
return
}
val commandParameters = command.split('.')
if (commandParameters[2] == "age") {
if (commandParameters[3] == "youngest") {
println(" The youngest congressman was born on ${getMostExtremeAge(true, data)}")
return
}
if (commandParameters[3] == "oldest") {
println(" The oldest congressman was born on ${getMostExtremeAge(false, data)}")
return
}
}
if (commandParameters[2] == "gender") {
when (getCommonGender(data)) {
CommonGender.MALE -> println(" There are more male than female congressmen")
CommonGender.FEMALE -> println(" There are more female than male congressmen")
CommonGender.SAME -> println(" There are the same amount of male and female congressmen")
}
return
}
printAutocorrect(command)
}
enum class CommonGender {
MALE,
FEMALE,
SAME
}
fun getCommonGender(data: List<Person>): CommonGender {
val allGender = arrayListOf<String>()
for (element in data) {
allGender.add(element.bio.gender)
}
var maleCount = 0
var femaleCount = 0
for (i in 0 until allGender.size) {
if (allGender[i] == "M") {
maleCount++
} else if (allGender[i] == "F") {
femaleCount++
}
}
return if (maleCount > femaleCount) {
CommonGender.MALE
} else if (femaleCount > maleCount) {
CommonGender.FEMALE
} else {
CommonGender.SAME
}
}
fun getMostExtremeAge(youngest: Boolean, data: List<Person>): String {
var extremeBday = "0000-00-00"
if (!youngest) {
extremeBday = "9999-99-99"
}
for (i in data.indices) {
if (data[i].bio.birthday != null) {
if (getBirthdayComparison(data[i].bio.birthday.toString(), extremeBday, youngest)) {
extremeBday = data[i].bio.birthday.toString()
}
}
}
val birthdayParts = extremeBday.split('-')
return monthInterpreter(birthdayParts[1].toInt().toString()) + " " + birthdayParts[2] + ", " + birthdayParts[0]
}
fun getBirthdayComparison(birthday1: String, birthday2: String, younger: Boolean): Boolean {
val bday1 = birthday1.split('-')
val bday2 = birthday2.split('-')
if (bday1[0].toInt() < bday2[0].toInt()) {
return !younger
} else if (bday1[0].toInt() == bday2[0].toInt()) {
if (bday1[1].toInt() < bday2[1].toInt()) {
return !younger
} else if (bday1[1].toInt() == bday2[1].toInt()) {
if (bday1[2].toInt() < bday2[2].toInt()) {
return !younger
} else if (bday1[2].toInt() == bday2[2].toInt()) {
return false
}
}
}
return younger
}
fun monthInterpreter(month: String): String {
return when (month.toInt()) {
1 -> "January"
2 -> "February"
3 -> "March"
4 -> "April"
5 -> "May"
6 -> "June"
7 -> "July"
8 -> "August"
9 -> "September"
10 -> "October"
11 -> "November"
12 -> "December"
else -> "Invalid Month Number"
}
} | 0 | Kotlin | 0 | 0 | 9efea9f9eec55c1e61ac1cb11d3e3460f825994b | 3,685 | congress-challenge | Apache License 2.0 |
src/main/kotlin/days/Day03.kt | TheMrMilchmann | 433,608,462 | false | {"Kotlin": 94737} | /*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.*
fun main() {
fun part1(): Int {
data class DiagnosticReport(val gammaRate: Int, val epsilonRate: Int)
data class BitsAtIndex(val index: Int, val gammaBit: Char, val epsilonBit: Char)
data class IncompleteDiagnosticData(val gammaBits: String, val epsilonBits: String)
val incompleteDiagnosticData = readInput()
.flatMap { sequence -> sequence.mapIndexed { index, c -> index to c } }
.groupBy(keySelector = { it.first }, valueTransform = { it.second })
.map { (index, values) ->
val bits = values.groupingBy { it }.eachCount()
BitsAtIndex(
index,
bits.maxByOrNull { it.value }!!.key,
bits.minByOrNull { it.value }!!.key
)
}
.sortedBy { it.index }
.fold(initial = IncompleteDiagnosticData(gammaBits = "", epsilonBits = "")) { acc, it ->
IncompleteDiagnosticData(
gammaBits = acc.gammaBits + it.gammaBit,
epsilonBits = acc.epsilonBits + it.epsilonBit
)
}
val report = DiagnosticReport(
gammaRate = incompleteDiagnosticData.gammaBits.toInt(radix = 2),
epsilonRate = incompleteDiagnosticData.epsilonBits.toInt(radix = 2)
)
return report.gammaRate * report.epsilonRate
}
fun part2(): Int {
val input = readInput()
tailrec fun Pair<List<String>, List<String>>.filterDownToOne(index: Int = 0, max: Int): Pair<List<String>, List<String>> {
var (first, second) = this
if (first.size > 1) {
val occs = first.groupingBy { it[index] }.eachCount()
val mcb = if (occs['0']!! <= occs['1']!!) '1' else '0'
first = first.filter { it[index] == mcb }
}
if (second.size > 1) {
val occs = second.groupingBy { it[index] }.eachCount()
val lcb = if (occs['0']!! > occs['1']!!) '1' else '0'
second = second.filter { it[index] == lcb }
}
return if (index < max) (first to second).filterDownToOne(index + 1, max) else (first to second)
}
return (input to input).filterDownToOne(max = input.first().length - 1)
.let { it.first.first().toInt(radix = 2) * it.second.first().toInt(radix = 2) }
}
println("Part 1: ${part1()}")
println("Part 2: ${part2()}")
} | 0 | Kotlin | 0 | 1 | dfc91afab12d6dad01de552a77fc22a83237c21d | 3,664 | AdventOfCode2021 | MIT License |
src/main/kotlin/me/peckb/aoc/_2015/calendar/day09/Day09.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2015.calendar.day09
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import me.peckb.aoc.generators.PermutationGenerator
import javax.inject.Inject
import kotlin.Int.Companion.MAX_VALUE
import kotlin.math.max
import kotlin.math.min
class Day09 @Inject constructor(
private val permutationGenerator: PermutationGenerator,
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(filename: String) = generatorFactory.forFile(filename).read { input ->
generateDistances(input.toList(), ::min)
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input ->
generateDistances(input.toList(), ::max)
}
private fun generateDistances(data: List<String>, comparator: (Long, Long) -> Long): Long {
val allCities = mutableSetOf<String>()
data.forEach {
val cities = it.substringBefore(" = ")
val (source, destination) = cities.split(" to ")
allCities.add(source)
allCities.add(destination)
}
val citiesWithIndices = allCities.toList()
val indexMapping = mutableMapOf<String, Int>()
citiesWithIndices.forEachIndexed { i, city -> indexMapping[city] = i }
val distances = Array(allCities.size) { Array(allCities.size) { MAX_VALUE.toLong() } }.apply {
indices.forEach { this[it][it] = 0 }
}
data.forEach {
val distance = it.substringAfter(" = ").toLong()
val cities = it.substringBefore(" = ")
val (source, destination) = cities.split(" to ")
distances[indexMapping[source]!!][indexMapping[destination]!!] = distance
distances[indexMapping[destination]!!][indexMapping[source]!!] = distance
}
val mutatingData = Array(distances.size) { MAX_VALUE }.apply {
(0 until size).forEach { this[it] = it }
}
val permutations = permutationGenerator.generatePermutations(mutatingData)
var bestCost = permutations.first().toList().windowed(2).sumOf { (s, d) -> distances[s][d] }
permutations.drop(1).map { permutation ->
val cost = permutation.toList().windowed(2).sumOf { (s, d) -> distances[s][d] }
bestCost = comparator(bestCost, cost)
}
return bestCost
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 2,189 | advent-of-code | MIT License |
CameraXVideo/utils/src/main/java/com/example/android/camera/utils/CameraSizes.kt | android | 185,094,070 | false | {"Kotlin": 665074, "Java": 50339, "RenderScript": 2800} | /*
* Copyright 2020 The Android Open Source Project
*
* 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
*
* https://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.example.android.camera.utils
import android.graphics.Point
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.params.StreamConfigurationMap
import android.util.Size
import android.view.Display
import kotlin.math.max
import kotlin.math.min
/** Helper class used to pre-compute shortest and longest sides of a [Size] */
class SmartSize(width: Int, height: Int) {
var size = Size(width, height)
var long = max(size.width, size.height)
var short = min(size.width, size.height)
override fun toString() = "SmartSize(${long}x${short})"
}
/** Standard High Definition size for pictures and video */
val SIZE_1080P: SmartSize = SmartSize(1920, 1080)
/** Returns a [SmartSize] object for the given [Display] */
fun getDisplaySmartSize(display: Display): SmartSize {
val outPoint = Point()
display.getRealSize(outPoint)
return SmartSize(outPoint.x, outPoint.y)
}
/**
* Returns the largest available PREVIEW size. For more information, see:
* https://d.android.com/reference/android/hardware/camera2/CameraDevice and
* https://developer.android.com/reference/android/hardware/camera2/params/StreamConfigurationMap
*/
fun <T>getPreviewOutputSize(
display: Display,
characteristics: CameraCharacteristics,
targetClass: Class<T>,
format: Int? = null
): Size {
// Find which is smaller: screen or 1080p
val screenSize = getDisplaySmartSize(display)
val hdScreen = screenSize.long >= SIZE_1080P.long || screenSize.short >= SIZE_1080P.short
val maxSize = if (hdScreen) SIZE_1080P else screenSize
// If image format is provided, use it to determine supported sizes; else use target class
val config = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)!!
if (format == null)
assert(StreamConfigurationMap.isOutputSupportedFor(targetClass))
else
assert(config.isOutputSupportedFor(format))
val allSizes = if (format == null)
config.getOutputSizes(targetClass) else config.getOutputSizes(format)
// Get available sizes and sort them by area from largest to smallest
val validSizes = allSizes
.sortedWith(compareBy { it.height * it.width })
.map { SmartSize(it.width, it.height) }.reversed()
// Then, get the largest output size that is smaller or equal than our max size
return validSizes.first { it.long <= maxSize.long && it.short <= maxSize.short }.size
} | 141 | Kotlin | 2,274 | 4,651 | 96cbc7d8014d72470c4b70ca76adfdc332d60123 | 3,110 | camera-samples | Apache License 2.0 |
src/main/kotlin/day10/solution.kt | bukajsytlos | 433,979,778 | false | {"Kotlin": 63913} | package day10
import java.io.File
val chunkPairs = mapOf(
'(' to ')',
'[' to ']',
'{' to '}',
'<' to '>',
)
val illegalCharacterPoints = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137,
)
val autocompleteCharacterPoints = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
fun main() {
val lines = File("src/main/kotlin/day10/input.txt").readLines()
val autoCompletesByState = lines
.map { it.toCharArray() }
.map { autocomplete(it) }
.partition { it.failed() }
println(autoCompletesByState.first
.mapNotNull { it.illegalChar }
.mapNotNull { illegalCharacterPoints[it] }
.sumOf { it }
)
println(autoCompletesByState.second
.mapNotNull { it.missedChars }
.map { it.fold(0L) { acc, unit -> acc * 5 + (autocompleteCharacterPoints[unit] ?: 0) } }
.sorted().let { it[it.size / 2] })
}
fun autocomplete(line: CharArray): Autocomplete {
val stack = ArrayDeque<Char>()
for (char in line) {
if (char in chunkPairs.keys) {
stack.addLast(char)
} else {
stack.removeLastOrNull()?.let {
if (chunkPairs[it] != char) {
return Autocomplete(illegalChar = char)
}
}
}
}
return Autocomplete(missedChars = stack.mapNotNull { chunkPairs[it] }.reversed())
}
data class Autocomplete(val illegalChar: Char? = null, val missedChars: List<Char>? = null) {
fun failed() = illegalChar != null
} | 0 | Kotlin | 0 | 0 | f47d092399c3e395381406b7a0048c0795d332b9 | 1,565 | aoc-2021 | MIT License |
src/Day21.kt | zt64 | 572,594,597 | false | null | import kotlin.math.absoluteValue
private object Day21 : Day(21) {
private val monkeys = input.lines().associate { line ->
val (name, job) = line.split(": ")
val split = job.split(" ")
val function = if (split.size == 1) {
Job.Number(job.toLong())
} else {
Job.Operation(split[1], split[0], split[2])
}
name to function
}.toMutableMap()
private fun solve(monkeyName: String): Long {
return when (val job = monkeys[monkeyName]!!) {
is Job.Number -> job.value
is Job.Operation -> when (job.op) {
"+" -> solve(job.a) + solve(job.b)
"-" -> solve(job.a) - solve(job.b)
"*" -> solve(job.a) * solve(job.b)
"/" -> solve(job.a) / solve(job.b)
else -> throw IllegalArgumentException("Unknown op: ${job.op}")
}
}
}
override fun part1(): Long = solve("root")
override fun part2(): Long {
val job = monkeys["root"]!! as Job.Operation
var crack = 0L
while (true) {
monkeys["humn"] = Job.Number(crack)
val a = solve(job.a)
val b = solve(job.b)
if (a == b) break
val diff = (a - b).absoluteValue
if (diff < 100) crack++ else crack += diff / 100
}
return crack
}
private sealed interface Job {
data class Number(val value: Long) : Job
data class Operation(val op: String, val a: String, val b: String) : Job
}
}
private fun main() = Day21.main() | 0 | Kotlin | 0 | 0 | 4e4e7ed23d665b33eb10be59670b38d6a5af485d | 1,610 | aoc-2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day05/Day05.kt | pfmaggi | 438,378,048 | false | {"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184} | /*
* 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 com.pietromaggi.aoc2021.day05
import com.pietromaggi.aoc2021.readInput
class AoCPoint(val x: Int, val y: Int) : Comparable<AoCPoint> {
constructor(point: List<Int>) : this(point[0], point[1])
override fun compareTo(other: AoCPoint): Int {
if (this.x != other.x) {
return this.x - other.x
}
return this.y - other.y
}
operator fun rangeTo(that: AoCPoint) = AoCPointRange(this, that)
operator fun inc(): AoCPoint {
return AoCPoint(this.x + 1, this.y + 1)
}
override fun toString(): String = "$x, $y"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AoCPoint
if (x != other.x) return false
if (y != other.y) return false
return true
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
}
class AoCPointRange(
override val start: AoCPoint,
override val endInclusive: AoCPoint,
) : ClosedRange<AoCPoint>, Iterable<AoCPoint> {
override fun iterator(): Iterator<AoCPoint> {
return AoCPointIterator(start, endInclusive)
}
}
class AoCPointIterator(private val start: AoCPoint, private val endInclusive: AoCPoint) : Iterator<AoCPoint> {
private var initValue = start
private var currentValue = start
private var incrementX = if (start.x < endInclusive.x) 1 else -1
private var incrementY = if (start.y < endInclusive.y) 1 else -1
override fun hasNext(): Boolean {
return currentValue != endInclusive
}
override fun next(): AoCPoint {
currentValue = initValue
initValue = if (start.x == endInclusive.x) {
AoCPoint(initValue.x, initValue.y + incrementY)
} else if (start.y == endInclusive.y) {
AoCPoint(initValue.x + incrementX, initValue.y)
} else {
AoCPoint(initValue.x + incrementX, initValue.y + incrementY)
}
return currentValue
}
}
fun compute(input: List<String>, full: Boolean): Int {
val fields: MutableMap<AoCPoint, Int> = mutableMapOf()
input.map { it.split(" -> ") }.map { line ->
val a = line[0].split(",").map { it.toInt() }
val b = line[1].split(",").map { it.toInt() }
val pointA = AoCPoint(a)
val pointB = AoCPoint(b)
if (full or (pointA.x == pointB.x) or (pointA.y == pointB.y)) {
// Only process horizontal and vertical lines if full == false
for (point in pointA..pointB) {
fields[point] = fields.getOrDefault(point, 0) + 1
}
}
}
return fields.filterValues { it > 1 }.count()
}
fun main() {
val input = readInput("Day05")
println(compute(input, false))
println(compute(input, true))
}
| 0 | Kotlin | 0 | 0 | 7c4946b6a161fb08a02e10e99055a7168a3a795e | 3,474 | AdventOfCode | Apache License 2.0 |
kotlin-practice/src/main/kotlin/practice/Reservation.kt | nicolegeorgieva | 590,020,790 | false | {"Kotlin": 120359} | package practice
//reserve a table
//input 1: peopleCount
//input 2: each person first name
//input 3: each person spending
//min consumation: 10 BGN/person (one can pay for the other). 10bgn is okay for 1 person
//reservation failed/successful (? advance need to pay && ? total)
//program says ? expense(all), advance money = 20% spending/person
fun main() {
val reservation = tableReserve()
println(reservation)
if (validateReservation(reservation)) {
println("Valid reservation.")
println("Your table's total bill is ${calculateTotalBill(reservation)}.")
println("Your table's money in advance is ${calculateAdvanceMoney(reservation)}.")
} else {
println("Invalid reservation.")
}
}
data class Reservation(val peopleCount: Int, val firstNames: List<String>, val individualBill: List<Double>)
private fun tableReserve(): Reservation {
val peopleCount = readInput("people count").toInt()
val firstNames = mutableListOf<String>()
val individualBill = mutableListOf<Double>()
for (i in 1..peopleCount) {
println("Enter person $i")
firstNames.add(readInput("first name"))
individualBill.add(readInput("individual spending").toDouble())
}
return Reservation(peopleCount, firstNames, individualBill)
}
private fun readInput(message: String): String {
println("Enter $message")
return readln()
}
fun validateReservation(reservation: Reservation): Boolean {
val tableMin = reservation.peopleCount * 10
val totalIndividualBillPlans = reservation.individualBill.sum()
return reservation.peopleCount > 0 && totalIndividualBillPlans >= tableMin
}
fun calculateAdvanceMoney(reservation: Reservation): Double {
return reservation.individualBill.sum() * 0.2
}
fun calculateTotalBill(reservation: Reservation): Double {
return reservation.individualBill.sum()
} | 0 | Kotlin | 0 | 1 | c96a0234cc467dfaee258bdea8ddc743627e2e20 | 1,887 | kotlin-practice | MIT License |
src/main/kotlin/com/dvdmunckhof/aoc/event2023/Day04.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2023
class Day04(private val input: List<String>) {
fun solvePart1(): Int {
return matchingCardNumbers().filter { it > 0 }.sumOf { 1 shl it - 1 }
}
fun solvePart2(): Int {
val cardsCount = Array(input.size) { 1 }
for ((index, matches) in matchingCardNumbers().withIndex()) {
val cardCount = cardsCount[index]
for (i in index+1..index+matches) {
cardsCount[i] += cardCount
}
}
return cardsCount.sum()
}
private fun matchingCardNumbers(): Sequence<Int> {
val firstLine = input[0]
val colonIndex = firstLine.indexOf(':')
val pipeIndex = firstLine.indexOf('|', colonIndex)
val winningRange = (colonIndex + 2)..<pipeIndex step 3
val numbersRange = (pipeIndex + 2)..firstLine.lastIndex step 3
return input.asSequence().map { line ->
val winningNumbers = winningRange.map { i -> line.substring(i, i + 2) }.toHashSet()
numbersRange.count { i -> line.substring(i, i + 2) in winningNumbers }
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,124 | advent-of-code | Apache License 2.0 |
src/Day03.kt | jamesrobert | 573,249,440 | false | {"Kotlin": 13069} | fun main() {
fun itemWeight(commonItem: Char) = if (commonItem <= 'Z') commonItem - 'A' + 27
else commonItem - 'a' + 1
fun List<List<String>>.sumWeightCommonItems() = sumOf {strings ->
strings.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.sumOf { itemWeight(it) }
}
fun part1(input: List<String>): Int = input.map {
listOf(it.substring(0, it.length / 2), it.substring(it.length / 2))
}.sumWeightCommonItems()
fun part2(input: List<String>): Int = input
.chunked(3)
.sumWeightCommonItems()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d0b49770fc313ae42d802489ec757717033a8fda | 873 | advent-of-code-2022 | Apache License 2.0 |
src/me/bytebeats/algo/kt/Solution5.kt | bytebeats | 251,234,289 | false | null | package me.bytebeats.algo.kt
import me.bytebeats.algo.kt.design.Employee
import me.bytebeats.algo.kt.design.NestedInteger
import me.bytebeats.algs.ds.TreeNode
import me.bytebeats.algs.ds.TreeNode2
class Solution5 {
var maxPathSum = Int.MIN_VALUE
fun maxPathSum(root: TreeNode?): Int {//124
maxGain(root)
return maxPathSum
}
private fun maxGain(root: TreeNode?): Int {
if (root == null) return 0
val left = Math.max(maxGain(root.left), 0)
val right = Math.max(maxGain(root.right), 0)
maxPathSum = Math.max(maxPathSum, left + right + root.`val`)
return root.`val` + Math.max(left, right)
}
fun findSecondMinimumValue(root: TreeNode?): Int {//671
val list = mutableListOf<Int>()
convert2List(root, list)
if (list.size > 1) {
list.sort()
return list[1]
} else {
return -1
}
}
private fun convert2List(root: TreeNode?, list: MutableList<Int>) {
if (root == null) {
return
}
if (!list.contains(root.`val`)) {
list.add(root.`val`)
}
convert2List(root.left, list)
convert2List(root.right, list)
}
fun kthLargest(root: TreeNode?, k: Int): Int {//面试题54
val list = mutableListOf<Int>()
convert2List(root, list)
list.sort()
return list[list.size - k]
}
fun connect(root: TreeNode2?): TreeNode2? {
if (root != null) {
connect(root.left, root.right)
}
return root
}
private fun connect(left: TreeNode2?, right: TreeNode2?) {//116
if (left == null || right == null) {
return
}
left.next = right
connect(left.left, left.right)
connect(right.left, right.right)
connect(left.right, right.left)
}
fun isValidSequence(root: TreeNode?, arr: IntArray): Boolean {
return isValidSequence(root, arr, 0)
}
fun isValidSequence(node: TreeNode?, arr: IntArray, index: Int): Boolean {
if (node == null) {
return arr.isEmpty()
} else if (index > arr.lastIndex) {
return false
} else if (index == arr.lastIndex && node.left == null && node.right == null && arr[index] == node.`val`) {
return true
} else {
return index < arr.size && node.`val` == arr[index] &&
(isValidSequence(node.left, arr, index + 1) || isValidSequence(node.right, arr, index + 1))
}
}
fun singleNumber(nums: IntArray): IntArray {//260
var xorV = 0
for (num in nums) {
xorV = xorV xor num
}
var d = 1
while (d and xorV == 0) {
d = d shl 1
}
var a = 0
var b = 0
for (num in nums) {
if (num and d == 0) {
a = a xor num
} else {
b = b xor num
}
}
return intArrayOf(a, b)
}
fun mincostTickets(days: IntArray, costs: IntArray): Int {//983
return dp(days, costs, 0, Array(days.size) { null })
}
private fun dp(
days: IntArray,
costs: IntArray,
i: Int,
memo: Array<Int?>,
durations: IntArray = intArrayOf(1, 7, 30)
): Int {
if (i >= days.size) {
return 0
}
if (memo[i] != null) {
return memo[i]!!
}
memo[i] = Int.MAX_VALUE
var j = i
for (k in durations.indices) {
while (j < days.size && days[j] < days[i] + durations[k]) {
j++
}
memo[i] = Math.min(memo[i]!!, dp(days, costs, j, memo) + costs[k])
}
return memo[i]!!
}
fun coinChange(coins: IntArray, amount: Int): Int {//322
if (coins.isNotEmpty() && amount >= 0) {
val matrix = Array(amount + 1) { -1 }
matrix[0] = 0
var diff = 0
for (i in 1..amount) {
for (j in coins.indices) {
diff = i - coins[j]
if (diff >= 0 && matrix[diff] > -1) {
if (matrix[i] == -1) {
matrix[i] = matrix[diff] + 1
} else {
matrix[i] = Math.min(matrix[i], matrix[diff] + 1)
}
}
}
}
return matrix[amount]
}
return -1
}
fun majorityElement(nums: IntArray): Int {//169
nums.sort()
return nums[nums.size / 2]
}
fun majorityElement1(nums: IntArray): List<Int> {//229, Moore voting
val ans = mutableListOf<Int>()
if (nums.isNotEmpty()) {
//initialize two candidates
var candidate1 = nums.first()
var voting1 = 0
var candidate2 = nums.first()
var voting2 = 0
for (i in nums.indices) {//配对阶段
//投票
if (candidate1 == nums[i]) {
voting1++
continue
}
if (candidate2 == nums[i]) {
voting2++
continue
}
//第一个候选人配对
if (voting1 == 0) {
candidate1 = nums[i]
voting1++
continue
}
if (voting2 == 0) {
candidate2 = nums[i]
voting2++
continue
}
voting1--
voting2--
}
voting1 = 0
voting2 = 0
for (i in nums.indices) {//计数阶段, 找到两个候选人之后, 确定票数是否 >=3
if (candidate1 == nums[i]) {
voting1++
} else if (candidate2 == nums[i]) {
voting2++
}
}
if (voting1 > nums.size / 3) {
ans.add(candidate1)
}
if (voting2 > nums.size / 3) {
ans.add(candidate2)
}
}
return ans
}
fun isMajorityElement(nums: IntArray, target: Int): Boolean {//1150
if (nums.isNotEmpty() && target == nums[nums.size / 2]) {
var count = 1
val half = nums.size / 2
var i = half
while (--i > -1 && nums[i] == target) {
count++
}
i = half
while (++i < nums.size && nums[i] == target) {
count++
}
return count > half
}
return false
}
fun findMaxAverage(nums: IntArray, k: Int): Double {//643
var sum = 0.0
for (i in 0 until k - 1) {
sum += nums[i]
}
var maxSum = sum + nums[k - 1]
for (i in k - 1 until nums.size) {
sum += nums[i]
if (sum > maxSum) {
maxSum = sum
}
sum -= nums[i - k + 1]
}
return maxSum / k
}
fun findMaxAverage1(nums: IntArray, k: Int): Double {//644
var maxAvg = Double.MIN_VALUE
var flag = false
for (i in k..nums.size) {
var sum = 0.0
for (j in 0..i - 2) {
sum += nums[j]
}
var maxSum = sum + nums[i - 1]
for (j in i - 1 until nums.size) {
sum += nums[j]
maxSum = Math.max(maxSum, sum)
sum -= nums[j - i + 1]
}
if (!flag) {
maxAvg = maxSum / i
flag = !flag
} else {
maxAvg = Math.max(maxAvg, maxSum / i)
}
}
return maxAvg
}
fun isSubtree(s: TreeNode?, t: TreeNode?): Boolean {//572
if (s == null) {
return t == null
} else {
var flag = isSameTree(s, t)
if (s.left != null) {
flag = flag or isSubtree(s?.left, t)
}
if (s.right != null) {
flag = flag or isSubtree(s?.right, t)
}
return flag
}
}
private fun isSameTree(s: TreeNode?, t: TreeNode?): Boolean {
if (s == null && t == null) {
return true
} else if (s != null && t != null) {
return s.`val` == t.`val` && isSameTree(s.left, t.left) && isSameTree(s.right, t.right)
} else {
return false
}
}
fun getImportance(employees: List<Employee?>, id: Int): Int {//690
var count = 0
val set = mutableSetOf<Int>()
set.add(id)
val sub = mutableSetOf<Int>()
while (set.isNotEmpty()) {
set.forEach { id ->
employees.first { it?.id == id }?.apply {
count += importance
subordinates?.apply { sub.addAll(this) }
}
}
set.clear()
set.addAll(sub)
sub.clear()
}
return count
}
fun countUnivalSubtrees(root: TreeNode?): Int {//250
val map = mutableMapOf<Int, Int>()
traverse(root, map)
for (key in map.keys) {
count(root, key, map)
}
map.forEach { t, u -> println("$t, $u") }
return map.entries.filter { it.value > 1 }.map { it.value }.sum()
}
private fun count(node: TreeNode?, `val`: Int, map: MutableMap<Int, Int>) {
node?.apply {
if (isUnivalSubtree(this, `val`)) {
map.compute(`val`) { _, v -> if (v == null) 1 else v + 1 }
}
if (left != null) {
count(left, `val`, map)
}
if (right != null) {
count(right, `val`, map)
}
}
}
private fun isUnivalSubtree(root: TreeNode?, `val`: Int): Boolean {
if (root == null) {
return true
}
return root.`val` == `val` && isUnivalSubtree(root.left, `val`) && isUnivalSubtree(root.right, `val`)
}
private fun traverse(root: TreeNode?, map: MutableMap<Int, Int>) {
if (root == null) {
return
}
if (!map.containsKey(root.`val`)) {
map[root.`val`] = 0
}
if (root.left != null) {
traverse(root.left, map)
}
if (root.right != null) {
traverse(root.right, map)
}
}
fun constructMaximumBinaryTree(nums: IntArray): TreeNode? {//654
return constructMaximumBinaryTree(nums, 0, nums.lastIndex)
}
fun constructMaximumBinaryTree(nums: IntArray, left: Int, right: Int): TreeNode? {//654
if (left > right) {
return null
}
var max = nums[left]
var index = left
for (i in left..right) {
if (nums[i] > max) {
max = nums[i]
index = i
}
}
val root = TreeNode(max)
root.left = constructMaximumBinaryTree(nums, left, index - 1)
root.right = constructMaximumBinaryTree(nums, index + 1, right)
return root
}
fun insertIntoMaxTree(root: TreeNode?, `val`: Int): TreeNode? {//998
if (root == null) {
return TreeNode(`val`)
} else {
if (root.`val` > `val`) {
root.right = insertIntoMaxTree(root.right, `val`)
return root
} else {
val node = TreeNode(`val`)
node.left = root
return node
}
}
}
fun depthSum(nestedList: List<NestedInteger>): Int {// 339
var sum = 0
val list = mutableListOf<NestedInteger>()
list.addAll(nestedList)
var depth = 1
val sub = mutableListOf<NestedInteger>()
while (list.isNotEmpty()) {
list.forEach {
if (it.isInteger()) {
sum += depth * (it.getInteger() ?: 0)
}
it.getList()?.apply {
sub.addAll(this)
}
}
depth++
list.clear()
list.addAll(sub)
sub.clear()
}
return sum
}
fun depthSumInverse(nestedList: List<NestedInteger>): Int {//364
var sum = 0
val list = mutableListOf<NestedInteger>()
list.addAll(nestedList)
var depth = 1
val sub = mutableListOf<NestedInteger>()
while (list.isNotEmpty()) {//computing max depth
list.forEach {
it.getList()?.apply {
sub.addAll(this)
}
}
depth++
list.clear()
list.addAll(sub)
sub.clear()
}
list.addAll(nestedList)
sub.clear()
while (list.isNotEmpty()) {
depth--
list.forEach {
if (it.isInteger()) {
sum += depth * (it.getInteger() ?: 0)
}
it.getList()?.apply {
sub.addAll(this)
}
}
list.clear()
list.addAll(sub)
sub.clear()
}
return sum
}
fun arrayNesting(nums: IntArray): Int {//565
var ans = 0
val visited = BooleanArray(nums.size) { false }
var start = 0
var count = 0
for (i in nums.indices) {
if (!visited[i]) {
start = nums[i]
count = 0
do {
start = nums[start]
count++
visited[start] = true
} while (start != nums[i])
if (count > ans) {
ans = count
}
}
}
return ans
}
fun findPairs(nums: IntArray, k: Int): Int {//532
var count = 0
nums.sort()
var left = 0
var right = 1
var diff = 0
while (right < nums.size) {
diff = nums[right] - nums[left]
if (diff < k) {
right++
} else if (diff > k) {
left++
while (left >= right) {
right++
}
} else {
count++
while (right < nums.lastIndex && nums[right] == nums[right + 1]) {
right++
}
while (left < right && nums[left] == nums[left + 1]) {
left++
}
left++
do {
right++
} while (left >= right)
}
}
return count
}
fun convertBST(root: TreeNode?): TreeNode? {//538
val list = mutableListOf<TreeNode>()
convertBST2List(root, list)
var sum = 0
var value = 0
for (i in list.lastIndex downTo 0) {
value = list[i].`val`
list[i].`val` += sum
sum += value
}
return root
}
fun bstToGst(root: TreeNode?): TreeNode? {//1038
val list = mutableListOf<TreeNode>()
convertBST2List(root, list)
var sum = 0
var value = 0
for (i in list.lastIndex downTo 0) {
value = list[i].`val`
list[i].`val` += sum
sum += value
}
return root
}
private fun convertBST2List(root: TreeNode?, list: MutableList<TreeNode>) {
if (root == null) {
return
}
convertBST2List(root.left, list)
list.add(root)
convertBST2List(root.right, list)
}
fun convertBiNode(root: TreeNode?): TreeNode? {//面试题17.12
if (root == null) {
return null
}
val list = mutableListOf<TreeNode>()
convertBST2List(root, list)
for (i in list.indices) {
list[i].left = null
if (i < list.lastIndex) {
list[i].right = list[i + 1]
} else {
list[i].right = null
}
}
return list[0]
}
fun matrixReshape(nums: Array<IntArray>, r: Int, c: Int): Array<IntArray> {//566
val row = nums.size
val column = nums[0].size
if (row * column != r * c) {
return nums
}
val ans = Array(r) { IntArray(c) }
for (i in 0 until r * c) {
ans[i / c][i % c] = nums[i / column][i % column]
}
return ans
}
fun canThreePartsEqualSum(A: IntArray): Boolean {//1013
if (A.size > 2) {
var sum = A.sum()
if (sum % 3 != 0) {
return false
}
val third = sum / 3
var pivot1 = 0
sum = 0
for (i in A.indices) {
sum += A[i]
if (sum == third) {
pivot1 = i
break
}
}
if (pivot1 < A.lastIndex - 1) {
var pivot2 = 0
sum = 0
for (i in pivot1 + 1 until A.lastIndex) {
sum += A[i]
if (sum == third) {
pivot2 = i
break
}
}
return pivot2 in pivot1 + 1 until A.lastIndex && A.drop(pivot2 + 1).sum() == third
} else {
return false
}
}
return false
}
fun checkStraightLine(coordinates: Array<IntArray>): Boolean {//1232
val point1 = coordinates.first()
val point2 = coordinates.last()
val a = point1[1] - point2[1]
val b = point2[0] - point1[0]
val c = point1[0] * point2[1] - point2[0] * point1[1]
for (i in 1 until coordinates.lastIndex) {
if (a * coordinates[i][0] + b * coordinates[i][1] + c != 0) {
return false
}
}
return true
}
fun balanceBST(root: TreeNode?): TreeNode? {//1382
val list = mutableListOf<Int>()
midReversal(root, list)
return createBST(list, 0, list.lastIndex)
}
private fun createBST(list: MutableList<Int>, left: Int, right: Int): TreeNode? {
if (left < 0 || left > right || right > list.lastIndex) {
return null
}
val mid = left + (right - left) / 2
val root = TreeNode(list[mid])
root.left = createBST(list, left, mid - 1)
root.right = createBST(list, mid + 1, right)
return root
}
private fun midReversal(root: TreeNode?, list: MutableList<Int>) {
if (root == null) {
return
}
midReversal(root.left, list)
list.add(root.`val`)
midReversal(root.right, list)
}
fun twoSumBSTs(root1: TreeNode?, root2: TreeNode?, target: Int): Boolean {//1214
if (root1 == null) {
return false
}
return sumBSTs(root1.`val`, root2, target) || twoSumBSTs(root1.left, root2, target) || twoSumBSTs(
root1.right,
root2,
target
)
}
private fun sumBSTs(`val`: Int, root2: TreeNode?, target: Int): Boolean {
if (root2 == null) {
return false
}
return `val` + root2.`val` == target || sumBSTs(`val`, root2.left, target) || sumBSTs(
`val`,
root2.right,
target
)
}
var maxSum: Int? = null
fun maxSumBST(root: TreeNode?): Int {//1373
maxSum = null
reverse(root)
return if (maxSum ?: 0 < 0) 0 else maxSum!!
}
private fun reverse(root: TreeNode?) {
if (root == null) {
return
}
if (isBST(root)) {
sumBST(root)
}
reverse(root.left)
reverse(root.right)
}
private fun isBST(root: TreeNode?): Boolean {
if (root == null || root.left == null && root.right == null) {
return true
} else if (root.left != null && root.right != null) {
return root.`val` > root.left.`val` && root.`val` < root.right.`val` && isBST(root.left) && isBST(root.right)
} else if (root.left != null) {
return root.`val` > root.left.`val` && isBST(root.left)
} else {
return root.`val` < root.right.`val` && isBST(root.right)
}
}
private fun sumBST(root: TreeNode?): Int {
if (root == null) {
return 0
} else {
var sum = root.`val`
if (root.left != null) {
sum += sumBST(root.left)
}
if (root.right != null) {
sum += sumBST(root.right)
}
if (maxSum == null) {
maxSum = sum
} else if (maxSum!! < sum) {
maxSum = sum
}
return sum
}
}
fun findMode(root: TreeNode?): IntArray {//501
val map = mutableMapOf<Int, Int>()
countMode(root, map)
val max = map.values.maxOfOrNull { it }
return map.entries.filter { it.value == max }.map { it.key }.toIntArray()
}
private fun countMode(root: TreeNode?, map: MutableMap<Int, Int>) {
root?.apply {
map.compute(`val`) { _, v -> if (v == null) 1 else v + 1 }
left?.apply { countMode(this@apply, map) }
right?.apply { countMode(this@apply, map) }
}
}
fun generateAbbreviations(word: String): List<String> {//320
val ans = mutableListOf<String>()
for (i in 1..word.length) {
}
return ans
}
//1035, equals to longest common sequences, which is not longest common substring
fun maxUncrossedLines1(A: IntArray, B: IntArray): Int {
val row = A.size
val column = B.size
val dp = Array(row + 1) { IntArray(column + 1) }
for (i in 0 until row) {
for (j in 0 until column) {
if (A[i] == B[j]) {
dp[i + 1][j + 1] = dp[i][j] + 1
} else {
dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1])
}
}
}
return dp[row][column]
}
fun maxUncrossedLines(A: IntArray, B: IntArray): Int {//1035
return maxUncrossedLines(A, 0, B, 0)
}
fun maxUncrossedLines(A: IntArray, a: Int, B: IntArray, b: Int): Int {
if (a > A.lastIndex || b > B.lastIndex) {
return 0
} else {
if (A[a] == B[b]) {
return 1 + maxUncrossedLines(A, a + 1, B, b + 1)
} else {
return Math.max(maxUncrossedLines(A, a + 1, B, b), maxUncrossedLines(A, a, B, b + 1))
}
}
}
fun findUnsortedSubarray(nums: IntArray): Int {//581
var ans = 0
val copy = nums.copyOfRange(0, nums.size)
copy.sort()
var start = 0
while (start < nums.size && copy[start] == nums[start]) {
start++
}
var end = nums.lastIndex
while (end >= start && copy[end] == nums[end]) {
end--
}
if (end >= start) {
return end - start + 1
} else {
return 0
}
}
fun pairSums(nums: IntArray, target: Int): List<List<Int>> {//面试题16.24
val ans = mutableListOf<MutableList<Int>>()
nums.sort()
var i = 0
var j = nums.lastIndex
var sum = 0
while (i < j) {
sum = nums[i] + nums[j]
if (sum > target) {
j--
} else if (sum < target) {
i++
} else {
val pair = mutableListOf<Int>()
pair.add(nums[i])
pair.add(nums[j])
ans.add(pair)
i++
j--
}
}
return ans
}
var ans: TreeNode? = null
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {//236
ans = null
dfs(root, p, q)
return ans
}
private fun dfs(root: TreeNode?, p: TreeNode?, q: TreeNode?): Boolean {
if (root == null) {
return false
}
val lson = dfs(root.left, p, q)
val rson = dfs(root.right, p, q)
if (lson && rson || (lson || rson) && (root.`val` == p?.`val` || root.`val` == q?.`val`)) {
ans = root
}
return lson || rson || (root.`val` == p?.`val` || root.`val` == q?.`val`)
}
fun buildArray(target: IntArray, n: Int): List<String> {//1441
val ans = mutableListOf<String>()
var count = 1
for (i in target.indices) {
for (j in count..n) {
if (target[i] > j) {
ans.add("Push")
ans.add("Pop")
count++
} else if (target[i] == j) {
ans.add("Push")
count++
} else {
break
}
}
}
return ans
}
fun countTriplets(arr: IntArray): Int {//1442
var ans = 0
var jxor = 0
var kxor = 0
for (i in 0..arr.size - 2) {
jxor = arr[i]
for (j in i + 1 until arr.size) {
if (j > i + 1) {
jxor = jxor xor arr[j - 1]
}
kxor = 0
for (k in j until arr.size) {
kxor = kxor xor arr[k]
if (jxor == kxor) {
ans++
}
}
}
}
return ans
}
fun findJudge(N: Int, trust: Array<IntArray>): Int {//997
val degrees = IntArray(N + 1) { 0 }
trust.forEach {
degrees[it[0]]--
degrees[it[1]]++
}
for (i in 1..N) {
if (degrees[i] == N - 1) {
return i
}
}
return -1
}
fun findDuplicates(nums: IntArray): List<Int> {//442
val ans = mutableListOf<Int>()
var index = 0
for (i in nums.indices) {
index = Math.abs(nums[i]) - 1
if (nums[index] < 0) {
ans.add(index + 1)
}
nums[index] = -nums[index]
}
return ans
}
fun minTime(time: IntArray, m: Int): Int {//LCP 12
var left = 0
var right = 0
var mid = 0
for (i in time.indices) {
right += time[i]
}
while (left <= right) {
mid = left + (right - left) / 2
if (check(mid, time, m)) {
right = mid - 1
} else {
left = mid + 1
}
}
return left
}
private fun check(limit: Int, time: IntArray, day: Int): Boolean {
var useDay = 1
var totalTime = 0
var maxTime = 0
var nextTime = 0
for (i in time.indices) {
nextTime = Math.min(maxTime, time[i])
if (nextTime + totalTime <= limit) {
totalTime += nextTime
maxTime = Math.max(maxTime, time[i])
} else {
useDay++
totalTime = 0
maxTime = time[i]
}
}
return useDay <= day
}
fun isBoomerang(points: Array<IntArray>): Boolean {//1037
val p1 = points[0]
val p2 = points[1]
val p3 = points[2]
if (p1[0] == p2[0] && p1[1] == p2[1] || p1[0] == p3[0] && p1[1] == p3[1] || p3[0] == p2[0] && p3[1] == p2[1]) {
return false
}
val a = p2[1] - p1[1]
val b = p1[0] - p2[0]
val c = p2[0] * p1[1] - p1[0] * p2[1]
return a * p3[0] + b * p3[1] + c != 0
}
fun isOneBitCharacter(bits: IntArray): Boolean {//717
var is2ndChar = false
var i = 0
while (i < bits.size) {
if (bits[i] == 1) {
i += 2
is2ndChar = true
} else {
i++
is2ndChar = false
}
}
return !is2ndChar
}
fun grayCode(n: Int): List<Int> {//89
val ans = mutableListOf<Int>()
return ans
}
fun floodFill(image: Array<IntArray>, sr: Int, sc: Int, newColor: Int): Array<IntArray> {//733
if (image.isNotEmpty() && image[0].isNotEmpty() && image[sr][sc] != newColor) {
floodFill(image, sr, sc, image[sr][sc], newColor)
}
return image
}
private fun floodFill(image: Array<IntArray>, sr: Int, sc: Int, oldColor: Int, newColor: Int) {//733
if (sr < 0 || sc < 0 || sr > image.lastIndex || sc > image[0].lastIndex) {
return
}
if (image[sr][sc] == oldColor) {
image[sr][sc] = newColor
if (sr - 1 > -1 && image[sr - 1][sc] == oldColor) {
floodFill(image, sr - 1, sc, oldColor, newColor)
}
if (sr + 1 < image.size && image[sr + 1][sc] == oldColor) {
floodFill(image, sr + 1, sc, oldColor, newColor)
}
if (sc - 1 > -1 && image[sr][sc - 1] == oldColor) {
floodFill(image, sr, sc - 1, oldColor, newColor)
}
if (sc + 1 < image[0].size && image[sr][sc + 1] == oldColor) {
floodFill(image, sr, sc + 1, oldColor, newColor)
}
}
}
fun islandPerimeter(grid: Array<IntArray>): Int {//463,
var perimeter = 0
for (i in grid.indices) {
for (j in grid[0].indices) {
if (grid[i][j] == 1) {
if (i - 1 < 0 || grid[i - 1][j] == 0) {
perimeter++
}
if (i + 1 > grid.lastIndex || grid[i + 1][j] == 0) {
perimeter++
}
if (j - 1 < 0 || grid[i][j - 1] == 0) {
perimeter++
}
if (j + 1 > grid[0].lastIndex || grid[i][j + 1] == 0) {
perimeter++
}
}
}
}
return perimeter
}
fun subdomainVisits(cpdomains: Array<String>): List<String> {//811
val map = mutableMapOf<String, Int>()
for (d in cpdomains) {
val sp = d.split(" ")
val count = sp[0].toInt()
for (key in subDomains(sp[1])) {
map.compute(key) { _, v -> if (v == null) count else v + count }
}
}
return map.entries.map { "${it.value} ${it.key}" }
}
private fun subDomains(domain: String): List<String> {
val ans = mutableListOf<String>()
val keys = domain.split(".")
var tmp = ""
for (i in keys.lastIndex downTo 0) {
if (i == keys.lastIndex) {
tmp = keys[i]
} else {
tmp = "${keys[i]}.$tmp"
}
ans.add(tmp)
}
return ans
}
fun findRepeatedDnaSequences1(s: String): List<String> {//187
val ans = mutableListOf<String>()
var sub = ""
for (i in 0 until s.length - 10) {
sub = s.substring(i, i + 10)
if (s.indexOf(sub, i + 1) > 0 && !ans.contains(sub)) {
ans.add(sub)
}
}
return ans
}
fun findRepeatedDnaSequences(s: String): List<String> {//187
val ans = mutableListOf<String>()
val next = IntArray(10)
var sub = ""
for (i in 0 until s.length - 10) {
next(s, i, i + 9, next)
for (j in i + 10 until s.length) {
if (kmp(s, j, next, i) > -1) {
sub = s.substring(i, i + 10)
if (!ans.contains(sub)) {
ans.add(sub)
}
}
}
}
return ans
}
private fun next(s: String, start: Int, end: Int, next: IntArray) {
for (i in 0 until 10) {
next[i] = 0
}
var j = 0
for (i in start + 1..end) {
while (j > 0 && s[i] != s[j + start]) {
j = next[j - 1]
}
if (s[i] == s[j + start]) {
j++
}
next[i - start] = j
}
}
private fun kmp(s: String, start: Int, next: IntArray, nS: Int): Int {
var j = 0
for (i in start until s.length) {
while (j > 0 && s[i] != s[j + nS]) {
j = next[j - 1]
}
if (s[i] == s[j + nS]) {
j++
}
if (j == 10) {
return i - j - nS + 1
}
}
return -1
}
/**
* single element in a sorted array
*/
fun singleNonDuplicate(nums: IntArray): Int {//540
var xorVal = 0
nums.forEach {
xorVal = xorVal xor it
}
return xorVal
}
fun singleNonDuplicate1(nums: IntArray): Int {//540, 只考虑 index 为偶数的索引
var low = 0
var high = nums.lastIndex
var mid = 0
while (low < high) {
mid = low + (high - low) / 2
if (mid and 1 == 1) mid--
if (nums[mid] == nums[mid + 1]) {
low = mid + 2
} else {
high = mid
}
}
return nums[low]
}
} | 0 | Kotlin | 0 | 1 | 7cf372d9acb3274003bb782c51d608e5db6fa743 | 33,826 | Algorithms | MIT License |
2017/day08_kotlin/day8.kts | nikklassen | 112,742,014 | false | {"Rust": 216342, "Go": 151024, "C#": 6392, "Assembly": 6377, "F#": 5335, "Clojure": 4751, "C": 3896, "C++": 3754, "Haskell": 3712, "Elixir": 3132, "Scala": 2919, "Java": 2775, "JavaScript": 2688, "Shell": 2551, "Groovy": 2544, "OCaml": 2073, "PHP": 2034, "Python": 2024, "Julia": 1990, "Ruby": 1990, "Kotlin": 1949, "Common Lisp": 1621, "MATLAB": 1286, "R": 818, "Raku": 774, "HTML": 634} | import java.io.File
import java.lang.Integer.max
data class Instruction(var reg: String, var incDec: String, var op: Int, var comparisonReg: String, var comparison: String, var predicate: Int)
fun main(maxReg: Boolean) {
val instructions = arrayListOf<Instruction>()
val registers = mutableMapOf<String, Int>()
File("input").forEachLine {
val match = Regex("([a-z]+) (inc|dec) (-?\\d+) if ([a-z]+) (\\S+) (-?\\d+)").find(it) ?: return@forEachLine
val register = match.groupValues[1]
val comparisonReg = match.groupValues[4]
registers[register] = 0
registers[comparisonReg] = 0
val instruction = Instruction(register, match.groupValues[2], match.groupValues[3].toInt(), comparisonReg, match.groupValues[5], match.groupValues[6].toInt())
instructions.add(instruction)
}
var maxVal = Int.MIN_VALUE
instructions.forEach {
val comparisonRegValue = registers.getOrDefault(it.comparisonReg, 0)
val doOp = when {
it.comparison == "==" -> comparisonRegValue == it.predicate
it.comparison == "!=" -> comparisonRegValue != it.predicate
it.comparison == ">=" -> comparisonRegValue >= it.predicate
it.comparison == ">" -> comparisonRegValue > it.predicate
it.comparison == "<=" -> comparisonRegValue <= it.predicate
it.comparison == "<" -> comparisonRegValue < it.predicate
else -> false
}
if (!doOp) {
return@forEach
}
var regValue = registers.getOrDefault(it.reg, 0)
if (it.incDec == "inc") {
regValue += it.op
} else {
regValue -= it.op
}
maxVal = max(maxVal, regValue)
registers[it.reg] = regValue
}
if (maxReg) {
// Part 1
println(registers.maxBy { (_, v) -> v })
} else {
// Part 2
println(maxVal)
}
}
main(false)
| 0 | Rust | 0 | 2 | bc1935dbbdb6e569fe2bb1ab69471ba705d14f1e | 1,949 | advent-of-code | MIT License |
aoc16/day_20/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
import kotlin.math.min
data class Range(val min: Long, val max: Long)
fun main() {
val denylist = File("input")
.readLines()
.map { Range(it.split("-")[0].toLong(), it.split("-")[1].toLong()) }
var validRanges = setOf(Range(0, 4294967295))
for (deny in denylist) {
validRanges = validRanges
.flatMap { r ->
if (deny.min <= r.min && deny.max >= r.max)
listOf(null)
else if (deny.min <= r.min && deny.max > r.min)
listOf(Range(deny.max + 1, r.max))
else if (deny.max >= r.max && deny.min < r.max)
listOf(Range(r.min, deny.min - 1))
else if (deny.min > r.min && deny.max < r.max)
listOf(Range(r.min, deny.min - 1), Range(deny.max + 1, r.max))
else
listOf(r)
}
.filterNotNull()
.toSet()
}
val first = validRanges.minByOrNull { it.min }!!.min
println("First: $first")
val second = validRanges.map { it.max - it.min + 1 }.sum()
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,160 | advent-of-code | MIT License |
src/Day01.kt | qexer | 575,383,214 | false | {"Kotlin": 16152} | /*
--- Day 1: Calorie Counting ---
Santa's reindeer typically eat regular reindeer food, but they need a lot of magical energy to deliver presents on Christmas. For that, their favorite snack is a special type of star fruit that only grows deep in the jungle. The Elves have brought you on their annual expedition to the grove where the fruit grows.
To supply enough magical energy, the expedition needs to retrieve a minimum of fifty stars by December 25th. Although the Elves assure you that the grove has plenty of fruit, you decide to grab any fruit you see along the way, just in case.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input).
The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's inventory (if any) by a blank line.
For example, suppose the Elves finish writing their items' Calories and end up with the following list:
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
This list represents the Calories of the food carried by five Elves:
The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories.
The second Elf is carrying one food item with 4000 Calories.
The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories.
The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories.
The fifth Elf is carrying one food item with 10000 Calories.
In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf).
Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?
--- Part Two ---
By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most Calories of food might eventually run out of snacks.
To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups.
In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves is 45000.
Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?
*/
fun main() {
val list = mutableListOf<Int>()
fun part1(input: List<String>): Int {
if(input.isEmpty()) return list.max()
list.add(input.takeWhile{ it.isNotBlank() }.sumOf{ it.toInt() })
return part1(input.dropWhile{ it.isNotBlank() }.dropWhile { it.isBlank() })
}
fun part2(input: List<String>): Int {
return list.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | a2e81fdfdf395e2d80c0ad31ef66b84e5e2f6829 | 3,790 | Advent-of-Code-2022 | Apache License 2.0 |
solutions/src/WordSearchTwo.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} |
//https://leetcode.com/problems/word-search-ii/
class WordSearchTwo {
private val grid: MutableMap<Pair<Int, Int>, Char> = mutableMapOf()
private val foundWords = mutableSetOf<String>()
private class CharTree(val value: Char, val children: MutableMap<Char,CharTree?> = mutableMapOf() )
fun findWords(board: Array<CharArray>, words: Array<String>): List<String> {
grid.clear()
foundWords.clear()
for (i in 0 until board.size) { // m*n
for (j in 0 until board[i].size) {
grid[Pair(i, j)] = board[i][j]
}
}
val rootTree = CharTree('#')
words.forEach { buildTree(it,rootTree) }
grid.keys.forEach { traverseTree(it, mutableSetOf(), StringBuilder(), rootTree) }
return words.filter { foundWords.contains(it) }
}
private fun buildTree(word: String, tree: CharTree) {
val wordList = word.toMutableList()
var current = tree
while (wordList.isNotEmpty()) {
val currentChar = wordList.removeAt(0)
var child = current.children[currentChar]
if (child== null) {
child = CharTree(currentChar)
current.children[currentChar] = child
}
current = child
}
}
private fun traverseTree(location: Pair<Int,Int>, found: MutableSet<Pair<Int,Int>>, sb: StringBuilder, tree: CharTree?) {
if (tree == null) {
return
}
if (tree.value == '#') {
traverseTree(location,found,sb, tree.children[grid.getValue(location)])
return
}
found.add(location)
sb.append(tree.value)
foundWords.add(sb.toString())
listOf(
Pair(location.first + 1, location.second),
Pair(location.first - 1, location.second),
Pair(location.first, location.second + 1),
Pair(location.first, location.second - 1)
)
.filter { grid.containsKey(it) && !found.contains(it)}
.forEach{
traverseTree(it, found.toMutableSet(), StringBuilder(sb), tree.children[grid.getValue(it)])
}
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 2,217 | leetcode-solutions | MIT License |
src/main/year_2016/day12/day16.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package year_2016.day12
import readInput
fun main() {
val input = readInput("main/year_2016/day12/Day12")
println(part1(input))
println(part2(input))
}
val registers = mutableMapOf(
"a" to 0,
"b" to 0,
"c" to 0,
"d" to 0,
)
fun part1(input: List<String>): Int {
var index = 0
while (index < input.size) {
val line = input[index]
when (line.substring(0, 3)) {
"cpy" -> {
val (_, x, reg) = line.split(" ")
if (x in listOf("a", "b", "c", "d"))
registers[reg] = registers[x]!!
else
registers[reg] = x.toInt()
index++
}
"inc" -> {
val (_, reg) = line.split(" ")
registers[reg] = registers[reg]!! + 1
index++
}
"dec" -> {
val (_, reg) = line.split(" ")
registers[reg] = registers[reg]!! - 1
index++
}
"jnz" -> {
val (_, x, y) = line.split(" ")
if (x.all { it.isDigit() }) {
if (x.toInt() != 0) index += y.toInt()
} else {
if (registers[x] != 0)
index += y.toInt()
else index++
}
}
}
}
return registers["a"]!!
}
fun part2(input: List<String>): Int {
registers["c"] = 1
return part1(input)
}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 1,518 | aoc-2022 | Apache License 2.0 |
src/Day06.kt | kthun | 572,871,866 | false | {"Kotlin": 17958} | fun main() {
fun firstUniqueCharSequence(chars: CharArray, sequenceLength: Int): Int {
val lastNchars = chars.take(sequenceLength).toMutableList()
chars.foldIndexed(lastNchars) { index, acc, c ->
acc.removeFirst()
acc.add(c)
if (acc.toSet().size == sequenceLength) {
return index + 1
}
acc
}
return -1
}
fun part1(input: List<String>): Int {
val chars = input[0].toCharArray()
return firstUniqueCharSequence(chars, 4)
}
fun part2(input: List<String>): Int {
val chars = input[0].toCharArray()
return firstUniqueCharSequence(chars, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
val input = readInput("Day06")
check(part1(testInput) == 11)
println(part1(input))
check(part2(testInput) == 26)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5452702e4e20ef2db3adc8112427c0229ebd1c29 | 980 | aoc-2022 | Apache License 2.0 |
src/day6/main.kt | DonaldLika | 434,183,449 | false | {"Kotlin": 11805} | package day6
import assert
import readLines
var NR_OF_DAYS = 80
fun main() {
fun part1(fishes: List<Fish>): Long {
return countTotalFish(fishes)
}
fun part2(fishes: List<Fish>): Long {
return countTotalFish(fishes, 256)
}
val testInput = readFishes("day6/test")
assert(part1(testInput) == 5934L)
assert(part2(testInput) == 26984457539)
val input = readFishes("day6/input")
val part1Result = part1(input)
val part2Result = part2(input)
println("Result of part 1= $part1Result")
println("Result of part 2= $part2Result")
}
fun countTotalFish(fishes: List<Fish>, limit: Int = NR_OF_DAYS): Long {
var finalFishes = fishes
repeat(limit) {
val newFishes = finalFishes.mapNotNull { it.step() }
finalFishes = finalFishes.plus(newFishes)
}
return finalFishes.count().toLong()
}
class Fish(var timer: Int = 8) {
override fun toString(): String = "[$timer]"
fun step(): Fish? {
if (isReadyForCreation()) {
timer = 6
return Fish(8)
}
timer--
return null
}
private fun isReadyForCreation() = timer == 0
}
private fun readFishes(name: String)= readLines(name)
.flatMap { it.split(",").map { nr -> nr.toInt() } }
.map {
Fish(it)
} | 0 | Kotlin | 0 | 0 | b288f16ee862c0a685a3f9e4db34d71b16c3e457 | 1,318 | advent-of-code-2021 | MIT License |
src/Day19.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | import kotlin.math.max
private data class Blueprint(
val id: Int,
val oreNeededOre: Int,
val clayNeededOre: Int,
val obsidianNeededOre: Int,
val obsidianNeededClay: Int,
val geodeNeededOre: Int,
val geodeNeededObsidian: Int
) {
val maxOreNeeded = listOf(oreNeededOre, clayNeededOre, obsidianNeededOre, geodeNeededOre).max()
fun possibleRobots(robots: Type, materials: Type): List<Type> {
val result = mutableListOf<Type>()
if (materials.ore >= geodeNeededOre &&
materials.obsidian >= geodeNeededObsidian) {
result.add(Type(geode = 1))
} else {
if (materials.ore >= obsidianNeededOre &&
robots.obsidian <= geodeNeededObsidian &&
materials.clay >= obsidianNeededClay
) {
result.add(Type(obsidian = 1))
}
if (robots.geode == 0 &&
robots.clay <= obsidianNeededClay &&
materials.ore >= clayNeededOre
) {
result.add(Type(clay = 1))
}
if (robots.obsidian == 0 &&
robots.ore <= maxOreNeeded &&
materials.ore >= oreNeededOre
) {
result.add(Type(ore = 1))
}
}
return result
}
fun costOfRobot(robot: Type): Type {
return Type(
ore = oreNeededOre * robot.ore + clayNeededOre * robot.clay + obsidianNeededOre * robot.obsidian + geodeNeededOre * robot.geode,
clay = obsidianNeededClay * robot.obsidian,
obsidian = geodeNeededObsidian * robot.geode,
geode = 0
)
}
}
data class Type(val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0) {
operator fun plus(other: Type): Type {
return Type(ore + other.ore, clay + other.clay, obsidian + other.obsidian, geode + other.geode)
}
operator fun minus(other: Type): Type {
return Type(ore - other.ore, clay - other.clay, obsidian - other.obsidian, geode - other.geode)
}
}
fun main() {
fun List<String>.parse(): List<Blueprint> {
val pattern = """Blueprint (?<id>\d+):
|Each ore robot costs (?<oreNeededOre>\d+) ore.
|Each clay robot costs (?<clayNeededOre>\d+) ore.
|Each obsidian robot costs (?<obsidianNeededOre>\d+) ore and (?<obsidianNeededClay>\d+) clay.
|Each geode robot costs (?<geodeNeededOre>\d+) ore and (?<geodeNeededObsidian>\d+) obsidian.""".trimMargin()
.replace("\n", "").toRegex()
return joinToString("\n").replace("\n ", " ").replace("\n\n", "\n").split("\n").map { line ->
val groups = pattern.matchEntire(line)?.groups ?: error("Cant parse")
Blueprint(
id = groups["id"]?.value?.toInt() ?: error("Cant parse"),
oreNeededOre = groups["oreNeededOre"]?.value?.toInt() ?: error("Cant parse"),
clayNeededOre = groups["clayNeededOre"]?.value?.toInt() ?: error("Cant parse"),
obsidianNeededOre = groups["obsidianNeededOre"]?.value?.toInt() ?: error("Cant parse"),
obsidianNeededClay = groups["obsidianNeededClay"]?.value?.toInt() ?: error("Cant parse"),
geodeNeededOre = groups["geodeNeededOre"]?.value?.toInt() ?: error("Cant parse"),
geodeNeededObsidian = groups["geodeNeededObsidian"]?.value?.toInt() ?: error("Cant parse"),
)
}
}
fun calcMaxGeodes(blueprint: Blueprint, maxTime: Int): Int {
fun dfs(robots: Type, materials: Type, time: Int, baned: List<Type>): Int {
if (time > maxTime) {
return materials.geode
}
var best = -Int.MAX_VALUE
val possibleRobots = blueprint.possibleRobots(robots, materials).toList()
for (builtRobot in possibleRobots) {
if (builtRobot !in baned) {
val newRobots = builtRobot + robots
val newMaterials = (materials - blueprint.costOfRobot(builtRobot)) + robots
val newBest = dfs(newRobots, newMaterials, time + 1, emptyList())
best = max(best, newBest)
}
}
best = max(best, dfs(robots, materials + robots, time + 1, possibleRobots)) // wait
return best
}
return dfs(Type(ore = 1), Type(), 1, emptyList())
}
fun part1(input: List<String>): Int {
return input.parse().map{ calcMaxGeodes(it, maxTime = 24) }
.mapIndexed { i, numberOfGeodes ->
(i + 1) * numberOfGeodes
}
.reduce { acc, i -> acc + i }
}
fun part2(input: List<String>): Int {
return input.parse().take(3).map{ calcMaxGeodes(it, maxTime = 32) }.reduce { acc, it -> acc * it }
}
val testInput = readInput("Day19_test")
val input = readInput("Day19")
assert(part1(testInput), 33)
println(part1(input))
assert(part2(testInput), 62 * 56)
println(part2(input))
}
// Time: 01:40 | 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 5,112 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day22/Day22.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2020.day22
import eu.janvdb.aocutil.kotlin.readGroupedLines
fun main() {
val decks = readGroupedLines(2020, "input22.txt").map(::parseDeck)
val game = Game(decks[0], decks[1])
part1(game)
part2(game)
}
fun part1(game: Game) {
val winner = playWithRules1(game)
println(winner.deck.score().toString())
}
fun part2(game: Game) {
val winner = playWithRules2(game)
println(winner.deck.score().toString())
}
fun parseDeck(lines: List<String>): Deck {
val cards = lines.drop(1).map(String::toInt).toMutableList()
return Deck(cards)
}
fun playWithRules1(game: Game): Winner {
var currentGame = game
while(true) {
val deck0 = currentGame.deck0
val deck1 = currentGame.deck1
if (deck1.isEmpty()) return Winner(0, deck0)
if (deck0.isEmpty()) return Winner(1, deck1)
val card0 = deck0.takeOne()
val card1 = deck1.takeOne()
currentGame = if (card0 > card1) {
Game(deck0.replaceFirst(card0, card1), deck1.replaceFirst())
} else {
Game(deck0.replaceFirst(), deck1.replaceFirst(card1, card0))
}
}
}
fun playWithRules2(game: Game, indent: String = ""): Winner {
val gamesPlayed = mutableSetOf<Game>()
var currentGame = game
var round = 1
while(true) {
val deck0 = currentGame.deck0
val deck1 = currentGame.deck1
println("$indent($round) $currentGame")
round++
if (gamesPlayed.contains(currentGame)) {
println("$indent\tAlready played -> Winner 0")
return Winner(0, deck0)
}
gamesPlayed.add(currentGame)
if (currentGame.deck1.isEmpty()) return Winner(0, deck0)
if (deck0.isEmpty()) return Winner(1, currentGame.deck1)
val card0 = deck0.takeOne()
val card1 = currentGame.deck1.takeOne()
val winner = if (deck0.size - 1 >= card0 && currentGame.deck1.size - 1 >= card1) {
val newDeck0 = deck0.subDeck(1, card0)
val newDeck1 = deck1.subDeck(1, card1)
val newGame = Game(newDeck0, newDeck1)
playWithRules2(newGame, indent + "\t").player
} else {
if (card0 > card1) 0 else 1
}
println("$indent\tWinner $winner")
currentGame = if (winner == 0) {
Game(deck0.replaceFirst(card0, card1), deck1.replaceFirst())
} else {
Game(deck0.replaceFirst(), deck1.replaceFirst(card1, card0))
}
}
}
data class Deck(val cards: List<Int>) {
val size = cards.size
fun isEmpty() = cards.isEmpty()
fun takeOne(): Int = cards[0]
fun replaceFirst(vararg cardsToAdd: Int): Deck {
val newCards = cards.toMutableList()
newCards.removeAt(0)
cardsToAdd.forEach(newCards::add)
return Deck(newCards)
}
fun subDeck(start: Int, numberOfCards: Int): Deck = Deck(cards.subList(start, start + numberOfCards))
fun score(): Int {
return (cards.indices).map { (cards.size - it) * cards[it] }.sum()
}
}
data class Game(val deck0: Deck, val deck1: Deck)
data class Winner(val player: Int, val deck: Deck) | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,807 | advent-of-code | Apache License 2.0 |
2021/src/day10/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day10
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
val matching = mapOf(
'(' to ')',
'[' to ']',
'{' to '}',
'<' to '>',
)
fun part1(lines: Input): Int {
val points = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137,
)
return lines.sumOf {
val stack = mutableListOf<Char>()
for (elem in it) {
if (matching.containsKey(elem)) {
stack.add(elem)
} else {
if (matching[stack.last()] != elem) {
return@sumOf points[elem]!!
} else {
stack.removeAt(stack.lastIndex)
}
}
}
0
}
}
fun part2(lines: Input): Long {
val points = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
return lines.map { line ->
val stack = mutableListOf<Char>()
for (elem in line) {
if (matching.containsKey(elem)) {
stack.add(elem)
} else {
if (matching[stack.last()] != elem) {
return@map 0
} else {
stack.removeAt(stack.lastIndex)
}
}
}
stack.reversed().map { matching[it] }.fold(0L) { acc, c -> acc * 5 + points[c]!! }
}.filter { it != 0L }.sorted().let {
it[it.size / 2]
}
}
check(part1(readInput("test-input.txt")) == 26397)
check(part2(readInput("test-input.txt")) == 288957L)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day10/$s")).readLines()
}
private typealias Input = List<String> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 1,676 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2022/d16/Day16.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2022.d16
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
data class Valve(val name: String, val flowRate: Int, val adjacentValves: List<String>)
fun parseLine(line: String): Valve {
val parts = line.split(" ")
val flowRate = parts[4].filter { it in '0'..'9' }.toInt()
val adjacentValves = parts.subList(9, parts.size).map { it.take(2) }
return Valve(parts[1], flowRate, adjacentValves)
}
const val START = "AA"
class Solver(valves: List<Valve>, private val time: Int) {
private val nameToValve = valves.associateBy { it.name }
private val nameToNumber = mutableMapOf<String, Int>()
private val numberToValve: Array<Valve>
private val distanceFromStart: IntArray
private val distances: Array<IntArray>
// The keys are bitmaps representing which valves are open.
// E.g. 0...01101 means that valves 0, 2, 3 are open, others closed.
// The value is the maximum amount of flow that can be released via some path
// that eventually opens this set of valves, in some order.
// Assumes that at most 32 valves can be opened!
private val maxFlows = mutableMapOf<Int, Int>()
init {
// number the valves with nonzero flow rate
valves.forEach { valve ->
if (valve.flowRate > 0) {
nameToNumber[valve.name] = nameToNumber.size
}
}
numberToValve = Array(nameToNumber.size) { Valve("dummy", 0, emptyList()) }.apply {
nameToNumber.forEach { (name, num) -> this[num] = nameToValve[name]!! }
}
// initialize distances
distanceFromStart = computeDistances(nameToValve[START]!!)
distances = Array(nameToNumber.size) {
computeDistances(numberToValve[it])
}
computeMaxFlows()
}
private fun computeDistances(start: Valve): IntArray {
val ret = IntArray(nameToNumber.size) { -1 }
val queue = ArrayDeque(listOf(start to 0))
val visited = mutableSetOf<String>()
while (queue.isNotEmpty()) {
val (valve, dist) = queue.removeFirst()
visited.add(valve.name)
nameToNumber[valve.name]?.let { n ->
ret[n] =
if (ret[n] == -1) dist
else minOf(ret[n], dist)
}
valve.adjacentValves
.filterNot { it in visited }
.forEach {
queue.add(nameToValve[it]!! to (dist + 1))
}
}
return ret
}
private fun totalFlowRate(openValves: Int): Int =
numberToValve.mapIndexed { n, valve ->
if (openValves and (1 shl n) != 0) valve.flowRate
else 0
}.sum()
private fun computeMaxFlows() {
// openValves is a bitmap, same as maxFlows' keys
data class State(val position: Int, val openValves: Int, val timeRemaining: Int, val flowSoFar: Int) {
val openValvesList = distances.indices.filter { openValves and (1 shl it) != 0 }
override fun toString() = "State(position=$position, openValves=$openValvesList, timeRemaining=$timeRemaining, flowSoFar=$flowSoFar)"
}
fun State.goTo(newPosition: Int): State {
val actionTime = distances[position][newPosition] + 1
val newOpenValves = openValves or (1 shl newPosition)
return State(newPosition, newOpenValves,
timeRemaining - actionTime,
flowSoFar + totalFlowRate(openValves) * actionTime)
}
val queue = distanceFromStart
.mapIndexed { n, dist ->
State(n, 1 shl n, time - (dist + 1), 0).takeIf { it.timeRemaining >= 0 }
}
.filterNotNull()
.let(::ArrayDeque)
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
maxFlows[curr.openValves] = maxOf(
maxFlows[curr.openValves] ?: 0,
curr.flowSoFar + totalFlowRate(curr.openValves) * curr.timeRemaining
)
distances.indices
.filter { curr.openValves and (1 shl it) == 0 } // do not go to an open valve
.filter { distances[curr.position][it] < curr.timeRemaining - 1 } // do not go to a valve we don't have time to open
.forEach { newPosition ->
queue.add(curr.goTo(newPosition))
}
}
}
fun findMaxFlow(partOne: Boolean): Int =
if (partOne) maxFlows.values.maxOrNull()!!
else maxFlows.maxOf { (openValves, flow) ->
flow + (maxFlows.filterKeys { it and openValves == 0 }.values.maxOrNull() ?: 0)
}
}
fun main() = timed {
val valves = (DATAPATH / "2022/day16.txt").useLines { lines ->
lines.toList()
.map(::parseLine)
}
Solver(valves, 30)
.also { println("Part one: ${it.findMaxFlow(true)}") }
Solver(valves, 26)
.also { println("Part two: ${it.findMaxFlow(false)}") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 5,111 | advent-of-code | MIT License |
2022/src/main/kotlin/Day23.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import Day23.Direction.*
import java.util.*
object Day23 {
fun part1(input: String): Int {
var elves = parseElves(input)
repeat(10) {
elves = round(elves, Direction.values()[it % 4])
}
val minX = elves.minOf { it.x }
val maxX = elves.maxOf { it.x }
val minY = elves.minOf { it.y }
val maxY = elves.maxOf { it.y }
return (maxX - minX + 1) * (maxY - minY + 1) - elves.size
}
fun part2(input: String): Int {
var elves = parseElves(input)
var round = 0
while (true) {
val nextElves = round(elves, Direction.values()[round % 4])
if (elves == nextElves) {
return round + 1
}
elves = nextElves
round++
}
}
private fun round(elves: Set<Point>, startingDirection: Direction): Set<Point> {
val proposedMoves = mutableMapOf<Point, MutableSet<Point>>()
val directionOrder = directionOrder(startingDirection)
val nextPositions = mutableSetOf<Point>()
// Propose moves
for (elf in elves) {
// If there's no adjacent elves, don't move
val adjacentPoints = adjacentPoints(elf)
if (adjacentPoints.none { it in elves }) {
nextPositions.add(elf)
continue
}
var foundMove = false
for (direction in directionOrder) {
val check = checkDirection(elf, direction)
if (check.none { it in elves }) {
val move = moveDirection(elf, direction)
proposedMoves.getOrPut(move) { mutableSetOf() }.add(elf)
foundMove = true
break
}
}
// No directions to move - just stay put
if (!foundMove) {
nextPositions.add(elf)
}
}
// Execute moves
for ((proposedMove, fromElves) in proposedMoves.entries) {
if (fromElves.size > 1) {
nextPositions.addAll(fromElves)
} else {
nextPositions.add(proposedMove)
}
}
return nextPositions
}
private fun directionOrder(startingDirection: Direction): List<Direction> {
val directions = Direction.values().toMutableList()
Collections.rotate(directions, -startingDirection.ordinal)
return directions
}
private fun adjacentPoints(point: Point): List<Point> {
return (-1..1).flatMap { xMod ->
(-1..1).map { yMod ->
Point(point.x + xMod, point.y + yMod)
}
}.filter { it != point }
}
private fun checkDirection(point: Point, direction: Direction): Set<Point> {
val (x, y) = point
return when (direction) {
NORTH -> setOf(Point(x - 1, y - 1), Point(x, y - 1), Point(x + 1, y - 1))
SOUTH -> setOf(Point(x - 1, y + 1), Point(x, y + 1), Point(x + 1, y + 1))
WEST -> setOf(Point(x - 1, y - 1), Point(x - 1, y), Point(x - 1, y + 1))
EAST -> setOf(Point(x + 1, y - 1), Point(x + 1, y), Point(x + 1, y + 1))
}
}
private fun moveDirection(point: Point, direction: Direction): Point {
val (x, y) = point
return when (direction) {
NORTH -> Point(x, y - 1)
SOUTH -> Point(x, y + 1)
WEST -> Point(x - 1, y)
EAST -> Point(x + 1, y)
}
}
private enum class Direction { NORTH, SOUTH, WEST, EAST }
private data class Point(val x: Int, val y: Int)
private fun parseElves(input: String): Set<Point> {
val elves = mutableSetOf<Point>()
input.splitNewlines().forEachIndexed { y, s ->
s.forEachIndexed { x, c ->
if (c == '#') {
elves.add(Point(x, y))
}
}
}
return elves
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 3,473 | advent-of-code | MIT License |
src/main/kotlin/championofgoats/advent/2019/day12/day12.kt | ChampionOfGoats | 225,446,764 | false | null | package championofgoats.advent.twentynineteen.day12
import championofgoats.advent.Problem
import championofgoats.advent.utils.MutablePair
import championofgoats.advent.utils.Vector3
import championofgoats.advent.utils.logging.Logger
object Day12 : Problem {
override fun solve(inputDir: String, outputDir: String, log: Logger) {
// The moons to simulate, as a zero-index list of pairs of their position and current velocity
var moons = listOf(
MutablePair(Vector3(-6, -5, -8), Vector3.zero), // Io
MutablePair(Vector3(0, -3, -13), Vector3.zero), // Europa
MutablePair(Vector3(-15, 10, -11), Vector3.zero), // Ganymede
MutablePair(Vector3(-3, -8, 3), Vector3.zero) // Callisto
)
// The moons to simulate, as a zero-index list of pairs of moons to apply gravity to
var pairs = listOf(
Pair(0, 1), // Io -> Europa
Pair(0, 2), // Io -> Ganymede
Pair(0, 3), // Io -> Callisto
Pair(1, 2), // Europa -> Ganymede
Pair(1, 3), // Europa -> Callisto
Pair(2, 3) // Ganymede -> Callisto
)
fun determineGravitationalPull(a: Vector3, b: Vector3) : Vector3 {
// For each axis, if the position of a < b then +1 else -1
return Vector3(
a.x.compareTo(b.x),
a.y.compareTo(b.y),
a.z.compareTo(b.z))
}
fun applyGravityToVelocity(pair: Pair<Int, Int>) {
// determine the pull for each moon
val gravity = determineGravitationalPull(moons[pair.first].first, moons[pair.second].first)
// apply pull to velocity
moons[pair.first].second = moons[pair.first].second - gravity
moons[pair.second].second = moons[pair.second].second + gravity
}
fun applyVelocityToPosition(moon: Int) {
// new position of the moon is the position + the velocity
moons[moon].first = moons[moon].first + moons[moon].second
}
fun applyGravity() {
for (p in pairs) {
applyGravityToVelocity(p)
}
for (p in 1..moons.size) {
applyVelocityToPosition(p - 1)
}
}
// do 1000 time steps
(1..1000).forEach { applyGravity() }
// then find the sum of the total energy
var totalEnergyInSystem = 0
moons.forEach { m ->
var a = m.first.absSum()
var b = m.second.absSum()
totalEnergyInSystem += a * b
}
// Initial answer is 768975672, which was too high.
log.Solution("DAY12p1 ans = %d".format(totalEnergyInSystem))
}
}
| 0 | Kotlin | 0 | 0 | 4f69de1579f40928c1278c3cea4e23e0c0e3b742 | 2,776 | advent-of-code | MIT License |
src/main/kotlin/g0001_0100/s0064_minimum_path_sum/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0064_minimum_path_sum
// #Medium #Top_100_Liked_Questions #Array #Dynamic_Programming #Matrix
// #Dynamic_Programming_I_Day_16 #Udemy_Dynamic_Programming #Big_O_Time_O(m*n)_Space_O(m*n)
// #2023_07_10_Time_164_ms_(100.00%)_Space_37.3_MB_(84.71%)
class Solution {
fun minPathSum(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
val dp = Array(m) { Array(n) { 0 } }
for (i in 0 until m) {
for (j in 0 until n) {
if (i == 0 && j == 0) {
dp[i][j] = grid[i][j]
} else if (i == 0) {
dp[i][j] = dp[i][j - 1] + grid[i][j]
} else if (j == 0) {
dp[i][j] = dp[i - 1][j] + grid[i][j]
} else {
dp[i][j] = minOf(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
}
}
}
return dp[m - 1][n - 1]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 955 | LeetCode-in-Kotlin | MIT License |
Zumkeller_numbers/Kotlin/src/ZumkellerNumbers.kt | ncoe | 108,064,933 | false | {"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409} | import java.util.ArrayList
import kotlin.math.sqrt
object ZumkellerNumbers {
@JvmStatic
fun main(args: Array<String>) {
var n = 1
println("First 220 Zumkeller numbers:")
run {
var count = 1
while (count <= 220) {
if (isZumkeller(n)) {
print("%3d ".format(n))
if (count % 20 == 0) {
println()
}
count++
}
n += 1
}
}
n = 1
println("\nFirst 40 odd Zumkeller numbers:")
run {
var count = 1
while (count <= 40) {
if (isZumkeller(n)) {
print("%6d".format(n))
if (count % 10 == 0) {
println()
}
count++
}
n += 2
}
}
n = 1
println("\nFirst 40 odd Zumkeller numbers that do not end in a 5:")
var count = 1
while (count <= 40) {
if (n % 5 != 0 && isZumkeller(n)) {
print("%8d".format(n))
if (count % 10 == 0) {
println()
}
count++
}
n += 2
}
}
private fun isZumkeller(n: Int): Boolean { // numbers congruent to 6 or 12 modulo 18 are Zumkeller numbers
if (n % 18 == 6 || n % 18 == 12) {
return true
}
val divisors = getDivisors(n)
val divisorSum = divisors.stream().mapToInt { i: Int? -> i!! }.sum()
// divisor sum cannot be odd
if (divisorSum % 2 == 1) {
return false
}
// numbers where n is odd and the abundance is even are Zumkeller numbers
val abundance = divisorSum - 2 * n
if (n % 2 == 1 && abundance > 0 && abundance % 2 == 0) {
return true
}
divisors.sort()
val j = divisors.size - 1
val sum = divisorSum / 2
// Largest divisor larger than sum - then cannot partition and not Zumkeller number
return if (divisors[j] > sum) false else canPartition(j, divisors, sum, IntArray(2))
}
private fun canPartition(j: Int, divisors: List<Int>, sum: Int, buckets: IntArray): Boolean {
if (j < 0) {
return true
}
for (i in 0..1) {
if (buckets[i] + divisors[j] <= sum) {
buckets[i] += divisors[j]
if (canPartition(j - 1, divisors, sum, buckets)) {
return true
}
buckets[i] -= divisors[j]
}
if (buckets[i] == 0) {
break
}
}
return false
}
private fun getDivisors(number: Int): MutableList<Int> {
val divisors: MutableList<Int> = ArrayList()
val sqrt = sqrt(number.toDouble()).toLong()
for (i in 1..sqrt) {
if (number % i == 0L) {
divisors.add(i.toInt())
val div = (number / i).toInt()
if (div.toLong() != i) {
divisors.add(div)
}
}
}
return divisors
}
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 3,296 | rosetta | MIT License |
src/main/kotlin/leetcode/problem0085/MaximalRectangle.kt | ayukatawago | 456,312,186 | false | {"Kotlin": 266300, "Python": 1842} | package leetcode.problem0085
import java.util.Stack
import kotlin.math.max
class MaximalRectangle {
fun maximalRectangle(matrix: Array<CharArray>): Int {
val heights = Array(matrix.size) { IntArray(matrix[0].size) { 0 } }
matrix.forEachIndexed { row, chars ->
chars.indices.forEach { column ->
heights[row][column] = when (matrix[row][column]) {
'1' -> if (row == 0) 1 else heights[row - 1][column] + 1
'0' -> 0
else -> error("Invalid value")
}
}
}
var maxSize = 0
heights.forEach {
maxSize = max(maxSize, largestRectangleArea(it))
}
return maxSize
}
private fun largestRectangleArea(heights: IntArray): Int {
val indexStack = Stack<Int>()
var maxArea = 0
heights.forEachIndexed { index, i ->
while (indexStack.isNotEmpty() && i < heights[indexStack.peek()]) {
val currentIndex = indexStack.pop()
val nextIndex = if (indexStack.isEmpty()) 0 else indexStack.peek() + 1
val area = heights[currentIndex] * (index - nextIndex)
maxArea = max(maxArea, area)
}
indexStack.push(index)
}
while (indexStack.isNotEmpty()) {
val currentIndex = indexStack.pop()
val nextIndex = if (indexStack.isEmpty()) 0 else indexStack.peek() + 1
val area = heights[currentIndex] * (heights.size - nextIndex)
maxArea = max(maxArea, area)
}
return maxArea
}
}
| 0 | Kotlin | 0 | 0 | f9602f2560a6c9102728ccbc5c1ff8fa421341b8 | 1,647 | leetcode-kotlin | MIT License |
src/main/kotlin/day10/KnotHasher.kt | Jessevanbekkum | 112,612,571 | false | null | package day10
fun hash64(input: String): String {
val length = convert(input);
return hex(dense(hash(length, 64)));
}
fun hex(input: List<Int>): String {
return input.map { i -> hexChar(i) }.joinToString("")
}
fun hexChar(i: Int): String {
val c = java.lang.Integer.toHexString(i)
if (i < 16) {
return "0" + c
}
return c;
}
fun dense(l: List<Int>): List<Int> {
if (l.isEmpty()) {
return emptyList()
} else {
return xor(l.take(16)) + dense(l.subList(16, l.size))
}
}
fun xor(l: List<Int>): List<Int> {
return listOf(l.fold(0, { total, next -> total xor next }))
}
fun convert(s: String): List<Int> {
return s.toCharArray().map { c -> c.toInt() } + listOf<Int>(17, 31, 73, 47, 23)
}
fun hash(input: List<Int>, repeat: Int): List<Int> {
var p = 0
var skip = 0
val list = mutableListOf<Int>()
(0..255).forEach {
list.add(it)
}
(1..repeat).forEach {
input.forEach {
val length = it
val end = (p + length) % list.size
val p2: List<Int>
if (end <= p) {
p2 = list.subList(p, list.size) + list.subList(0, end)
} else {
p2 = list.subList(p, p + length)
}
val inv = p2.reversed()
var c = 0
(p..(p + length - 1)).forEach {
val nc = inv[c]
list[it % list.size] = nc
c++
}
p = (p + it + skip) % list.size
skip++
}
}
return list
}
| 0 | Kotlin | 0 | 0 | 1340efd354c61cd070c621cdf1eadecfc23a7cc5 | 1,585 | aoc-2017 | Apache License 2.0 |
src/main/kotlin/com/vaclavbohac/advent2023/day1/Trebuchet.kt | vaclavbohac | 725,991,261 | false | {"Kotlin": 15155} | package com.vaclavbohac.advent2023.day1
class Trebuchet(private val lines: List<String>) {
fun sumCalibratedValues(): Int =
lines.fold(0) { sum, line -> sum + (line.getFirstDigit() * 10 + line.reversed().getFirstDigit()) }
fun sumCalibratedValuesAfterInterpolation(): Int =
lines.fold(0) { sum, line -> sum + (line.getFirstInterpolatedNumber(INTERPOLATION_TABLE) * 10 + line.getLastInterpolatedNumber(INTERPOLATION_TABLE)) }
companion object {
val INTERPOLATION_TABLE = 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)
}
}
private fun String.getFirstDigit(): Int = this.first { c -> c.isDigit() }.digitToInt()
private fun String.getFirstInterpolatedNumber(numbers: Map<String, Int>): Int {
this.forEachIndexed { i, c ->
if (c.isDigit()) {
return c.digitToInt()
}
for (number in numbers) {
if (this.startsWith(number.key, i)) {
return number.value
}
}
}
return -1
}
private fun String.getLastInterpolatedNumber(numbers: Map<String, Int>): Int =
this.reversed().getFirstInterpolatedNumber(numbers.mapKeys { it.key.reversed() } )
| 0 | Kotlin | 0 | 0 | daa1feb960c4e3d26c3c75842afbd414ecc2f008 | 1,249 | advent-of-code-2023 | MIT License |
src/main/kotlin/com/leetcode/monthly_challenges/2021/april/ones_and_zeroes/Main.kt | frikit | 254,842,734 | false | null | package com.leetcode.monthly_challenges.`2021`.april.ones_and_zeroes
import kotlin.math.max
fun main() {
println("Test case 1:")
println(Solution().findMaxForm(arrayOf("10", "0001", "111001", "1", "0"), 5, 3)) //4
println()
println("Test case 2:")
println(Solution().findMaxForm(arrayOf("10", "0", "1"), 1, 1)) //2
println()
println("Test case 3:")
println(Solution().findMaxForm(arrayOf("10", "0001", "111001", "1", "0"), 4, 3)) //3
println()
}
class Solution {
fun findMaxForm(strs: Array<String>?, m: Int, n: Int): Int {
if (strs == null || m < 0 || n < 0) return 0
val dp = Array(m + 1) { IntArray(n + 1) }
for (str in strs) {
val ones = str.chars().filter { num: Int -> num == Integer.parseInt("1") }.count().toInt()
val zeroes = str.length - ones
for (i in m downTo zeroes) {
for (j in n downTo ones) {
println(dp[i].contentToString())
dp[i][j] = max(dp[i][j], dp[i - zeroes][j - ones] + 1)
}
}
}
return dp[m][n]
}
}
| 0 | Kotlin | 0 | 0 | dda68313ba468163386239ab07f4d993f80783c7 | 1,131 | leet-code-problems | Apache License 2.0 |
src/chapter1/problem8/solution1.kts | neelkamath | 395,940,983 | false | null | /*
Question:
Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
Solution:
Modifying in-place.
*/
val matrix1 = arrayOf(
arrayOf(0, 1, 2, 3, 4),
arrayOf(5, 6, 7, 8, 9),
arrayOf(10, 11, 12, 0, 14),
arrayOf(15, 16, 17, 18, 19),
arrayOf(20, 21, 22, 23, 0),
)
val matrix2 = arrayOf(
arrayOf(1, 2, 3, 4, 5),
arrayOf(6, 7, 0, 9, 10),
arrayOf(11, 12, 13, 0, 15),
arrayOf(16, 17, 18, 19, 20)
)
setOf(matrix1, matrix2).forEachIndexed { index, matrix ->
println("Matrix ${index + 1}\nOriginal:")
matrix.display()
zeroMatrix(matrix)
println("Modified:")
matrix.display()
}
typealias Matrix = Array<Array<Int>>
fun zeroMatrix(matrix: Matrix) {
val hasZeroInFirstRow = 0 in matrix[0]
val hasZeroInFirstCol = matrix.any { it[0] == 0 }
for (rowIndex in 1 until matrix.size)
for (colIndex in 1 until matrix[0].size)
if (matrix[rowIndex][colIndex] == 0) {
matrix[0][colIndex] = 0
matrix[rowIndex][0] = 0
}
for (rowIndex in 1 until matrix.size)
for (colIndex in 1 until matrix[0].size)
if (matrix[rowIndex][0] == 0 || matrix[0][colIndex] == 0) matrix[rowIndex][colIndex] = 0
if (hasZeroInFirstRow) matrix[0] = Array(matrix[0].size) { 0 }
if (hasZeroInFirstCol) matrix.forEach { it[0] = 0 }
}
fun Matrix.display(): Unit = forEach { println(it.contentToString()) }
| 0 | Kotlin | 0 | 0 | 4421a061e5bf032368b3f7a4cee924e65b43f690 | 1,482 | ctci-practice | MIT License |
src/Day01.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} | fun getList(input: List<String>): HashMap<Int, Int> {
var idx = 0
var sum = 0
val sums = HashMap<Int, Int>()
input.map { it.trim() }.forEach {
if (it.isNotEmpty()) {
sum += it.toInt()
} else {
sums[idx++] = sum
sum = 0
}
}
return sums
}
fun part1(input: List<String>): Int = getList(input).values.sortedDescending()[0]
fun part2(input: List<String>): Int = getList(input).values.sortedDescending().subList(0, 3).sum()
fun main() {
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
measureTimeMillisPrint {
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
}
| 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 736 | aoc-22-kotlin | Apache License 2.0 |
src/main/kotlin/dev/tasso/adventofcode/_2021/day11/Day11.kt | AndrewTasso | 433,656,563 | false | {"Kotlin": 75030} | package dev.tasso.adventofcode._2021.day11
import dev.tasso.adventofcode.Solution
class Day11 : Solution<Int> {
override fun part1(input: List<String>): Int {
val energyMap = input.map{ row -> row.toCharArray().map { it.digitToInt() }.toTypedArray() }.toTypedArray()
var numFlashes = 0
(1..100).forEach { _ ->
val alreadyFlashed : MutableSet<Pair<Int, Int>> = mutableSetOf()
energyMap.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, _ ->
increaseEnergyLevel(energyMap, rowIndex, colIndex, alreadyFlashed)
}
}
energyMap.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, _ ->
if(energyMap[rowIndex][colIndex] > 9 ) {
energyMap[rowIndex][colIndex] = 0
}
}
}
numFlashes += alreadyFlashed.size
}
return numFlashes
}
override fun part2(input: List<String>): Int {
val energyMap = input.map{ row -> row.toCharArray().map { it.digitToInt() }.toTypedArray() }.toTypedArray()
var firstSynchronized = 0
for(step in 1..Int.MAX_VALUE) {
val alreadyFlashed : MutableSet<Pair<Int, Int>> = mutableSetOf()
energyMap.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, _ ->
increaseEnergyLevel(energyMap, rowIndex, colIndex, alreadyFlashed)
}
}
energyMap.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, _ ->
if(energyMap[rowIndex][colIndex] > 9 ) {
energyMap[rowIndex][colIndex] = 0
}
}
}
if (energyMap.all { row -> row.all { energy -> energy == 0 } }) {
firstSynchronized = step
break
}
}
return firstSynchronized
}
}
fun increaseEnergyLevel(energyMap: Array<Array<Int>>, rowIndex: Int, colIndex: Int, alreadyFlashed : MutableSet<Pair<Int, Int>> = mutableSetOf()) {
energyMap[rowIndex][colIndex] += 1
if(!alreadyFlashed.contains(Pair(rowIndex, colIndex))) {
if(energyMap[rowIndex][colIndex] > 9 ) {
alreadyFlashed.add(Pair(rowIndex, colIndex))
val adjacentCoords = getAdjacentCoordinates(energyMap, rowIndex, colIndex)
adjacentCoords.forEach { adjacentCoord ->
if(!alreadyFlashed.contains(adjacentCoord)) {
increaseEnergyLevel(energyMap, adjacentCoord.first, adjacentCoord.second, alreadyFlashed )
}
}
}
}
}
fun getAdjacentCoordinates(heightMap : Array<Array<Int>>, rowIndex : Int, colIndex : Int): List<Pair<Int,Int>> {
return listOfNotNull(
//Northwest
if(rowIndex > 0 && colIndex > 0) Pair(rowIndex - 1,colIndex - 1) else null,
//North
if(rowIndex > 0) Pair(rowIndex-1,colIndex) else null,
//Northeast
if(rowIndex > 0 && colIndex < heightMap[0].size-1 ) Pair(rowIndex - 1,colIndex + 1) else null,
//West
if(colIndex > 0) Pair(rowIndex,colIndex-1) else null,
//East
if(colIndex < heightMap[0].size-1) Pair(rowIndex, colIndex+1) else null,
//Southwest
if(rowIndex < heightMap.size-1 && colIndex > 0 ) Pair(rowIndex + 1,colIndex - 1) else null,
//South
if(rowIndex < heightMap.size-1) Pair(rowIndex + 1,colIndex) else null,
//Southeast
if(rowIndex < heightMap.size-1 && colIndex < heightMap[0].size-1 ) Pair(rowIndex + 1,colIndex + 1) else null
)
} | 0 | Kotlin | 0 | 0 | daee918ba3df94dc2a3d6dd55a69366363b4d46c | 3,781 | advent-of-code | MIT License |
src/main/kotlin/days/Day5.kt | jgrgt | 575,475,683 | false | {"Kotlin": 94368} | package days
class Day5 : Day(5) {
override fun partOne(): Any {
val stackInput = inputList.subList(0, 8)
check(stackInput[7].startsWith("[")) { "probably wrong stack" }
val game = Day5Game.fromStackInput(stackInput)
inputList.drop(10).forEach { line ->
val move = Move.parse(line)
game.execute(move)
}
return game.topCrates().joinToString("")
}
override fun partTwo(): Any {
val stackInput = inputList.subList(0, 8)
check(stackInput[7].startsWith("[")) { "probably wrong stack" }
val game = Day5Game.fromStackInput(stackInput)
inputList.drop(10).forEach { line ->
val move = Move.parse(line)
game.execute2(move)
}
return game.topCrates().joinToString("")
}
}
typealias Stack = MutableList<Char>
data class Move(val amount: Int, val fromIndex: Int, val toIndex: Int) {
companion object {
fun parse(s: String): Move {
// move 3 from 5 to 2
val parts = s.split(" ")
val amount = parts[1].toInt()
val fromIndex = parts[3].toInt()
val toIndex = parts[5].toInt()
return Move(amount, fromIndex, toIndex)
}
}
}
class Day5Game(private val stacks: List<Stack>) {
fun execute(move: Move) {
val fromStack = stacks[move.fromIndex - 1]
val toStack = stacks[move.toIndex - 1]
repeat(move.amount) {
val v = fromStack.removeLast()
toStack.add(v)
}
}
fun execute2(move: Move) {
val fromStack = stacks[move.fromIndex - 1]
val toStack = stacks[move.toIndex - 1]
val moved = mutableListOf<Char>()
repeat(move.amount) {
val v = fromStack.removeLast()
moved.add(v)
}
toStack.addAll(moved.reversed())
}
fun topCrates(): List<Char> {
return stacks.map { it.last() }
}
companion object {
fun fromStackInput(lines: List<String>): Day5Game {
// letters are on indexes:
// [B] [L] [Q] [W] [S] [L] [J] [W] [Z]
// 1 5 9 13 17 21 25 29 34
val stacks: List<Stack> = listOf(
mutableListOf(),
mutableListOf(),
mutableListOf(),
mutableListOf(),
mutableListOf(),
mutableListOf(),
mutableListOf(),
mutableListOf(),
mutableListOf(),
)
val indexes = listOf(1, 5, 9, 13, 17, 21, 25, 29, 33)
lines.forEach { line ->
indexes.forEachIndexed { stackIndex, charIndex ->
val c = line[charIndex]
if (c != ' ') {
stacks[stackIndex].add(0, c)
}
}
}
return Day5Game(stacks)
}
}
}
| 0 | Kotlin | 0 | 0 | 5174262b5a9fc0ee4c1da9f8fca6fb86860188f4 | 2,961 | aoc2022 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day20.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.getText
import kotlin.math.abs
fun main() {
val input = getText("day20.txt")
println(day20A(input))
println(day20B(input))
}
fun day20A(input: String) = mix(input)
fun day20B(input: String) = mix(input, 10, 811589153)
private fun mix(input: String, times: Int = 1, decryptKey: Long = 1L): Long {
val numbers = input.lines().mapIndexed { index, s ->
Node(s.toInt() * decryptKey, index)
}.toMutableList()
repeat(times) { _ ->
repeat(numbers.size) { index ->
val from = numbers.indexOfFirst { it.originalIndex == index }
val moves = numbers.first { it.originalIndex == index }.value
if(moves != 0L) {
var to = from + moves
if (abs(to) >= numbers.size) {
to %= numbers.size - 1
}
if (to < 0) {
to += numbers.size - 1
}
if(from < to) {
numbers.add(to.toInt(), numbers.removeAt(from))
}else if(from > to) {
numbers.add(to.toInt(), numbers[from])
numbers.removeAt(from+1)
}
}
}
}
val zeroAt = numbers.indexOfFirst { it.value == 0L }
return numbers[(zeroAt + 1000) % numbers.size].value +
numbers[(zeroAt + 2000) % numbers.size].value +
numbers[(zeroAt + 3000) % numbers.size].value
}
private class Node(val value: Long, val originalIndex: Int)
| 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 1,516 | AdventOfCode2022 | MIT License |
leetcode-75-kotlin/src/main/kotlin/StringCompression.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* Given an array of characters chars, compress it using the following algorithm:
*
* Begin with an empty string s. For each group of consecutive repeating characters in chars:
*
* If the group's length is 1, append the character to s.
* Otherwise, append the character followed by the group's length.
* The compressed string s should not be returned separately, but instead, be stored in the input character array chars.
* Note that group lengths that are 10 or longer will be split into multiple characters in chars.
*
* After you are done modifying the input array, return the new length of the array.
*
* You must write an algorithm that uses only constant extra space.
*
*
*
* Example 1:
*
* Input: chars = ["a","a","b","b","c","c","c"]
* Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
* Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
* Example 2:
*
* Input: chars = ["a"]
* Output: Return 1, and the first character of the input array should be: ["a"]
* Explanation: The only group is "a", which remains uncompressed since it's a single character.
* Example 3:
*
* Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
* Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
* Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
*
*
* Constraints:
*
* 1 <= chars.length <= 2000
* chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.
* @see <a href="https://leetcode.com/problems/string-compression/">LeetCode</a>
*/
fun compress(chars: CharArray): Int {
var answerIndex = 0
var currentIndex = 0
while (currentIndex < chars.size) {
val currentCharacter = chars[currentIndex]
var count = 0
while (currentIndex < chars.size && chars[currentIndex] == currentCharacter) {
currentIndex++
count++
}
chars[answerIndex++] = currentCharacter
if (count > 1) {
count.toString().forEach { digit ->
chars[answerIndex++] = digit
}
}
}
return answerIndex
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 2,228 | leetcode-75 | Apache License 2.0 |
src/Day09.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | import kotlin.math.abs
import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
val ropeSize = 2;
var set = mutableSetOf<Pair<Int, Int>>();
var dx = listOf<Int>(1, 0, -1, 0);
var dy = listOf<Int>(0, -1, 0, 1);
var dir = mutableMapOf<Char, Int>();
dir['R'] = 0;
dir['D'] = 1;
dir['L'] = 2;
dir['U'] = 3;
var rope = mutableListOf<MutablePair<Int, Int>>();
for (ite in 0 until ropeSize) rope.add(MutablePair(0, 0));
set.add(Pair(0, 0));
for (line in input) {
var vs = line.split(" ");
var d = vs[0][0];
var steps = vs[1].toInt();
for (ite in 0 until steps) {
rope[0] = MutablePair(rope[0].first + dx[dir[d]!!], rope[0].second + dy[dir[d]!!]);
for (i in 1 until ropeSize) {
while (max(abs(rope[i].first - rope[i - 1].first), abs(rope[i].second - rope[i - 1].second)) > 1) {
if (rope[i].first < rope[i-1].first) rope[i].first += 1;
else if (rope[i].first > rope[i-1].first) rope[i].first -= 1;
if (rope[i].second < rope[i-1].second) rope[i].second++;
else if (rope[i].second > rope[i-1].second) rope[i].second--;
}
}
set.add(Pair(rope[ropeSize-1].first, rope[ropeSize-1].second));
}
}
return set.size;
}
fun part2(input: List<String>): Int {
val ropeSize = 10;
var set = mutableSetOf<Pair<Int, Int>>();
var dx = listOf<Int>(1, 0, -1, 0);
var dy = listOf<Int>(0, -1, 0, 1);
var dir = mutableMapOf<Char, Int>();
dir['R'] = 0;
dir['D'] = 1;
dir['L'] = 2;
dir['U'] = 3;
var rope = mutableListOf<MutablePair<Int, Int>>();
for (ite in 0 until ropeSize) rope.add(MutablePair(0, 0));
set.add(Pair(0, 0));
for (line in input) {
var vs = line.split(" ");
var d = vs[0][0];
var steps = vs[1].toInt();
for (ite in 0 until steps) {
rope[0] = MutablePair(rope[0].first + dx[dir[d]!!], rope[0].second + dy[dir[d]!!]);
for (i in 1 until ropeSize) {
while (max(abs(rope[i].first - rope[i - 1].first), abs(rope[i].second - rope[i - 1].second)) > 1) {
if (rope[i].first < rope[i-1].first) rope[i].first += 1;
else if (rope[i].first > rope[i-1].first) rope[i].first -= 1;
if (rope[i].second < rope[i-1].second) rope[i].second++;
else if (rope[i].second > rope[i-1].second) rope[i].second--;
}
}
set.add(Pair(rope[ropeSize-1].first, rope[ropeSize-1].second));
}
}
return set.size;
}
val input = readInput("Day09")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 3,045 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day07.kt | bunjix | 573,915,819 | false | {"Kotlin": 9977} | fun main() {
val rootMap = mutableMapOf<String, Int>()
var currentDir = ""
fun enterDirectory(dirName: String) {
currentDir = when {
currentDir.isEmpty() -> dirName
currentDir == "/" -> "/$dirName"
else -> "$currentDir/$dirName"
}
rootMap[currentDir] = rootMap.getOrDefault(currentDir, 0)
}
fun endDirectory() {
currentDir = currentDir.removeSuffix("/").substringBeforeLast('/')
if (currentDir.isEmpty()) {
currentDir = "/"
}
}
fun parseFileContent(file: String) {
rootMap[currentDir] = rootMap.getOrDefault(currentDir, 0) + file.split(" ")[0].toInt()
}
val input = readInput("Day07_input")
input.forEach {
when {
it.startsWith("$ cd ..") -> endDirectory()
it.startsWith("$ cd ") -> enterDirectory(it.removePrefix("$ cd "))
it.endsWith(" ls") -> Unit
it.take(1).toIntOrNull() != null -> parseFileContent(it)
}
}
val directorySizeMap = rootMap.mapValues { (dir) -> rootMap.filter { it.key.startsWith(dir) }.values.sum() }
val sumOfDirectoryOfMaxSize100000 = directorySizeMap.filterValues { it <= 100000 }.values.sum()
println(sumOfDirectoryOfMaxSize100000)
val totalAvailableDiskSpace = 70000000
val spaceNeededForUpdate = 30000000
val currentFreeSpace = totalAvailableDiskSpace - directorySizeMap["/"]!!
val spaceToFree = spaceNeededForUpdate - currentFreeSpace
val directoryToDelete = directorySizeMap.toList().sortedBy { it.second }
.first { it.second >= spaceToFree }
println(directoryToDelete.second)
} | 0 | Kotlin | 0 | 0 | ee2a344f6c0bb2563cdb828485e9a56f2ff08fcc | 1,669 | aoc-2022-kotlin | Apache License 2.0 |
core/src/main/kotlin/com/bsse2018/salavatov/flt/algorithms/CFPQTensor.kt | vsalavatov | 241,599,920 | false | {"Kotlin": 149462, "ANTLR": 1960} | package com.bsse2018.salavatov.flt.algorithms
import com.bsse2018.salavatov.flt.automata.PushDownAutomaton
import com.bsse2018.salavatov.flt.grammars.ContextFreeGrammar.Companion.Epsilon
import com.bsse2018.salavatov.flt.utils.Graph
import org.la4j.matrix.SparseMatrix
import org.la4j.matrix.sparse.CRSMatrix
import java.util.*
fun CFPQTensorQuery(graph: Graph, grammar: PushDownAutomaton, epsilonRepr: String = Epsilon): Set<Pair<Int, Int>> {
val grammarSize = grammar.automaton.size
val graphSize = graph.size
val symbols = grammar.symbols.union(graph.flatMap { it.map { it.first }.toSet() }.toSet())
val epsEdges = grammar.automaton.mapIndexed { u, edges ->
edges.filter { it.first == epsilonRepr }
.map { Pair(u, it.second) }
}.flatten()
val grammarMatrices = mutableMapOf<String, SparseMatrix>()
val graphMatrices = mutableMapOf<String, SparseMatrix>()
val startFinishToNonTerm = mutableMapOf<Pair<Int, Int>, String>()
grammar.startStates.forEach { (nonTerm, u) ->
grammar.finishStates[nonTerm]?.forEach { v ->
startFinishToNonTerm[u to v] = nonTerm
}
}
symbols.forEach { sym ->
grammarMatrices[sym] = CRSMatrix(grammarSize, grammarSize)
graphMatrices[sym] = CRSMatrix(graphSize, graphSize)
}
grammar.automaton.forEachIndexed { u, edges ->
edges.filter { it.first != epsilonRepr }
.forEach { (sym, v) ->
grammarMatrices[sym]!![u, v] = 1.0
}
}
graph.forEachIndexed { u, edges ->
edges.forEach { (sym, v) ->
graphMatrices[sym]!![u, v] = 1.0
}
}
do {
var changed = false
val totalProduct = CRSMatrix(grammarSize * graphSize, grammarSize * graphSize)
symbols.forEach { sym ->
val gramMt = grammarMatrices[sym]!!
val graphMt = graphMatrices[sym]!!
gramMt.eachNonZero { i, j, _ ->
graphMt.eachNonZero { u, v, _ ->
totalProduct[i * graphSize + u, j * graphSize + v] = 1.0
}
}
}
epsEdges.forEach { (u, v) ->
graph.indices.forEach { grU ->
totalProduct[u * graphSize + grU, v * graphSize + grU] = 1.0
}
}
val tc = transitiveClosure(totalProduct)
tc.eachNonZero { i, j, _ ->
val grammarU = i / graphSize
val grammarV = j / graphSize
val graphU = i % graphSize
val graphV = j % graphSize
startFinishToNonTerm[grammarU to grammarV]?.let { nonTerm ->
val mt = graphMatrices[nonTerm]!!
if (mt.get(graphU, graphV) == 0.0) {
mt[graphU, graphV] = 1.0
changed = true
}
}
}
} while (changed)
val result = mutableSetOf<Pair<Int, Int>>()
graphMatrices[grammar.start]!!.eachNonZero { i, j, _ ->
result.add(i to j)
}
return result
}
private fun transitiveClosurePow(matrix: CRSMatrix): SparseMatrix {
return matrix.add(CRSMatrix.identity(matrix.columns())).power(matrix.columns()).toSparseMatrix()
}
private fun transitiveClosure(matrix: CRSMatrix): CRSMatrix {
val queue = LinkedList<Int>()
val visited = Array(matrix.rows()) { false }
val result = CRSMatrix(matrix.rows(), matrix.columns())
for (u in matrix.iteratorOfNonZeroRows()) {
visited.fill(false)
matrix.eachNonZeroInRow(u) { v, _ ->
if (!visited[v]) {
visited[v] = true
queue.add(v)
result[u, v] = 1.0
}
}
while (queue.isNotEmpty()) {
val curU = queue.pop()
matrix.eachNonZeroInRow(curU) { v, _ ->
if (!visited[v]) {
visited[v] = true
queue.add(v)
result[u, v] = 1.0
}
}
}
}
return result
} | 0 | Kotlin | 0 | 1 | c1c229c113546ef8080fc9d3568c5024a22b80a5 | 4,020 | bsse-2020-flt | MIT License |
src/main/kotlin/kr/co/programmers/P67258.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/455
class P67258 {
fun solution(gems: Array<String>): IntArray {
// ["AA", "AB", "AC", "AA", "AC"]
// [ 0, 1, 2, 0, 2 ]
val map = mutableMapOf<String, Int>()
val list = mutableListOf<Int>()
var i = 0
for (gem in gems) {
val idx = map[gem] ?: i++
map[gem] = idx
list += idx
}
val counter = IntArray(i)
counter[list[0]]++
// 계산하기
var count = 1
var from = 0
var to = 0
// [가장 짧은 구간 길이, 시작 진열대 번호, 끝 진열대 번호]
val min = intArrayOf(gems.size, 1, gems.size)
while (from < gems.size) {
if (count < counter.size) { // 모든 물건을 사지 않았다
if (to < list.lastIndex) { // to + 1
to++
counter[list[to]]++
if (counter[list[to]] == 1) {
count++
}
} else { // from + 1
counter[list[from]]--
if (counter[list[from]] == 0) {
count--
}
from++
}
} else { // 모든 물건을 샀다
if (to - from + 1 < min[0]) {
min[0] = to - from + 1
min[1] = from + 1
min[2] = to + 1
}
// 완성된 크기가 고유한 물건의 크기와 일치하면 바로 종료
if (min[0] == counter.size) break
counter[list[from]]--
if (counter[list[from]] == 0) {
count--
}
from++
}
}
return intArrayOf(min[1], min[2])
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,921 | algorithm | MIT License |
src/Day03.kt | proggler23 | 573,129,757 | false | {"Kotlin": 27990} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
it.chunked(it.length / 2)
.map { half -> half.toSet() }
.let { (left, right) -> left intersect right }
.single().priority
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf {
it.map { line -> line.toSet() }
.let { (elf1, elf2, elf3) -> elf1 intersect elf2 intersect elf3 }
.single().priority
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
val Char.priority: Int get() = if (isLowerCase()) (this - 'a') + 1 else (this - 'A') + 27 | 0 | Kotlin | 0 | 0 | 584fa4d73f8589bc17ef56c8e1864d64a23483c8 | 909 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/gitTraining/Fibbonaci.kt | stellake | 275,847,748 | true | {"Kotlin": 5488} | package com.gitTraining
fun computeFibbonaciNumber(position: Int?, recursion: Boolean = false): Int {
var notNullPosition = position
if (notNullPosition == null) {
notNullPosition = 1
}
if (recursion) return recursiveFibbonachi(1, 1, notNullPosition - 2)
if (notNullPosition == 0) return 0
if (notNullPosition < 0) {
return computeNegativeFibbonachi(notNullPosition)
}
if (notNullPosition == 1 || notNullPosition == 2) return 1
var smallFibbonachiNumber = 1
var largeFibbonachiNumber = 1
var currentPosition = 2
while (currentPosition < notNullPosition) {
val nextFibbonachiNumber = smallFibbonachiNumber + largeFibbonachiNumber
smallFibbonachiNumber = largeFibbonachiNumber
largeFibbonachiNumber = nextFibbonachiNumber
currentPosition ++
}
return largeFibbonachiNumber
}
fun computeFibbonachiArray(start: Int, end: Int, efficient: Boolean = false): List<Int> {
if (!efficient) return (start..end).map { computeFibbonaciNumber(it) }
if (start > end) return listOf()
if (start == end) return listOf(computeFibbonaciNumber(start))
val output = mutableListOf(computeFibbonaciNumber(start), computeFibbonaciNumber(start + 1))
(2..(end-start)).forEach { output.add(output[it-2] + output[it-1]) }
return output
}
fun recursiveFibbonachi(previous: Int, current: Int, stepsLeft: Int): Int {
if (stepsLeft < 0) return 1
return when (stepsLeft) {
0 -> current
else -> recursiveFibbonachi(current, previous + current, stepsLeft - 1)
}
}
fun computeNegativeFibbonachi(position:Int): Int {
if (position >= 0) throw Exception("potition must be smaller than zero!")
val resultIsNegative = position % 2 == 0
val absoluteResult = computeFibbonaciNumber(-position)
return if (resultIsNegative) (absoluteResult * -1) else absoluteResult
}
| 0 | Kotlin | 0 | 0 | d4b42d81eb35c78a42ac6aa62f64964d2bd1bc94 | 1,899 | git-training | MIT License |
2021/src/main/kotlin/com/trikzon/aoc2021/Day6.kt | Trikzon | 317,622,840 | false | {"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397} | package com.trikzon.aoc2021
fun main() {
val input = getInputStringFromFile("/day6.txt")
benchmark(Part.One, ::daySixPartOne, input, 5934, 500)
benchmark(Part.Two, ::daySixPartTwo, input, 377263, 50000)
}
// Note: This was a slow naive solution. Part 2 is much faster. I'm keeping
// this here to show my thought process.
fun daySixPartOne(input: String): Int {
val list = ArrayList<Int>()
list.addAll(input.split(',').map { str -> str.toInt() })
for (i in 0 until 80) {
for (j in list.indices) {
if (list[j] == 0) {
list[j] = 6
list.add(8)
} else {
list[j]--
}
}
}
return list.size
}
fun daySixPartTwo(input: String): Long {
val fishOfAges = Array(9) { 0L }
input.split(',').map { str -> str.toInt() }.forEach { num -> fishOfAges[num]++ }
for (i in 0 until 256) {
val fishOfAgeZero = fishOfAges[0]
for (j in 1 until fishOfAges.size) {
fishOfAges[j - 1] = fishOfAges[j]
}
fishOfAges[8] = fishOfAgeZero
fishOfAges[6] += fishOfAgeZero
}
var totalFish = 0L
for (fish in fishOfAges) {
totalFish += fish
}
return totalFish
}
| 0 | Kotlin | 1 | 0 | d4dea9f0c1b56dc698b716bb03fc2ad62619ca08 | 1,250 | advent-of-code | MIT License |
src/Day25.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | fun main() {
fun part1(input: List<String>): String {
var n = input.sumOf {
it.fold(0L) { acc, c ->
acc * 5L + when (c) {
'0' -> 0L
'1' -> 1L
'2' -> 2L
'-' -> -1L
'=' -> -2L
else -> throw IllegalArgumentException("Invalid input $c")
}
}
}
val s = ArrayDeque<Int>()
var acc = 0
while (n != 0L) {
var rem = (n % 5L).toInt() + acc
acc = if (rem >= 3) {
rem -= 5
1
} else {
0
}
s.add(rem)
n /= 5
}
return s.reversed().joinToString("") {
when (it) {
0 -> "0"
1 -> "1"
2 -> "2"
-1 -> "-"
-2 -> "="
else -> throw IllegalArgumentException("Invalid input $it")
}
}
}
val testInput = readInput("Day25_test")
check(part1(testInput) == "2=-1=0")
val input = readInput("Day25")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 1,195 | aoc-2022 | Apache License 2.0 |
strings/CheckIfAWordOccursAsAPrefixOfAnyWordInASentence/kotlin/Solution.kt | YaroslavHavrylovych | 78,222,218 | false | {"Java": 284373, "Kotlin": 35978, "Shell": 2994} | /**
* Given a sentence that consists of some words separated by a single space,
* and a searchWord. You have to check if searchWord
* is a prefix of any word in sentence.
* Return the index of the word in sentence
* where searchWord is a prefix of this word (1-indexed).
* If searchWord is a prefix of more than one word,
* return the index of the first word (minimum index).
* If there is no such word return -1.
* A prefix of a string S is any leading contiguous substring of S.
* <br>
* https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
*/
class Solution {
fun isPrefixOfWord(sentence: String, searchWord: String): Int {
var i = 0
var word = 1
var start = true
for (ch in sentence) {
if (ch == ' ') {
start = true
word += 1
continue
}
if (start && searchWord[i] == ch) {
i += 1
if (i >= searchWord.length) return word
} else {
start = false
i = 0
}
}
return -1
}
}
fun main() {
println("Check If a Word Occurs As a Prefix of Any Word in a Sentence" +
": test is not implemented")
}
| 0 | Java | 0 | 2 | cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd | 1,287 | codility | MIT License |
src/Day01.kt | Krzychuk9 | 573,127,179 | false | null | import common.Elv
import common.Item
fun main() {
fun part1(input: List<String>): Int {
return input.getElves()
.maxBy { it.getTotalCalories() }
.getTotalCalories()
}
fun part2(input: List<String>): Int {
return input.getElves()
.sortedByDescending { it.getTotalCalories() }
.take(3)
.sumOf { it.getTotalCalories() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
fun List<String>.getElves(): List<Elv> {
val elves = mutableListOf(Elv(1))
this.forEach {
val lastElv = elves.last()
if (it.isEmpty()) elves.add(Elv(lastElv.id + 1)) else lastElv.items.add(Item((it.toInt())))
}
return elves
}
| 0 | Kotlin | 0 | 0 | ded55d03c9d4586166bf761c7d5f3f45ac968e81 | 939 | adventOfCode2022 | Apache License 2.0 |
src/cn/leetcode/codes/simple724/Simple724.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple724
import cn.leetcode.codes.out
import com.sun.xml.internal.xsom.impl.ForeignAttributesImpl
import java.util.*
fun main() {
// val nums = intArrayOf(1, 7, 3, 6, 5, 6)
// val nums = intArrayOf(1,2,3)
val nums = intArrayOf(-1,-1,-1,-1,-1,0)
val i = pivotIndex(nums)
out("i = $i")
}
/*
724. 寻找数组的中心索引
给你一个整数数组 nums,请编写一个能够返回数组 “中心索引” 的方法。
数组 中心索引 是数组的一个索引,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果数组不存在中心索引,返回 -1 。如果数组有多个中心索引,应该返回最靠近左边的那一个。
示例 1:
输入:nums = [1, 7, 3, 6, 5, 6]
输出:3
解释:
索引 3 (nums[3] = 6) 的左侧数之和 (1 + 7 + 3 = 11),与右侧数之和 (5 + 6 = 11) 相等。
同时, 3 也是第一个符合要求的中心索引。
示例 2:
输入:nums = [1, 2, 3]
输出:-1
解释:
数组中不存在满足此条件的中心索引。
提示:
nums 的长度范围为 [0, 10000]。
任何一个 nums[i] 将会是一个范围在 [-1000, 1000]的整数。
*/
fun pivotIndex(nums: IntArray): Int {
if (nums.isEmpty()) return -1
//总和
val sum = nums.sum()
var leftCount = 0
for (l in nums.indices) {
//乘2 代表左右两边整体数据
if ((2 * leftCount) + nums[l] == sum) {
return l
}
leftCount += nums[l]
}
return -1
} | 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 1,532 | LeetCodeSimple | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountPyramids.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* 2088. Count Fertile Pyramids in a Land
* @see <a href="https://leetcode.com/problems/count-fertile-pyramids-in-a-land/">Source</a>
*/
fun interface CountPyramids {
operator fun invoke(grid: Array<IntArray>): Int
}
class CountPyramidsDP : CountPyramids {
override operator fun invoke(grid: Array<IntArray>): Int {
val m: Int = grid.size
val n: Int = grid.first().size
val rev = Array(m) { IntArray(n) }
for (i in 0 until m) {
for (j in 0 until n) rev[m - i - 1][j] = grid[i][j]
}
return cal(grid) + cal(rev)
}
private fun cal(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
var res = 0
for (i in 1 until m) {
var j = 0
var cnt = 0
while (j < n) {
if (0 != grid[i][j]) cnt++ else cnt = 0
if (0 == cnt || 0 == j) {
++j
continue
}
grid[i][j] = min(grid[i - 1][j - 1] + 1, cnt + 1 shr 1)
res += grid[i][j] - 1
++j
}
}
return res
}
}
class CountPyramidsDP2 : CountPyramids {
override operator fun invoke(grid: Array<IntArray>): Int {
val inverseGrid = inverse(grid)
return helper(grid) + helper(inverseGrid)
}
private fun helper(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
var ans = 0
for (i in 1 until m) {
for (j in 1 until n - 1) {
if (grid[i][j] > 0) {
grid[i][j] = min(
min(grid[i - 1][j], grid[i - 1][j - 1]),
grid[i - 1][j + 1],
) + 1
ans += grid[i][j] - 1
}
}
}
return ans
}
private fun inverse(grid: Array<IntArray>): Array<IntArray> {
val m = grid.size
val n = grid[0].size
val g = Array(m) { IntArray(n) }
for (i in 0 until m) {
for (j in 0 until n) {
g[i][j] = grid[m - i - 1][j]
}
}
return g
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,881 | kotlab | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem2007/Solution2.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2007
/**
* LeetCode page: [2007. Find Original Array From Doubled Array](https://leetcode.com/problems/find-original-array-from-doubled-array/);
*/
class Solution2 {
/* Complexity:
* Time O(NLogN) and Space O(N) where N is size of changed;
*/
fun findOriginalArray(changed: IntArray): IntArray {
val isSizeOfChangedOdd = changed.size and 1 == 1
if (isSizeOfChangedOdd) return intArrayOf()
val sortedNumberToChangedFrequency = getSortedNumberToFrequency(changed)
return constructOriginalArray(changed.size shr 1, sortedNumberToChangedFrequency)
}
private fun getSortedNumberToFrequency(numbers: IntArray): MutableMap<Int, Int> {
val sortedNumberToFrequency = sortedMapOf<Int, Int>()
for (number in numbers) {
sortedNumberToFrequency[number] = sortedNumberToFrequency.getOrDefault(number, 0) + 1
}
return sortedNumberToFrequency
}
private fun constructOriginalArray(size: Int, sortedNumberToChangedFrequency: MutableMap<Int, Int>): IntArray {
val attemptRevertZeroFailed =
!attemptRevertFrequencyChangeOfZero(sortedNumberToChangedFrequency)
if (attemptRevertZeroFailed) return intArrayOf()
val original = IntArray(size)
var currIndexOfOriginal = sortedNumberToChangedFrequency[0] ?: 0
sortedNumberToChangedFrequency.remove(0)
for (number in sortedNumberToChangedFrequency.keys) {
val frequencyOfNumber = checkNotNull(sortedNumberToChangedFrequency[number])
if (frequencyOfNumber == 0) continue
val attemptRevertDoubleFailed =
!attemptRevertFrequencyChangeOfItsDoubled(number, sortedNumberToChangedFrequency)
if (attemptRevertDoubleFailed) return intArrayOf()
repeat(frequencyOfNumber) { original[currIndexOfOriginal++] = number }
}
return original
}
private fun attemptRevertFrequencyChangeOfZero(numberToFrequency: MutableMap<Int, Int>): Boolean {
val frequencyOfZero = numberToFrequency[0]
if (frequencyOfZero != null) {
val isFrequencyOfZeroOdd = frequencyOfZero and 1 == 1
if (isFrequencyOfZeroOdd) return false
numberToFrequency[0] = frequencyOfZero shr 1
}
return true
}
private fun attemptRevertFrequencyChangeOfItsDoubled(
positiveNumber: Int,
numberToFrequency: MutableMap<Int, Int>
): Boolean {
val double = positiveNumber shl 1
val frequencyOfDouble = numberToFrequency[double]
val frequencyOfNumber = requireNotNull(numberToFrequency[positiveNumber])
val isInvalidDouble = frequencyOfDouble == null || frequencyOfDouble < frequencyOfNumber
if (isInvalidDouble) return false
numberToFrequency[double] = checkNotNull(frequencyOfDouble) - frequencyOfNumber
return true
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,957 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day03.kt | naturboy | 572,742,689 | false | {"Kotlin": 6452} | import java.lang.IllegalArgumentException
fun main() {
fun scoreOf(char: Char): Int {
return when (char) {
in 'a'..'z' -> char - 'a' + 1
in 'A'..'Z' -> char - 'A' + 27
else -> throw IllegalArgumentException("Invalid Char '$char'")
}
}
fun part1(input: List<String>): Int {
val intersectingChars = input.map {
val (first, second) = it.chunked(it.length / 2)
val firstSet = first.toSortedSet()
val secondSet = second.toSortedSet()
firstSet.intersect(secondSet)
}
return intersectingChars.sumOf { chars -> chars.sumOf { char -> scoreOf(char) } }
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.sumOf { group ->
group.map { it.toSortedSet() }
.reduce { first, second -> first.intersect(second).toSortedSet() }.sumOf { scoreOf(it) }
}
}
val testInput = readInputLineByLine("Day03_test")
check(part1(testInput) == 157)
val input = readInputLineByLine("Day03")
println(part1(input))
check(part2(testInput) == 70)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 852871f58218d80702c3b49dd0fd453096e56a43 | 1,194 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/fp/kotlin/example/chapter04/CompositionFunctions.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter04
import fp.kotlin.example.chapter04.solution.curried
import kotlin.math.abs
fun main() {
println(composed(3)) // 9
val addThree = { i: Int -> i + 3 }
val twice = { i: Int -> i * 2 }
val composedFunc = addThree compose twice
println(composedFunc(3)) // 9
val absolute = { i: List<Int> -> i.map { abs(it) } }
val negative = { i: List<Int> -> i.map { -it } }
val minimum = { i: List<Int> -> i.min() }
val result1 = minimum(negative(absolute(listOf(3, -1, 5, -2, -4, 8, 14))))
println(result1) // -14
val composed = minimum compose negative compose absolute
val result2 = composed(listOf(3, -1, 5, -2, -4, 8, 14))
println(result2) // -14
val powerOfTwo = { x: Int -> power(x.toDouble(), 2).toInt() }
val gcdPowerOfTwo = { x1: Int, x2: Int -> gcd(powerOfTwo(x1), powerOfTwo(x2)) }
println(gcdPowerOfTwo(25, 5)) // 25
val curriedGcd1 = ::gcd.curried()
// 잘못된 합성의 예
val composedGcdPowerOfTwo1 = curriedGcd1 compose powerOfTwo
println(composedGcdPowerOfTwo1(25)(5)) // 5
val curriedGcd2 = { m: Int, n: Int -> gcd(m, powerOfTwo(n)) }.curried()
// 적절한 합성의 예
val composedGcdPowerOfTwo2 = curriedGcd2 compose powerOfTwo
println(composedGcdPowerOfTwo2(25)(5)) // 25
}
private fun composed(i: Int) = addThree(twice(i))
private fun addThree(i: Int) = i + 3
private fun twice(i: Int) = i * 2
private tailrec fun gcd(m: Int, n: Int): Int = when (n) {
0 -> m
else -> gcd(n, m % n)
}
private tailrec fun power(x: Double, n: Int, acc: Double = 1.0): Double = when (n) {
0 -> acc
else -> power(x, n - 1, x * acc)
}
infix fun <F, G, R> ((F) -> R).compose(g: (G) -> F): (G) -> R {
return { gInput: G -> this(g(gInput)) }
} | 1 | Kotlin | 23 | 39 | bb10ea01d9f0e1b02b412305940c1bd270093cb6 | 1,812 | fp-kotlin-example | MIT License |
workshops/moscow_prefinals2020/day4/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package workshops.moscow_prefinals2020.day4
fun main() {
val s = readLine()!!
val initMask = s.reversed().replace("(", "0").replace(")", "1").toLong(2)
val memo = List(s.length + 1) { mutableMapOf<Long, Double>() }
memo[0][0] = 1.0
fun solve(n: Int, mask: Long): Double {
memo[n][mask]?.also { return it }
if ((mask and 1) != 0L || (mask shr (n - 1)) == 0L) return 0.0
var options = 0
var sum = 0.0
for (j in 0 until n) if (((mask shr j) and 1L) != 0L) {
for (i in 0 until j) if (((mask shr i) and 1L) == 0L) {
sum += solve(n - 2, (if (j + 1 < n) (mask shr (j + 1) shl (j - 1)) else 0) +
(if (i + 1 < j) ((mask and ((1L shl j) - 1)) shr (i + 1) shl i) else 0) +
(if (0 < i) (mask and ((1L shl i) - 1)) else 0))
options++
}
}
val res = if (options == 0) 0.0 else sum / options
memo[n][mask] = res
return res
}
println(solve(s.length, initMask))
}
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 898 | competitions | The Unlicense |
domain/src/main/kotlin/com/seanshubin/kotlin/tryme/domain/dice/SpheresOfInfluenceDiceStatisticsApp.kt | SeanShubin | 228,113,855 | false | null | package com.seanshubin.kotlin.tryme.domain.dice
object SpheresOfInfluenceDiceStatisticsApp {
fun List<Int>.incrementDieRoll(faces: Int): List<Int> {
val newValues = mutableListOf<Int>()
var carry = true
for (currentIndex in size - 1 downTo 0) {
val value = get(currentIndex)
if (carry) {
if (value == faces) {
newValues.add(1)
} else {
newValues.add(value + 1)
carry = false
}
} else {
newValues.add(value)
}
}
newValues.reverse()
return newValues
}
fun allRolls(quantity: Int, faces: Int): List<List<Int>> {
val startingValue = (1..quantity).map { 1 }
var currentValue = startingValue
val results = mutableListOf(currentValue)
currentValue = currentValue.incrementDieRoll(faces)
while (currentValue != startingValue) {
results.add(currentValue)
currentValue = currentValue.incrementDieRoll(faces)
}
return results
}
fun List<Int>.extractAtIndex(index: Int): Pair<Int, List<Int>> {
val value = get(index)
val before = subList(0, index)
val after = subList(index + 1, size)
val remain = before + after
return Pair(value, remain)
}
fun List<Int>.permutations(): List<List<Int>> {
if (size < 2) return listOf(this)
val allPermutations = mutableListOf<List<Int>>()
for (index in this.indices) {
val (atIndex, remain) = extractAtIndex(index)
remain.permutations().forEach {
val permutation = listOf(atIndex) + it
allPermutations.add(permutation)
}
}
return allPermutations
}
fun List<Int>.hitsForRoll(): Int {
var hits = 0
var accumulator = 0
for (index in indices) {
val current = get(index)
accumulator += current
if (accumulator >= 6) {
hits++
accumulator = 0
}
}
return hits
}
fun List<Int>.maxHitsForRoll(): Int {
val scores: List<Int> = permutations().map { it.hitsForRoll() }
return scores.max() ?: throw RuntimeException("unable to compute maximum of $scores")
}
fun List<List<Int>>.scoreHistogram(): Map<Int, Int> {
val histogram = mutableMapOf<Int, Int>()
forEach {
val score = it.maxHitsForRoll()
histogram[score] = (histogram[score] ?: 0) + 1
}
return histogram
}
fun Int.scoreHistogram(): Map<Int, Int> {
val allRolls = allRolls(this, 6)
return allRolls.scoreHistogram()
}
fun pluralize(quantity: Int, singular: String, plural: String): String {
return if (quantity == 1) singular else plural
}
fun <T> List<List<T>>.flattenWithSpacer(spacer: T): List<T> =
map { listOf(spacer) + it }.flatten().drop(1)
data class HistogramForQuantity(val quantity: Int, val histogram: Map<Int, Int>) {
fun summary(): List<String> {
val total = histogram.values.sum()
val keys = histogram.keys.sorted()
val diceString = pluralize(quantity, "die", "dice")
val caption = "$quantity $diceString"
val summaries = keys.map {
val possible = histogram.getValue(it)
val percent = possible.toDouble() / total.toDouble() * 100.0
val hitString = pluralize(it, "hit", "hits")
val summary = "$possible/$total (%.2f%%) chance of $it $hitString".format(percent)
summary
}
return listOf(caption) + summaries
}
}
@JvmStatic
fun main(args: Array<String>) {
val header = listOf(
"1 hit per grouping of dice that sums to 6 or greater",
""
)
val body = (1..5).map {
HistogramForQuantity(it, it.scoreHistogram())
}.map {
it.summary()
}.flattenWithSpacer("")
val lines = header + body
lines.forEach(::println)
}
}
/*
1 hit per grouping of dice that sums to 6 or greater
1 die
5/6 (83.33%) chance of 0 hits
1/6 (16.67%) chance of 1 hit
2 dice
10/36 (27.78%) chance of 0 hits
25/36 (69.44%) chance of 1 hit
1/36 (2.78%) chance of 2 hits
3 dice
10/216 (4.63%) chance of 0 hits
145/216 (67.13%) chance of 1 hit
60/216 (27.78%) chance of 2 hits
1/216 (0.46%) chance of 3 hits
4 dice
5/1296 (0.39%) chance of 0 hits
333/1296 (25.69%) chance of 1 hit
847/1296 (65.35%) chance of 2 hits
110/1296 (8.49%) chance of 3 hits
1/1296 (0.08%) chance of 4 hits
5 dice
1/7776 (0.01%) chance of 0 hits
456/7776 (5.86%) chance of 1 hit
4258/7776 (54.76%) chance of 2 hits
2885/7776 (37.10%) chance of 3 hits
175/7776 (2.25%) chance of 4 hits
1/7776 (0.01%) chance of 5 hits
*/
| 0 | Kotlin | 0 | 0 | abc67c5f43c01bdf55c6d4adcf05b77610c0473a | 5,007 | kotlin-tryme | The Unlicense |
y2017/src/main/kotlin/adventofcode/y2017/Day12.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2017
import adventofcode.io.AdventSolution
object Day12 : AdventSolution(2017, 12, "Digital Plumber") {
override fun solvePartOne(input: String): String {
val connections = parseInput(input)
val group = findGroup(connections, 0)
return group.size.toString()
}
override fun solvePartTwo(input: String): String {
val connections: MutableMap<Int, List<Int>> = parseInput(input).toMutableMap()
val groups = generateSequence {
connections.keys.firstOrNull()
?.let { id -> findGroup(connections, id) }
?.also { group -> connections -= group }
}
return groups.count().toString()
}
private fun parseInput(input: String): Map<Int, List<Int>> = input.lines()
.map { line -> line.split(" <-> ") }
.associate { (program, connections) ->
program.toInt() to connections.split(", ").map { it.toInt() }
}
private fun findGroup(connections: Map<Int, List<Int>>, firstElement: Int): Set<Int> {
val group = mutableSetOf<Int>()
var newConnections = setOf(firstElement)
while (newConnections.isNotEmpty()) {
group += newConnections
newConnections = newConnections.flatMap { connections[it]!! }.toSet() - group
}
return group
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,202 | advent-of-code | MIT License |
src/day03.kt | skuhtic | 572,645,300 | false | {"Kotlin": 36109} | fun main() {
day03.execute(onlyTests = false, forceBothParts = true)
}
val day03 = object : Day<Int>(3, 157, 70) {
@Suppress("SpellCheckingInspection")
override val testInput: InputData
get() = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
""".trimIndent().lines()
override fun part1(input: InputData): Int = input.asSequence()
.map { line -> line.splitIntoPartsExact(2).map { it.toSet() } }
.map { it.intersectSoloElementOrNull ?: error("Invalid input") }
.sumOf { it.priority }
override fun part2(input: InputData): Int = input.asSequence()
.map { it.toSet() }
.chunked(3)
.map { it.intersectSoloElementOrNull ?: error("Invalid input") }
.sumOf { it.priority }
val Char.priority
get() = when {
isLowerCase() -> this - 'a' + 1
isUpperCase() -> this - 'A' + 27
else -> error("Invalid input")
}
}
fun String.splitIntoPartsExact(noOfParts: Int): List<String> = (length / noOfParts).let { partLength ->
require(length == noOfParts * partLength) { "String not splittable into $noOfParts parts with same size" }
chunked(partLength)
}
val <T> List<Set<T>>.intersectSoloElementOrNull: T?
get() = this.reduce { acc, items -> acc.intersect(items) }.singleOrNull()
| 0 | Kotlin | 0 | 0 | 8de2933df90259cf53c9cb190624d1fb18566868 | 1,529 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/sorting/Inversions.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.sorting
fun main() {
val items = mutableListOf(2, 3, 9, 2, 9) // 2
print("items: $items \n")
print("inversions: ${count(items)} \n")
}
// O(nlog(n)) time | O(n) space
private fun count(arr: MutableList<Int>): Long {
val n = arr.size
val b = MutableList(n) { i -> i }
val aux = MutableList(n) { i -> i }
for (i in 0 until n) {
b[i] = arr[i]
}
return count(arr, b, aux, 0, n - 1)
}
private fun count(arr: MutableList<Int>, b: MutableList<Int>, aux: MutableList<Int>, low: Int, high: Int): Long {
var inversions = 0L
if (high <= low) {
return 0
}
val mid = low + (high - low) / 2
inversions += count(arr, b, aux, low, mid)
inversions += count(arr, b, aux, mid + 1, high)
inversions += merge(b, aux, low, mid, high)
return inversions
}
private fun merge(arr: MutableList<Int>, aux: MutableList<Int>, low: Int, mid: Int, high: Int): Long {
var inversions = 0L
for (k in low..high) {
aux[k] = arr[k]
}
var i = low
var j = mid + 1
for (k in low..high) {
when {
i > mid -> arr[k] = aux[j++]
j > high -> arr[k] = aux[i++]
aux[j] < aux[i] -> {
arr[k] = aux[j++]
inversions += (mid - i + 1)
}
else -> arr[k] = aux[i++]
}
}
return inversions
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 1,427 | algs4-leprosorium | MIT License |
src/main/kotlin/day14/Day14.kt | limelier | 725,979,709 | false | {"Kotlin": 48112} | package day14
import common.InputReader
import util.Grid
import util.Grid.Companion.asGrid
private enum class Rock {
Round,
Square,
None;
override fun toString(): String = when(this) {
Round -> "O"
Square -> "#"
None -> "."
}
}
private fun Grid<Rock>.rollNorth() {
for (lastRow in rowIndices.reversed()) {
for (row in 1 .. lastRow) {
for (col in colIndices) {
val tile = this[row, col]
if (tile == Rock.Round && this[row - 1, col] == Rock.None) {
this[row - 1, col] = Rock.Round
this[row, col] = Rock.None
}
}
}
}
}
private fun Grid<Rock>.rollSouth() {
for (firstRow in rowIndices) {
for (row in rowCount - 2 downTo firstRow) {
for (col in colIndices) {
val tile = this[row, col]
if (tile == Rock.Round && this[row + 1, col] == Rock.None) {
this[row + 1, col] = Rock.Round
this[row, col] = Rock.None
}
}
}
}
}
private fun Grid<Rock>.rollEast() {
for (firstCol in colIndices) {
for (col in colCount - 2 downTo firstCol) {
for (row in rowIndices) {
val tile = this[row, col]
if (tile == Rock.Round && this[row, col + 1] == Rock.None) {
this[row, col + 1] = Rock.Round
this[row, col] = Rock.None
}
}
}
}
}
private fun Grid<Rock>.rollWest() {
for (lastCol in colIndices.reversed()) {
for (col in 1..lastCol) {
for (row in rowIndices) {
val tile = this[row, col]
if (tile == Rock.Round && this[row, col - 1] == Rock.None) {
this[row, col - 1] = Rock.Round
this[row, col] = Rock.None
}
}
}
}
}
private fun Grid<Rock>.spinCycle() {
rollNorth()
rollWest()
rollSouth()
rollEast()
}
private fun Grid<Rock>.load(): Int = rowIndices.sumOf { r ->
this[r].count { it == Rock.Round } * (rowCount - r)
}
public fun main() {
val rocks = InputReader("day14/input.txt")
.lines()
.asGrid { line -> line.map { when(it) {
'O' -> Rock.Round
'#' -> Rock.Square
'.' -> Rock.None
else -> throw IllegalArgumentException("Bad input")
} }.toTypedArray() }
rocks.rollNorth()
println("Part 1: ${rocks.load()}")
val copies = mutableListOf(Grid.shallowCopy(rocks))
var iEqualToLast = 0
for (cycle in 1..1_000_000_000) {
rocks.spinCycle()
val equalCopyIdx = copies.indexOfFirst { it == rocks }
if (equalCopyIdx != -1) {
println("Rocks after $cycle cycles are the same as after $equalCopyIdx cycles, breaking")
iEqualToLast = equalCopyIdx
break
}
copies.add(Grid.shallowCopy(rocks))
}
// we now have a cycle: rocks == copies[iEqualToLast]
val cycleLength = copies.size - iEqualToLast
val cycledCycles = 1_000_000_000 - iEqualToLast
val finalCopyIdx = iEqualToLast + cycledCycles % cycleLength
copies[finalCopyIdx].print("")
println("Part 2: ${copies[finalCopyIdx].load()}")
} | 0 | Kotlin | 0 | 0 | 0edcde7c96440b0a59e23ec25677f44ae2cfd20c | 3,365 | advent-of-code-2023-kotlin | MIT License |
src/Day09.kt | sungi55 | 574,867,031 | false | {"Kotlin": 23985} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
val day = "Day09"
fun getHeadSteps(lines: List<String>) =
sequence {
var x = 0
var y = 0
yield(P(x, y))
for (line in lines) {
repeat(line.drop(2).toInt()) {
when (line[0]) {
'L' -> x--
'R' -> x++
'U' -> y--
'D' -> y++
}
yield(P(x, y))
}
}
}
fun part1(lines: List<String>): Int =
getHeadSteps(lines)
.moveTail()
.toSet()
.count()
fun part2(lines: List<String>): Int =
getHeadSteps(lines)
.moveTail()
.moveTail()
.moveTail()
.moveTail()
.moveTail()
.moveTail()
.moveTail()
.moveTail()
.moveTail()
.toSet()
.count()
val testInput = readInput(name = "${day}_test")
val testInputSecond = readInput(name = "${day}_2_test")
val input = readInput(name = day)
check(part1(testInput) == 13)
check(part2(testInputSecond) == 36)
println(part1(input))
println(part2(input))
}
private fun Sequence<P>.moveTail(): Sequence<P> = scan(P(0, 0)) { tail, (x, y) ->
val dx = x - tail.first
val dy = y - tail.second
val absX = abs(dx)
val absY = abs(dy)
when {
absX <= 1 && absY <= 1 -> tail
absX < absY -> P(x, y - dy.sign)
absX > absY -> P(x - dx.sign, y)
else -> P(x - dx.sign, y - dy.sign)
}
}
data class P(val first: Int, val second: Int) | 0 | Kotlin | 0 | 0 | 2a9276b52ed42e0c80e85844c75c1e5e70b383ee | 1,739 | aoc-2022 | Apache License 2.0 |
Bootcamp_00/src/exercise3/src/main/kotlin/Main.kt | Hasuk1 | 740,111,124 | false | {"Kotlin": 120039} | fun main() {
val outputMode = readOutputMode()
val seasonInput = readSeason()
var temperatureInput = readTemperature()
val modeSymbol = getModeSymbol(outputMode)
val comfortableTemperatureRange = getComfortableTemperatureRange(seasonInput, outputMode)
val comfortable = temperatureInput in comfortableTemperatureRange
temperatureInput = setTemperatureAsMod(outputMode, temperatureInput)
println("\nThe temperature is %.2f $modeSymbol".format(temperatureInput))
println("The comfortable temperature is from ${comfortableTemperatureRange.start} $modeSymbol to ${comfortableTemperatureRange.endInclusive} $modeSymbol")
if (!comfortable) {
val adjustment = if (temperatureInput < comfortableTemperatureRange.start) "warmer by %.2f $modeSymbol".format(
comfortableTemperatureRange.start - temperatureInput
)
else "cooler by %.2f $modeSymbol".format(temperatureInput - comfortableTemperatureRange.endInclusive)
println("Please, make it $adjustment.")
}
}
enum class Mode {
CELSIUS, KELVIN, FAHRENHEIT
}
fun readOutputMode(): Mode {
while (true) {
try {
print("Output mode: ")
val input = readLine()
?: throw IllegalArgumentException("The output format is not correct. Standard format - Celsius is set")
return when (input.uppercase()) {
"CELSIUS" -> Mode.CELSIUS
"KELVIN" -> Mode.KELVIN
"FAHRENHEIT" -> Mode.FAHRENHEIT
else -> {
println("The output format is not correct. Standard format - Celsius is set")
return Mode.CELSIUS
}
}
} catch (e: IllegalArgumentException) {
println(e.message)
return Mode.CELSIUS
}
}
}
enum class Season {
SUMMER, WINTER
}
fun readSeason(): Season {
while (true) {
println("Enter a season - (W)inter or (S)ummer: ")
val input = readLine()?.uppercase()
if (input == "W" || input == "WINTER") {
return Season.WINTER
} else if (input == "S" || input == "SUMMER") {
return Season.SUMMER
} else {
println("Incorrect input. Please enter either 'W' for Winter or 'S' for Summer.")
}
}
}
fun readTemperature(): Float {
while (true) {
try {
println("Enter a temperature in Celsius (˚C): ")
val input = readLine()?.toFloatOrNull()
if (input != null && input >= -50 && input <= 50) {
return input
} else {
println("Incorrect input. Please enter a valid temperature.")
}
} catch (e: NumberFormatException) {
println("Failed to parse the temperature. Please try again.")
}
}
}
fun getModeSymbol(outputMode: Mode): String {
return when (outputMode) {
Mode.CELSIUS -> "˚C"
Mode.FAHRENHEIT -> "°F"
Mode.KELVIN -> "K"
}
}
fun getComfortableTemperatureRange(seasonInput: Season, outputMode: Mode): ClosedFloatingPointRange<Float> {
return when (outputMode) {
Mode.CELSIUS -> when (seasonInput) {
Season.SUMMER -> 22f..25f
Season.WINTER -> 20f..22f
}
Mode.KELVIN -> when (seasonInput) {
Season.SUMMER -> 295.15f..298.15f
Season.WINTER -> 293.15f..295.15f
}
Mode.FAHRENHEIT -> when (seasonInput) {
Season.SUMMER -> 71.6f..77f
Season.WINTER -> 68f..71.6f
}
}
}
fun setTemperatureAsMod(outputMode: Mode, temperatureInput: Float): Float {
return when (outputMode) {
Mode.CELSIUS -> temperatureInput
Mode.FAHRENHEIT -> (temperatureInput * 9 / 5) + 32
Mode.KELVIN -> (temperatureInput + 273.15f)
}
}
| 0 | Kotlin | 0 | 1 | 1dc4de50dd3cd875e3fe76e3da4a58aa04bb87c7 | 3,490 | Kotlin_bootcamp | MIT License |
src/main/kotlin/g0801_0900/s0815_bus_routes/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0815_bus_routes
// #Hard #Array #Hash_Table #Breadth_First_Search #Level_2_Day_11_Graph/BFS/DFS
// #2023_03_22_Time_429_ms_(100.00%)_Space_55.8_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
fun numBusesToDestination(routes: Array<IntArray>, source: Int, target: Int): Int {
if (source == target) {
return 0
}
val targetRoutes: MutableSet<Int> = HashSet()
val queue: Queue<Int> = LinkedList()
val taken = BooleanArray(routes.size)
val graph = buildGraph(routes, source, target, queue, targetRoutes, taken)
if (targetRoutes.isEmpty()) {
return -1
}
var bus = 1
while (queue.isNotEmpty()) {
val size = queue.size
for (i in 0 until size) {
val route = queue.poll()
if (targetRoutes.contains(route)) {
return bus
}
for (nextRoute in graph[route]!!) {
if (!taken[nextRoute]) {
queue.offer(nextRoute)
taken[nextRoute] = true
}
}
}
bus++
}
return -1
}
private fun buildGraph(
routes: Array<IntArray>,
source: Int,
target: Int,
queue: Queue<Int>,
targetRoutes: MutableSet<Int>,
taken: BooleanArray
): Array<ArrayList<Int>?> {
val len = routes.size
val graph: Array<ArrayList<Int>?> = arrayOfNulls(len)
for (i in 0 until len) {
routes[i].sort()
graph[i] = ArrayList()
var id = routes[i].binarySearch(source)
if (id >= 0) {
queue.offer(i)
taken[i] = true
}
id = routes[i].binarySearch(target)
if (id >= 0) {
targetRoutes.add(i)
}
}
for (i in 0 until len) {
for (j in i + 1 until len) {
if (commonStop(routes[i], routes[j])) {
graph[i]?.add(j)
graph[j]?.add(i)
}
}
}
return graph
}
private fun commonStop(routeA: IntArray, routeB: IntArray): Boolean {
var idA = 0
var idB = 0
while (idA < routeA.size && idB < routeB.size) {
if (routeA[idA] == routeB[idB]) {
return true
} else if (routeA[idA] < routeB[idB]) {
idA++
} else {
idB++
}
}
return false
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,665 | LeetCode-in-Kotlin | MIT License |
Chapter07/HeapSort.kt | PacktPublishing | 125,371,513 | false | null | import java.util.*
fun <E: Comparable<E>> Array<E>.sort() {
val middle = size / 2 - 1
for (i in middle downTo 0) {
heapify(this, size, i)
}
for (i in size - 1 downTo 0) {
this[0] = this[i].also { this[i] = this[0] }
heapify(this, i, 0)
}
}
private fun <E: Comparable<E>> heapify(arr: Array<E>, heapSize: Int, root: Int) {
var largest = root
val leftNode = 2 * root + 1
val rightNode = 2 * root + 2
if (leftNode < heapSize && arr[leftNode] > arr[largest]) largest = leftNode
if (rightNode < heapSize && arr[rightNode] > arr[largest]) largest = rightNode
if (largest != root) {
arr[root] = arr[largest].also { arr[largest] = arr[root] }
heapify(arr, heapSize, largest)
}
}
fun <E: Comparable<E>> MutableList<E>.sort() {
val middle = size / 2 - 1
for (i in middle downTo 0) {
heapify(this, size, i)
}
for (i in size - 1 downTo 0) {
this[0] = this[i].also { this[i] = this[0] }
heapify(this, i, 0)
}
}
private fun <E: Comparable<E>> heapify(arr: MutableList<E>, heapSize: Int, root: Int) {
var largest = root
val leftNode = 2 * root + 1
val rightNode = 2 * root + 2
if (leftNode < heapSize && arr[leftNode] > arr[largest]) largest = leftNode
if (rightNode < heapSize && arr[rightNode] > arr[largest]) largest = rightNode
if (largest != root) {
arr[root] = arr[largest].also { arr[largest] = arr[root] }
heapify(arr, heapSize, largest)
}
}
fun main(args: Array<String>) {
val nums = arrayOf(2, 12, 89, 23, 76, 43, 12)
nums.sort()
println(Arrays.toString(nums))
val languages = mutableListOf("Kotlin", "Java", "C#", "R", "Python", "Scala", "Groovy", "C", "C++")
languages.sort()
println(languages)
}
| 0 | Kotlin | 62 | 162 | f125372a286a3bf4f0248db109a7427f6bc643a7 | 1,802 | Hands-On-Data-Structures-and-Algorithms-with-Kotlin | MIT License |
2020/Day3/src/main/kotlin/main.kt | airstandley | 225,475,112 | false | {"Python": 104962, "Kotlin": 59337} | import java.io.File
fun getInput(): List<String> {
return File("Input").readLines()
}
val TREE = '#'
val GROUND = '.'
class Slope(val grid: List<String>, start: Pair<Int, Int>) {
var x = start.first
var y = start.second
fun position(): Char {
return this.grid[this.y][this.x]
}
fun atBottom(): Boolean {
return this.y == (this.grid.size - 1)
}
fun moveDownSlope(angle: Pair<Int, Int>): Char {
val (x, y) = angle
this.y += y
this.x += x
if (this.x >= this.grid[this.y].length) {
this.x = this.x - this.grid[this.y].length
}
return this.position()
}
}
fun countTreesInPath(slope: Slope, angle: Pair<Int, Int>): Int {
var count = 0
while (!slope.atBottom()) {
if (slope.moveDownSlope(angle) == TREE) {
count ++
}
}
return count
}
val anglesToCheck = listOf(Pair(1,1), Pair(3,1), Pair(5,1), Pair(7,1), Pair(1,2))
fun main(args: Array<String>) {
println("First Solution: ${countTreesInPath(Slope(getInput(), Pair(0,0)), Pair(3,1))}")
val counts = ArrayList<Int>(anglesToCheck.size)
anglesToCheck.forEach { angle -> counts.add(countTreesInPath(Slope(getInput(), Pair(0,0)), angle)) }
println("Counts: ${counts}")
var sum: Double = 1.0
counts.forEach {count -> sum = sum * count}
println("Second Solution: ${sum.toBigDecimal().toPlainString()}")
} | 0 | Python | 0 | 0 | 86b7e289d67ba3ea31a78f4a4005253098f47254 | 1,433 | AdventofCode | MIT License |
src/Day04_part1.kt | yashpalrawat | 573,264,560 | false | {"Kotlin": 12474} | fun main() {
val input = readInput("Day04")
/* basically check if one pair is included within other pair
Pair(a,b) Pair(c,d)
the are inclusive if
c >= a && d <= b
a >= c && b <= d
* */
val result = input.sumOf {
val firstPair = it.split(",")[0].toIntPair()
val secondPair = it.split(",")[1].toIntPair()
isInclusive(firstPair, secondPair)
}
print(result)
}
fun String.toIntPair() : Pair<Int, Int> {
val tokens = this.split("-")
return Pair(tokens[0].toInt(), tokens[1].toInt())
}
fun isInclusive(firstAssignment: Pair<Int, Int>, secondAssignment: Pair<Int, Int>) : Int {
val result = (firstAssignment.first >= secondAssignment.first &&
firstAssignment.second <= secondAssignment.second) ||
(secondAssignment.first >= firstAssignment.first &&
secondAssignment.second <= firstAssignment.second)
return if(result) {
1
} else {
0
}
} | 0 | Kotlin | 0 | 0 | 78a3a817709da6689b810a244b128a46a539511a | 1,005 | code-advent-2022 | Apache License 2.0 |
src/main/kotlin/days_2020/Day3.kt | BasKiers | 434,124,805 | false | {"Kotlin": 40804} | package days_2020;
import util.Day
class Day3 : Day(3, 2020) {
val input = World(inputString)
enum class Geology {
TREE, GROUND
}
class World(val geology: List<List<Geology>>) {
constructor(geologyStr: String) : this(
geologyStr.split("\n").map { lineStr ->
lineStr.toCharArray().map {
when (it) {
'#' -> Geology.TREE
else -> Geology.GROUND
}
}
}
)
fun getGeology(x: Int, y: Int) = if (y < geology.size) geology[y].let { line -> line[x % line.size] } else null;
override fun toString() = geology.joinToString("\n") { line ->
line.joinToString("") { if (it == Geology.TREE) "#" else "." }
}
}
class Plane(val world: World, val slope: Pair<Int, Int>) : Iterator<Plane> {
var x: Int = 0
var y: Int = 0
fun hasFlownIntoTree() = world.getGeology(x, y) == Geology.TREE
override fun hasNext() = world.getGeology(x, y) != null
override fun next(): Plane {
x += slope.first
y += slope.second
return this
}
override fun toString() = "(x: $x, y: $y)"
}
fun getTreeEncounters(plane: Plane) = plane.iterator().asSequence().map { it.hasFlownIntoTree() }.count { it }
override fun partOne(): Any {
return getTreeEncounters(Plane(input, 3 to 1))
}
override fun partTwo(): Any {
val slopes = listOf(1 to 1, 3 to 1, 5 to 1, 7 to 1, 1 to 2)
return slopes.fold(1L) { acc, slope -> acc * getTreeEncounters(Plane(input, slope)) }
}
}
| 0 | Kotlin | 0 | 0 | 870715c172f595b731ee6de275687c2d77caf2f3 | 1,694 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/Day01.kt | RusticFlare | 574,508,778 | false | {"Kotlin": 78496} | fun main() {
fun part1(input: String): Int {
return input.splitToSequence("\n\n")
.maxOf { elf -> elf.lines().sumOf { it.toInt() } }
}
fun part2(input: String): Int {
return input.splitToSequence("\n\n")
.map { elf -> elf.lines().sumOf { it.toInt() } }
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readText("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readText("Day01")
check(part1(input) == 68802)
println(part1(input))
check(part2(input) == 205370)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 10df3955c4008261737f02a041fdd357756aa37f | 731 | advent-of-code-kotlin-2022 | Apache License 2.0 |
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2015/day17/Day17.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2015.day17
const val capacity = 150
val input = listOf(50, 44, 11, 49, 42, 46, 18, 32, 26, 40, 21, 7, 18, 43, 10, 47, 36, 24, 22, 40)
fun combinations(options: List<Int> = input.indices.toList(), choices: List<Int> = emptyList()): Set<List<Int>> {
val currentSum = choices.sumOf { input[it] }
if (currentSum == capacity) {
return setOf(choices)
}
val candidate = options.firstOrNull { input[it] + currentSum <= capacity }
if (candidate == null) {
return emptySet()
}
return combinations(options - candidate, choices + candidate) + combinations(options - candidate, choices)
}
fun main() {
val combinations = combinations()
println("Part one: ${combinations.size}")
val minimum = combinations.minOf { it.size }
println("Part two: ${combinations.filter { it.size == minimum }.size}")
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 876 | advent-of-code | MIT License |
src/d05/Day05.kt | Ezike | 573,181,935 | false | {"Kotlin": 7967} | package d05
import readString
data class Action(
val size: Int,
val from: Int,
val to: Int,
)
fun main() {
val input = readString("d05/Day05")
.split("\n\n")
val (crates, instructions) = input
val actions = instructions.split(" ", "\n")
.filter {
it !in listOf("move", "from", "to")
}.chunked(3) { (s, f, t) ->
Action(s.toInt(), f.toInt(), t.toInt())
}
val crateMap = crates
.filter { it.isDigit() }
.associate { it.digitToInt() to "" }
.toMutableMap()
val lines = crates.lines()
for (i in lines.size - 2 downTo 0) {
var c = 1
repeat(crateMap.size) {
val c1 = lines[i].getOrNull(c)
if (c1 != null && c1.toString().isNotBlank()) {
crateMap[it + 1] = crateMap[it + 1] + c1
}
c += 4
}
}
fun part1(): String {
val map = crateMap.toMutableMap()
actions.forEach { (size, from, to) ->
val fromWord = map[from]!!.toMutableList()
var moved = ""
repeat(size) {
fromWord.removeLastOrNull()?.let { moved += it }
}
map[to] = map[to] + moved
map[from] = fromWord.joinToString("")
}
return map.values.mapNotNull { it.lastOrNull() }.joinToString("")
}
fun part2(): String {
val map = crateMap.toMutableMap()
actions.forEach { (size, from, to) ->
val s = map[from]!!
val i = s.length - size
val fromWord = s.substring(i, s.length)
map[to] = map[to] + fromWord
map[from] = s.substring(0, i)
}
return map.values.mapNotNull { it.lastOrNull() }.joinToString("")
}
println(part1())
println(part2())
} | 0 | Kotlin | 0 | 0 | 07ed8acc2dcee09cc4f5868299a8eb5efefeef6d | 1,831 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day02.kt | csabapap | 117,575,936 | false | null | object Day02 {
fun part1(input: String): Int {
var sum = 0
input.lines().forEach({ line ->
var min = 0
var max = 0
line.split("\\s+".toRegex()).forEach {
val number = it.toInt()
if (min == 0 || min > number) {
min = number
}
if (max == 0 || max < number) {
max = number
}
}
sum += max - min
})
return sum
}
fun part2(input: String): Int {
var sum = 0
input.lines().forEach({ line ->
var lineSum = 0;
val numbersString = line.split("\\s".toRegex())
for (i in 0 until numbersString.size - 1) {
(i + 1 until numbersString.size)
.filter {
val first = numbersString[i].toInt()
val second = numbersString[it].toInt()
if (first > second) {
first % second == 0
} else {
second % first == 0
}
}
.forEach {
val first = numbersString[i].toInt()
val second = numbersString[it].toInt()
if (first > second) {
lineSum += first / second
} else {
lineSum += second / first
}
}
}
sum += lineSum
})
return sum
}
} | 0 | Kotlin | 0 | 0 | c1cca8f43b6af87fe3364696d873e0300b602902 | 1,738 | aoc-2017 | MIT License |
2023/src/day02/Day02.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day02
import java.io.File
fun main() {
val input = File("src/day02/Day02.txt").readLines()
val games = input.map { Game(it) }
val colorMap = mapOf<String, Int>(
"red" to 12,
"green" to 13,
"blue" to 14
)
println(games.filter { it.isValidGame(colorMap) }.sumOf { it.id })
println(games.sumOf { it.getPower() })
}
class Game {
private val maxSeen = mutableMapOf<String, Int>()
val id: Int
constructor(input: String) {
id = input.substring(5, input.indexOf(":")).toInt()
// Divide up reveals
val reveals = input.substring(input.indexOf(":") + 1).split(";").map { it.trim() }
reveals.forEach {
val colorStrings = it.split(",").map { it2: String -> it2.trim() }
colorStrings.forEach { colorString: String ->
val pairString = colorString.split(" ")
val count = pairString[0].toInt()
val color = pairString[1]
if (count > maxSeen.getOrDefault(color, 0)) {
maxSeen[color] = count
}
}
}
}
/**
* Returns {@code true} if the game could be played based on reveals
*/
fun isValidGame(colorCount: Map<String, Int>): Boolean {
return colorCount.filter {
maxSeen.getOrDefault(it.key, 0) > it.value
}.isEmpty()
}
fun getMaxSeen(color: String): Int {
return maxSeen.getOrDefault(color, 0)
}
fun getPower(): Int {
return maxSeen.values.reduce { acc: Int, i: Int -> acc * i }
}
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 1,598 | adventofcode | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2019/Day3.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2019
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
class Day3 : AdventDay(2019, 3) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val d = Day3()
report { d.part1() }
report { d.part2() }
}
val centralPort = Point(0, 0)
}
fun part1(): Int {
val (routeA, routeB) = inputAsLines.map {
centralPort.route(it)
}
return manhattanForClosest(routeCollides(routeA, routeB))
}
fun part2(): Int {
val (routeA, routeB) = inputAsLines.map {
centralPort.route(it)
}
return closestToCentralBySteps(routeA, routeB)
}
fun routeCollides(routeA: Route, routeB: Route): Set<Point> {
return routeA.toSet().intersect(routeB.toSet())
}
fun closestToCentral(collisions: Set<Point>): Point {
return collisions.minByOrNull { it: Point -> it.manhattan(centralPort) }!!
}
fun manhattanForClosest(collisions: Set<Point>): Int {
return closestToCentral(collisions).manhattan(centralPort)
}
fun closestToCentralBySteps(routeA: Route, routeB: Route): Int {
return routeCollides(routeA, routeB).map {
steps(routeA, it) + steps(routeB, it)
}.minOrNull() ?: 0
}
fun steps(route: List<Point>, point: Point): Int {
return 1 + route.indexOfFirst { it == point }
}
}
data class Instruction(val d: Direction, val c: Int) {
constructor(code: String) : this(Direction.valueOf(code.first().uppercaseChar().toString()), code.drop(1).toInt())
}
typealias Route = List<Point>
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 1,688 | adventofcode | MIT License |
src/main/kotlin/graph/variation/TwoSat.kt | yx-z | 106,589,674 | false | null | package graph.variation
import graph.core.Edge
import graph.core.Graph
import graph.core.Vertex
import graph.core.tarjan
import util.*
// describe a polynomial time algorithm for 2sat:
// given a boolean formula B in 2cnf (conjunctive normal form)
// determine if it is satisfiable
// note that 3sat is np-complete, but not 2sat
// here we will use a graph algorithm (scc, strongly connected component)
// to solve this problem (that's why we are in the graph package)
fun OneArray<Tuple2<String, String>>.twoSat(): Boolean {
val literals = HashSet<String>()
forEach { (v1, v2) ->
if (v1[0] == '!') {
literals.add(v1[1..1])
} else {
literals.add(v1[0..0])
}
if (v2[0] == '!') {
literals.add(v2[1..1])
} else {
literals.add(v2[0..0])
}
}
val vertices = HashSet<Vertex<String>>()
literals.forEach {
vertices.add(Vertex((it)))
vertices.add(Vertex("!$it"))
}
val edges = HashSet<Edge<String>>()
forEach { (v1, v2) ->
if (v1[0] == '!') {
edges.add(Edge(Vertex(v1[1..1]), Vertex(v2), true))
} else {
edges.add(Edge(Vertex("!$v1"), Vertex(v2), true))
}
if (v2[0] == '!') {
edges.add(Edge(Vertex(v2[1..1]), Vertex(v1), true))
} else {
edges.add(Edge(Vertex("!$v2"), Vertex(v1), true))
}
}
val graph = Graph(vertices, edges)
val scc = graph.tarjan(false)
// println(scc.vertices)
return scc.vertices.none {
val component = it.data
return@none component.any {
val literal = it.data
if (literal[0] == '!') {
component.contains(Vertex(literal[1..1]))
} else {
component.contains(Vertex("!$literal"))
}
}
}
// polynomial time for building the graph, building the scc (meta graph),
// and checking if !x and x are contained in the same component
// references: https://www.geeksforgeeks.org/2-satisfiability-2-sat-problem
}
fun main(args: Array<String>) {
// (!x | y) & (x | !z) & (w & !y)
// this is satisfiable: ex. x = F, y = T, z = F, w = T
// one clause per tuple, assuming literals are single characters
val B = oneArrayOf(
"!x" tu "y",
"x" tu "!z",
"w" tu "!y")
println(B.twoSat())
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,094 | AlgoKt | MIT License |
jeorg-kotlin-algorithms/jeorg-kotlin-alg-4-latent-semantic-analysis/src/main/kotlin/org/jesperancinha/algorithms/weigh/term/frequency/LatentSemanticAnalysisCalculator.kt | jesperancinha | 354,756,418 | false | {"Kotlin": 35444, "Java": 14401, "JavaScript": 10140, "Python": 4018, "Makefile": 1258, "Shell": 89} | package org.jesperancinha.algorithms.weigh.term.frequency
import Jama.EigenvalueDecomposition
import Jama.Matrix
import Jama.SingularValueDecomposition
import org.jesperancinha.console.consolerizer.console.ConsolerizerComposer
import kotlin.math.abs
import kotlin.math.sqrt
class LatentSemanticAnalysisCalculator(sentences: List<String>) {
private val resultTable: List<ArrayList<Any>>
private val stopWords = arrayOf(
"I",
"have",
"show",
"and",
"you",
"Your",
"your",
"it",
"no",
"that",
"the",
"It",
"a",
"us",
"an",
"are",
"That",
"The",
"at",
"to",
"of",
"or",
"with",
"so",
"can",
"go",
"for",
"in",
"is",
"as"
)
private val roots = arrayOf("professional", "cert", "lgbt", "empat", "know", "intelli", "hashmap", "lov")
init {
resultTable = resultTable(sentences)
}
fun calculateSemanticProximity(
word1: String,
word2: String
) {
val word1Sanitized = toSanitizedWordForm(word1)
val word2Sanitized = toSanitizedWordForm(word2)
val word1Filtered = resultTable.filter { word1Sanitized.startsWith(it[0].toString().toLowerCase()) }[0]
val word2Filtered = resultTable.filter { word2Sanitized.startsWith(it[0].toString().toLowerCase()) }[0]
ConsolerizerComposer.outSpace()
.magenta(
"The semantic proximity between word %s and %s is %.2f%s",
word1,
word2,
findSimilarity(word1Filtered, word2Filtered) * 100,
"%%"
)
}
private fun resultTable(sentencesSympathy: List<String>): List<ArrayList<Any>> {
val tf = calculateU(sentencesSympathy)
val uTable = calculateUFromSVD(tf)
val resultTable = (uTable!!.array.zip(tf)).map {
val arrayListOf = arrayListOf(it.second[0])
arrayListOf.addAll(it.first.toList())
arrayListOf
}
return resultTable
}
private fun findSimilarity(word1: List<Any?>, word2: List<Any?>): Double {
val document1: List<Double> = word1.subList(1, word1.size).map { it as Double }
val document2: List<Double> = word2.subList(1, word2.size).map { it as Double }
val product = multiply(document1, document2)
val length1 = pLength(document1)
val length2 = pLength(document2)
val denominator = length1 * length2
if (denominator == 0.0) {
return 0.0
}
return abs(product / denominator)
}
private fun pLength(document1: List<Double>): Double {
var total = 0.0
for (i in document1.indices) {
total += document1[i] * document1[i]
}
return sqrt(total)
}
private fun multiply(document1: List<Double>, document2: List<Double>): Double {
var total = 0.0
for (i in document1.indices) {
total += document1[i] * document2[i]
}
return total
}
private fun calculateUFromSVD(tf: List<Array<Any>>): Matrix? {
val tfArray = tf.map { it.copyOfRange(1, it.size).map { number -> (number as Int).toDouble() }.toDoubleArray() }
.toTypedArray()
val matrixA = Matrix.constructWithCopy(tfArray)
print("The real A =")
matrixA.print(2, 2)
val singularValueDecomposition = SingularValueDecomposition(matrixA)
print("U =")
val u = singularValueDecomposition.u
u.print(2, 2)
ConsolerizerComposer.outSpace().red("S =");
singularValueDecomposition.s.print(2, 2)
ConsolerizerComposer.outSpace().green("V =")
singularValueDecomposition.v.print(2, 2)
ConsolerizerComposer.outSpace().blue("D =")
val e: EigenvalueDecomposition = matrixA.eig()
val d: Matrix = e.d
d.print(2, 2)
return u
}
private fun calculateU(sentences: List<String>): List<Array<Any>> {
val wordsPerSentence =
sentences.map {
it
.replace(".", "")
.replace(",", "")
.replace("!", "")
.split(" ").map { word -> word.toLowerCase() }
}
ConsolerizerComposer.outSpace()
.magenta("1. Stemming => We reduce the words to known root forms")
.magenta("2. Removing stop words => We remove words thar are normally neutral and we identify as of no interest to our analysis")
val allWords = wordsPerSentence.asSequence().flatten()
.filter { !stopWords.contains(it) && it.isNotEmpty() }
.map {
toSanitizedWordForm(it)
}
.distinct()
.sorted().toList()
val tf = allWords.map {
val mutableListOf = arrayListOf<Any>(
it
)
wordsPerSentence.forEach { listWords ->
mutableListOf.add(listWords.filter { word -> word.startsWith(it) }.count())
}
mutableListOf.toArray()
}
tf.forEach {
ConsolerizerComposer.outSpace()
.yellow(
"%s\t%s\t%s\t%s\t%s\t%s",
(it[0] as String).padStart(20),
it[1],
it[2],
it[3],
it[4],
it[5],
it[6],
it[7]
)
}
return tf
}
private fun toSanitizedWordForm(it: String): String {
val findLast = roots.findLast { root -> it.toLowerCase().startsWith(root) }
return if (findLast != null) {
if (it.length >= findLast.length) {
findLast.toLowerCase()
} else
it.toLowerCase()
} else {
it.toLowerCase()
}
}
} | 1 | Kotlin | 0 | 1 | 7a382ed529ebdc53cc025671a453c7bd5699539e | 6,055 | jeorg-algorithms-test-drives | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day16.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2021
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
import at.mpichler.aoc.lib.Test
open class Part16A : PartSolution() {
lateinit var packet: Packet
override fun parseInput(text: String) {
val binData = text.map { it.digitToInt(16).toString(2) }
.joinToString(separator = "") { it.padStart(4, '0') }
packet = Packet(binData)
}
override fun compute(): Long {
return packet.versionSum.toLong()
}
override fun getExampleAnswer(): Int {
return 16
}
override fun getExampleInput(): String? {
return "8A004A801A8002F478"
}
override fun tests(): Sequence<Test> {
return sequence {
yield(Test("620080001611562C8802118E34", 12, "Operator packet(v3) with 2 subPackets"))
yield(Test("C0015000016115A2E0802F182340", 23, "Operator packet"))
yield(Test("A0016C880162017C3686B18A3D4780", 31, "Multiple nested operator packets"))
}
}
private fun Packet(line: String): Packet {
val version = line.substring(0, 3).toInt(2)
val type = line.substring(3, 6).toInt(2)
val content = line.substring(6)
return if (type == 4) { // literal packet
val (length, literal) = parseLiteral(content)
Packet(version, type, length + 6, literal)
} else {
val (length, subPackets) = parseSubPackets(content)
Packet(version, type, length + 6, subPackets = subPackets)
}
}
private fun parseLiteral(text: String): Pair<Int, Long> {
var value = ""
var length = 0
var txt = text
while (true) {
value += txt.substring(1, 5)
length += 5
if (txt.first() == '0') {
break
}
txt = txt.substring(5)
}
return length to value.toLong(2)
}
private fun parseSubPackets(txt: String): Pair<Int, List<Packet>> {
var length = 1
var text = txt
val subPackets = mutableListOf<Packet>()
val lengthType = text.first()
val subPacketLength: Int
if (lengthType == '0') {
subPacketLength = text.substring(1, 16).toInt(2)
length += 15
text = text.substring(16)
} else {
subPacketLength = text.substring(1, 12).toInt(2)
length += 11
text = text.substring(12)
}
var currentLength = 0
while (currentLength < subPacketLength) {
val subPacket = Packet(text)
subPackets.add(subPacket)
length += subPacket.length
if (text.length > subPacket.length) {
text = text.substring(subPacket.length)
}
currentLength += if (lengthType == '1') 1 else subPacket.length
}
return length to subPackets
}
data class Packet(
val version: Int,
val type: Int,
val length: Int,
val literal: Long = 0,
val subPackets: List<Packet> = listOf()
) {
val versionSum: Int get() = version + subPackets.sumOf { it.versionSum }
val value: Long
get() {
return when (type) {
0 -> subPackets.sumOf { it.value }
1 -> subPackets.map { it.value }.reduce { acc, v -> acc * v }
2 -> subPackets.minOf { it.value }
3 -> subPackets.maxOf { it.value }
4 -> literal
5 -> if (subPackets[0].value > subPackets[1].value) 1 else 0
6 -> if (subPackets[0].value < subPackets[1].value) 1 else 0
7 -> if (subPackets[0].value == subPackets[1].value) 1 else 0
else -> error("Invalid type")
}
}
}
}
class Part16B : Part16A() {
override fun compute(): Long {
return packet.value
}
override fun getExampleAnswer(): Int {
return 15
}
override fun tests(): Sequence<Test> {
return sequence {
yield(Test("C200B40A82", 3, "sum of 1 + 2"))
yield(Test("04005AC33890", 54, "product of 6 * 9"))
yield(Test("880086C3E88112", 7, "min of 7, 8, and 9"))
yield(Test("CE00C43D881120", 9, "maximum of 7, 8, and 9"))
yield(Test("D8005AC2A8F0", 1, "produces 1, because 5 is less than 15"))
yield(Test("F600BC2D8F", 0, "produces 0, because 5 is not greater than 15"))
yield(Test("9C005AC2F8F0", 0, "produces 0, because 5 is not equal to 15"))
yield(Test("9C0141080250320F1802104A08", 1, "produces 1, because 1 + 3 = 2 * 2"))
}
}
}
fun main() {
Day(2021, 16, Part16A(), Part16B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 4,823 | advent-of-code-kotlin | MIT License |
src/main/kotlin/day03/part2/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 day03.part2
import utils.*
fun main() {
val input = readInputText("/day03/input.txt")
val data = input.lineSequence().map { it.split(',') }.toList()
println(run(data))
}
private fun run(data: List<List<String>>): Int {
data class Point(val x: Int, val y: Int)
data class TrackedPoint(val point: Point, val steps: Int)
fun String.toPoints(origin: TrackedPoint): List<TrackedPoint> {
val op: (Point) -> Point = when (val dir = this[0]) {
'U' -> { it -> it.copy(y = it.y + 1) }
'D' -> { it -> it.copy(y = it.y - 1) }
'R' -> { it -> it.copy(x = it.x + 1) }
'L' -> { it -> it.copy(x = it.x - 1) }
else -> error("Encountered unexpected direction: $dir")
}
val res = mutableListOf<TrackedPoint>()
var tail = origin
for (i in 0 until substring(1).toInt()) {
tail.copy(point = op(tail.point), steps = tail.steps + 1).also {
tail = it
res.add(it)
}
}
return res
}
fun <T> Iterable<Iterable<T>>.intersectAll(): Iterable<T> {
val itr = iterator()
var res = if (itr.hasNext()) itr.next().toSet() else emptySet()
while (itr.hasNext()) res = res.intersect(itr.next())
return res
}
fun <T, K> Iterable<Iterable<T>>.intersectAllBy(selector: (T) -> K): Iterable<T> {
val tmp = map { it.map(selector) }.intersectAll()
val res = mutableListOf<T>()
forEach { iterable ->
iterable.forEach { element ->
if (selector(element) in tmp) res.add(element)
}
}
return res
}
return data.map { path ->
var tail = TrackedPoint(Point(0, 0), 0)
path.flatMap { segment -> segment.toPoints(tail).also { tail = it.last() } }
.groupBy { it.point }
.map { it.value.minBy(TrackedPoint::steps)!! }
}.intersectAllBy { it.point }
.filter { it.point != Point(0, 0) }
.groupBy { it.point }
.map { it.value.sumBy(TrackedPoint::steps) }
.min()!!
} | 0 | Kotlin | 0 | 1 | 9d6e2adbb25a057bffc993dfaedabefcdd52e168 | 3,246 | AdventOfCode2019 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/UniqueBinarySearchTrees.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 96. Unique Binary Search Trees
* @see <a href="https://leetcode.com/problems/unique-binary-search-trees/">Source</a>
*/
fun interface UniqueBinarySearchTrees {
operator fun invoke(n: Int): Int
}
/**
* Approach 1: Dynamic Programming
* Time complexity O(N^2)
* Space complexity O(N)
*/
class UniqueBSTDP : UniqueBinarySearchTrees {
override fun invoke(n: Int): Int {
val g = IntArray(n + 1)
g[0] = 1
g[1] = 1
for (i in 2..n) {
for (j in 1..i) {
g[i] += g[j - 1] * g[i - j]
}
}
return g[n]
}
}
/**
* Approach 2: Mathematical Deduction
* Time complexity : O(N)
* Space complexity : O(1)
*/
class UniqueBSTDeduction : UniqueBinarySearchTrees {
override fun invoke(n: Int): Int {
// Note: we should use long here instead of int, otherwise overflow
var c: Long = 1
for (i in 0 until n) {
c = c * 2 * (2 * i + 1) / (i + 2)
}
return c.toInt()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,661 | kotlab | Apache License 2.0 |
src/main/kotlin/Main.kt | NiksonJD | 611,690,522 | false | null | package wordsvirtuoso
import java.io.File
fun input(prompt: String) = println(prompt).run { readln() }
fun check(f: Set<String>) = f.filter { it.length != 5 || !it.matches(Regex("[a-z]{5}")) || it.toSet().size != 5 }
class Statistics() {
val start = System.currentTimeMillis()
val badChar = mutableSetOf<String>()
val variants = mutableListOf<MutableMap<String, Color>>()
var count = 0
fun addMap(wordMap: MutableMap<String, Color>) = variants.add(wordMap)
fun addChar(bad: String) = badChar.add(bad)
fun addWord(word: String) =
word.asSequence().map { it.toString() to Color.GREEN }.toMap().toMutableMap().also { addMap(it) }
fun printV() = variants.forEach { ml -> ml.forEach { (key, value) -> print(value.dye(key)) }.run { println() } }
}
enum class Color(private val value: String) {
GREEN("\u001B[48:5:10m"),
YELLOW("\u001B[48:5:11m"),
GREY("\u001B[48:5:7m"),
AZURE("\u001B[48:5:14m");
fun dye(string: String) = "$value$string\u001B[0m"
}
fun output(input: String, x: String, statistics: Statistics) {
val m = mutableMapOf<String, Color>()
input.mapIndexed { i, c ->
if (c == x[i]) m.put(c.toString(), Color.GREEN) else if (x.contains(c)) m.put(c.toString(), Color.YELLOW) else {
statistics.addChar(c.toString()); m.put(c.toString(), Color.GREY)
}
}
statistics.addMap(m).also { println() }.run { statistics.printV() }
println("\n" + statistics.badChar.sorted().joinToString("").let { Color.AZURE.dye(it) })
}
fun game(candidateWords: Set<String>, allWords: Set<String>) {
val x = candidateWords.random().uppercase()
val statistics = Statistics()
while (true) {
val i = input("Input a 5-letter word:").uppercase().also { statistics.count++ }
if (i.equals("exit", true)) {
println("The game is over."); break
} else if (i == x) {
if (statistics.count == 1) {
x.forEach { print(Color.GREEN.dye(it.toString())) }
println("\n\nCorrect!\nAmazing luck! The solution was found at once.")
} else {
statistics.addWord(x).also { println() }.also { statistics.printV() }
val seconds = (System.currentTimeMillis() - statistics.start) / 1000
println("\nCorrect!\nThe solution was found after ${statistics.count} tries in $seconds seconds.")
}; break
} else if (i.length != 5) println("The input isn't a 5-letter word.")
else if (!i.matches(Regex("[A-Z]{5}"))) println("One or more letters of the input aren't valid.")
else if (i.toSet().size != 5) println("The input has duplicate letters.")
else if (!allWords.contains(i.lowercase())) println("The input word isn't included in my words list.")
else output(i, x, statistics)
}
}
fun start(args: Array<String>) {
if (args.size != 2) println("Error: Wrong number of arguments.").also { return }
val (w, c) = arrayOf(File(args[0]), File(args[1]))
if (!w.exists()) println("Error: The words file $w doesn't exist.").also { return }
if (!c.exists()) println("Error: The candidate words file $c doesn't exist.").also { return }
val (a, d) = arrayOf(w.readLines().map { it.lowercase() }.toSet(), c.readLines().map { it.lowercase() }.toSet())
if (!check(a).isEmpty()) println("Error: ${check(a).size} invalid words were found in the $w file.").also { return }
if (!check(d).isEmpty()) println("Error: ${check(d).size} invalid words were found in the $c file.").also { return }
val r = d.toMutableSet(); r.removeAll(a)
if (r.isNotEmpty()) println("Error: ${r.size} candidate words are not included in the $w file.").also { return }
println("Words Virtuoso").also { game(d, a) }
}
fun main(args: Array<String>) = start(args) | 0 | Kotlin | 0 | 0 | a3a9cddb24175c9ddffb0f3830885a731360b7be | 3,821 | Kotlin_WordsVirtuoso | Apache License 2.0 |
src/Day04/Day04.kt | NST-d | 573,224,214 | false | null | package Day04
import utils.*
fun main() {
fun part1(input: List<String>)=
input.map {
it.split(',')
}.sumOf {
val first = it[0].split('-')
val second = it[1].split('-')
var value = 0
if (first[0].toInt() >= second[0].toInt() && first[1].toInt() <= second[1].toInt()){
value = 1
}else if (first[0].toInt() <= second[0].toInt() && first[1].toInt() >= second[1].toInt() ){
value = 1
}
value
}
fun part2(input: List<String>)=
input.map {
it.split(',')
}.count {
val first = it[0].split('-')
val second = it[1].split('-')
( second[0].toInt() <= first[1].toInt() && first[1].toInt() <= second[1].toInt() ) ||
( second[0].toInt() <= first[0].toInt() && first[0].toInt() <= second[1].toInt() ) ||
( first[0].toInt() <= second[0].toInt() && second[0].toInt() <= first[1].toInt() ) ||
( first[0].toInt() <= second[1].toInt() && second[1].toInt() <= first[1].toInt() )
}
val input = readInputLines("Day04")
val test = readTestLines("Day04")
println(part2(input ))
} | 0 | Kotlin | 0 | 0 | c4913b488b8a42c4d7dad94733d35711a9c98992 | 1,246 | aoc22 | Apache License 2.0 |
src/main/kotlin/g2801_2900/s2813_maximum_elegance_of_a_k_length_subsequence/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2801_2900.s2813_maximum_elegance_of_a_k_length_subsequence
// #Hard #Array #Hash_Table #Sorting #Greedy #Heap_Priority_Queue
// #2023_12_06_Time_853_ms_(100.00%)_Space_104.7_MB_(100.00%)
import kotlin.math.max
class Solution {
fun findMaximumElegance(items: Array<IntArray>, k: Int): Long {
items.sortWith { a: IntArray, b: IntArray -> b[0] - a[0] }
val n = items.size
val vis = BooleanArray(n)
val arr = ArrayDeque<Long>()
var distinct: Long = 0
var sum: Long = 0
for (i in 0 until k) {
sum += items[i][0].toLong()
if (vis[items[i][1] - 1]) {
arr.addLast(items[i][0].toLong())
} else {
++distinct
vis[items[i][1] - 1] = true
}
}
var ans = sum + distinct * distinct
var i = k
while (i < n && distinct < k) {
if (!vis[items[i][1] - 1]) {
sum -= arr.removeLast()
sum += items[i][0].toLong()
++distinct
vis[items[i][1] - 1] = true
ans = max(ans.toDouble(), (sum + distinct * distinct).toDouble()).toLong()
}
i++
}
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,262 | LeetCode-in-Kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.