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/commonMain/kotlin/advent2020/day01/Day01Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day01
import advent2020.ProgressLogger
var comparisons = 0 // comparisons counter for reporting
internal fun findIndex(
sortedEntries: List<Int>,
expectedSum: Int,
indexOfExcluded: Int = -1,
): Int {
var startIndex = indexOfExcluded + 1
var endIndex = sortedEntries.lastIndex
while (startIndex < endIndex) {
val sum = sortedEntries[startIndex] + sortedEntries[endIndex]
comparisons++
when {
sum == expectedSum -> return startIndex
sum < expectedSum -> startIndex++
sum > expectedSum -> endIndex--
else -> error("wtf")
}
}
return -1
}
fun part1(input: String): String {
comparisons = 0
val lines = input.trim().lines()
val sortedEntries = lines.map { it.toInt() }.sorted()
val i1 = findIndex(sortedEntries, 2020)
val v1 = sortedEntries[i1]
val result = v1 * (2020 - v1)
return result.toString()
}
interface Day01Part2ProgressLogger : ProgressLogger {
suspend fun progress(no: Int, total: Int, entry: Int, comparisons: Int) {}
suspend fun final(v1: Int, v2: Int, v3: Int, comparisons: Int) {}
}
suspend fun part2(input: String, logger: ProgressLogger = object : Day01Part2ProgressLogger {}): String {
logger as Day01Part2ProgressLogger
comparisons = 0
val lines = input.trim().lines()
val sortedEntries = lines.map { it.toInt() }.sorted()
var i1 = -1
var i2 = -1
while (i2 < 0 && i1 < sortedEntries.size) {
i1++
logger.progress(i1 + 1, sortedEntries.size, sortedEntries[i1], comparisons)
i2 = findIndex(sortedEntries, 2020 - sortedEntries[i1], i1)
}
val v1 = sortedEntries[i1]
val v2 = sortedEntries[i2]
val v3 = 2020 - v2 - v1
val result = v1 * v2 * v3
logger.final(v1, v2, v3, comparisons)
return result.toString()
}
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 1,879 | advent-of-code-2020 | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[50]Pow(x, n).kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。
//
//
//
// 示例 1:
//
//
//输入:x = 2.00000, n = 10
//输出:1024.00000
//
//
// 示例 2:
//
//
//输入:x = 2.10000, n = 3
//输出:9.26100
//
//
// 示例 3:
//
//
//输入:x = 2.00000, n = -2
//输出:0.25000
//解释:2-2 = 1/22 = 1/4 = 0.25
//
//
//
//
// 提示:
//
//
// -100.0 < x < 100.0
// -231 <= n <= 231-1
// -104 <= xn <= 104
//
// Related Topics 递归 数学
// 👍 673 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun myPow(x: Double, n: Int): Double {
//递归分治
//指数
var n1 = n
var value = x
//处理符号 让负 指数 变成 正数
if(n1 < 0 ){
n1 = -n1
value = 1/value
}
return dfsPow(n1,value)
}
private fun dfsPow(n: Int, value: Double): Double {
//递归结束条件
//指数为1 返回1
if(n == 0) return 1.0
//逻辑处理进入下层循环
//分别化为为对半最小单位进行计算
var halfVal = dfsPow(n/2,value)
//根据奇偶性继续计算
return if(n % 2 == 0){
halfVal*halfVal
}else{
halfVal*halfVal*value
}
//数据rever
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,426 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/tree/bintree/LargestBST.kt | yx-z | 106,589,674 | false | null | package tree.bintree
fun main(args: Array<String>) {
// sample tree
// 3
// / \
// 2 5
// \ / \
// 1 3 6
val root = BinTreeNode(3)
root.left = BinTreeNode(2)
root.right = BinTreeNode(5)
root.left!!.right = BinTreeNode(1)
root.right!!.left = BinTreeNode(3)
root.right!!.right = BinTreeNode(6)
// should return 3 (a subtree consisting of 5 -> {3, 6})
println(root.largestBSTSize())
}
// given a Binary Tree find the size of the largest Binary Search Tree among all its subtrees
fun BinTreeNode<Int>.largestBSTSize(): Int = largestBST().size
fun BinTreeNode<Int>?.largestBST(): Ret {
if (this === null) {
return Ret(true, 0)
}
val lBST = this.left.largestBST()
val rBST = this.right.largestBST()
var isValid = lBST.isValid && rBST.isValid
if ((this.left !== null && this.left!!.data > this.data) ||
(this.right !== null && this.right!!.data < this.data)) {
isValid = false
}
return if (isValid) {
Ret(true, lBST.size + rBST.size + 1, lBST.min, rBST.max)
} else {
Ret(false, Math.max(lBST.size, rBST.size))
}
}
class Ret(var isValid: Boolean, var size: Int, var min: Int = 0, var max: Int = 0)
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,170 | AlgoKt | MIT License |
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec23.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2020
import org.elwaxoro.advent.PuzzleDayTester
class Dec23 : PuzzleDayTester(23, 2020) {
override fun part1(): Any = playCupGameWithCrabbo(parse(), 100).let { cups ->
cups.listify(1, cups[1]!!, listOf()).joinToString("")
}
override fun part2(): Any = playCupGameWithCrabbo(parse().plus((10..1000000)), 10000000).let { cups ->
cups[1]!! * cups[cups[1]]!!.toLong()
}
/**
* Starting from an initial key, fetch value, then value's value as a pair
*/
private fun Map<Int, Int>.extract(start: Int): Pair<Int, Int> = this[start]!! to this[this[start]]!!
/**
* Explore the map until the starting key is found again, return as a list
* Initially this was to print the list, then it turned out this was the answer for part 1 also
*/
private tailrec fun Map<Int, Int>.listify(start: Int, last: Int = start, thingy: List<Int> = listOf()): List<Int> {
return if (this[last] == start) {
// end of the loop!
thingy.plus(last)
} else {
this.listify(start, this[last]!!, thingy.plus(last))
}
}
private fun playCupGameWithCrabbo(initial: List<Int>, rounds: Int): Map<Int, Int> {
val maxVal = initial.maxOrNull()!!
// shitty linked list time! key = cup, value = ptr to next cup
val cups = initial.zipWithNext { a, b ->
a to b
}.toMap(mutableMapOf())
// close the loop
cups[initial.last()] = initial.first()
// start with first cup
var current = initial.first()
var a: Pair<Int, Int> = 1 to 1
var b: Pair<Int, Int> = 2 to 2
var c: Pair<Int, Int> = 3 to 3
var finder = -1
var destination: Int? = null
(1..rounds).forEach {
a = cups.extract(current)
b = cups.extract(a.first)
c = cups.extract(b.first)
// instead of removing these 3, then searching the other cups
// lets just look at the ones we pulled out instead
finder = current - 1
destination = null
do {
if (finder == a.first || finder == b.first || finder == c.first) {
finder--
} else if (finder < 1) {
finder = maxVal
} else {
destination = finder
}
} while (destination == null)
// current cup points to what 3rd cup used to point to (fake remove)
cups[current] = c.second
// 3rd cup points to what destination used to point to
cups[c.first] = cups[destination]!!
// destination points to what current used to point to
cups[destination!!] = a.first
// advance to the next cup
current = cups[current]!!
}
return cups
}
private fun parse(): MutableList<Int> =
load().single().split("").filter { it.isNotEmpty() }.map { it.toInt() }.toMutableList()
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 3,057 | advent-of-code | MIT License |
src/Day03.kt | maquirag | 576,698,073 | false | {"Kotlin": 3883} | fun main() {
val day = "03"
fun priority(c: Char): Int = when(c) {
in 'a'..'z' -> (c - 'a') + 1
else -> (c - 'A') + 27
}
fun part1(input: List<String>): Int =
input.map {
val misplaced = (it.take(it.length/2).toSet() intersect it.drop(it.length/2).toSet()).first()
priority(misplaced)
}.sum()
fun part2(input: List<String>): Int =
input.chunked(3).map {(a, b, c) ->
val badge = (a.toSet() intersect b.toSet() intersect c.toSet()).first()
priority(badge)
}.sum()
val testInput = readInput("Day${day}_Test")
val input = readInput("Day${day}")
val test1 = part1(testInput)
check(test1 == 157)
println("Part 1 => ${part1(input)}")
val test2 = part2(testInput)
check(test2 == 70)
println("Part 2 => ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | 23403172e909f8fb0c87e953d06fc0921c75fc32 | 894 | aoc2022-kotlin | Apache License 2.0 |
src/day07/day07.kt | tmikulsk1 | 573,165,106 | false | {"Kotlin": 25281} | package day07
import readInput
data class Node(
val key: String,
val level: Int,
val size: Int = 0,
var totalSize: Int = 0,
var children: List<Node>? = null,
val parent: String? = null
)
var globalCurrentDir = ""
var globalParentDir = ""
var globalLevel = 1
var globalRootNode = Node(key = "dir /", 1)
var currentNodeParent = ""
var currentNodeKey = ""
fun test() {
val file = readInput("day07/input.txt").readLines()
val rootNode = globalRootNode
var goToDir = ""
var skipCharValidation = false
val nodeList = mutableListOf<Node>()
var currentDir = ""
var previsousDir = ""
var parentNode = rootNode
var level = 1
file.forEachIndexed { index, line ->
println(line)
if (!skipCharValidation) {
if (line.contains("cd") && line.contains("..").not()) {
level++
globalLevel = level
}
nodeList.clear()
if (line.contains("$ cd")) {
val lastChar = line.toList().last()
if (lastChar.equals('/', true)) {
currentDir = "dir /"
globalCurrentDir = currentDir
parentNode = rootNode
return@forEachIndexed
} else if (lastChar.equals('.', true)) {
level--
parentNode = rootNode.getPreviousNode(level)
return@forEachIndexed
} else {
// cd x
previsousDir = currentDir
globalParentDir = previsousDir
currentDir = line.replace("$ cd ", "dir ")
globalCurrentDir = currentDir
// parentNode = rootNode.getPreviousNode(level)
// currentNodeKey = rootNode.key
// currentNodeParent = rootNode.parent.orEmpty()
val currentNode = rootNode.findNodeByCurrentKeyAndLevel(currentDir, level -1)
val parent = rootNode.findNodeByCurrentKeyAndLevel(currentNode.parent.orEmpty(), currentNode.level -1)
parentNode = currentNode
// currentNodeParent = parent.key.orEmpty()
// currentNodeKey = currentNode.key
return@forEachIndexed
}
}
if (line.contains("$ ls") && file[index + 1].contains("$").not()) {
skipCharValidation = true
return@forEachIndexed
}
}
// createNodes
if (index < file.size - 1) {
if (file[index + 1].contains("$")) {
skipCharValidation = false
}
}
val (size, fileName) = if (line.contains("dir")) {
listOf("0", line)
} else {
line.split(" ")
}
// convert size from string to int
val intSize = size.toInt()
val node = parentNode.generateNode(fileName, intSize, level) ?: return@forEachIndexed
nodeList.add(node)
parentNode.children = nodeList.toList()
}
println(rootNode)
globalRootNode = rootNode
globalRootNode.sumTotalForEachParent()
println(globalRootNode)
globalRootNode.sumNodesLimit100000()
println(sum)
}
fun Node.generateNode(key: String, size: Int = 0, level: Int): Node {
return Node(
key,
level,
size,
parent = this.key
)
}
fun Node.findParentNode(key: String): Node {
var foundChild: Node = this
with(this) {
while (this.children != null) {
this.children!!.forEachIndexed { index, child ->
if (child.key == key) {
foundChild = this.children!![index]
return@with
}
}
}
}
return foundChild
}
fun Node.findNodeByCurrentKeyAndLevel(keyToFind: String, levelToMatch: Int): Node {
if (isThisNodeFound(keyToFind, levelToMatch)) {
return this
}
this.children!!.getNodeWithKeyAndLevel(keyToFind, levelToMatch)
return currentNodeFound
}
var currentNodeFound: Node = globalRootNode
fun List<Node>.getNodeWithKeyAndLevel(keyToFind: String, levelToMatch: Int) {
with(this) {
forEachIndexed { index, child ->
if (child.isThisNodeFound(keyToFind, levelToMatch)) {
currentNodeFound = this[index]
return@with
}
if (child.children?.isNotEmpty() == true) {
child.children?.getNodeWithKeyAndLevel(keyToFind, levelToMatch)
}
}
}
}
fun Node.isThisNodeFound(keyToFind: String, levelToMatch: Int) =
this.key.equals(keyToFind, true) && this.level == levelToMatch
// tem que ser a root
fun Node.getPreviousNode(level: Int): Node {
var node = this
// if (isThisNode(globalParentDir, globalCurrentDir, level)) {
if (isThisNode(currentNodeParent, currentNodeKey, level)) {
return node
}
// val fnode = this.children!!.getNode(globalParentDir, globalCurrentDir, level)
val fnode = this.children!!.getNode(currentNodeParent, currentNodeKey, level)
if (fnode != null) node = fnode
// globalParentDir = node.parent.orEmpty()
// globalCurrentDir = node.key
currentNodeKey = node.key
currentNodeParent = node.parent.orEmpty()
return node
}
fun List<Node>.getNode(parentKey: String, childKey: String, level: Int): Node? {
var node: Node? = null
with(this) {
forEachIndexed { index, child ->
if (child.isThisNode(parentKey, childKey, level)) {
node = this[index]
return@with
}
if (child.children?.isNotEmpty() == true) {
child.children?.getNode(globalParentDir, globalCurrentDir, level)
}
}
}
return node
}
fun Node.isThisNode(previousKey: String, currentDir: String, level: Int): Boolean {
return this.key.equals(previousKey, true) &&
this.children?.any { it.level == level } == true &&
this.children?.any { it.key == currentDir } == true
}
fun main() {
test()
getaaa()
}
// rootNode
fun Node.sumTotalForEachParent() {
this.getAllChildrenSum()
}
fun Node.getAllChildrenSum() {
val total = loopSumChildren()
totalSize += total
children?.forEach { subChildren ->
subChildren.getAllChildrenSum()
}
}
fun Node.loopSumChildren(): Int {
return children?.sumOf { child ->
child.size + child.loopSumChildren()
} ?: 0
}
var sum = 0
fun Node.sumNodesLimit100000() {
if (totalSize <= 100000) {
sum += totalSize
}
children?.forEach { child ->
child.sumNodesLimit100000()
}
}
val flatNodes = mutableListOf<Node>()
fun Node.getFlatListOfNodesDirWithTotalSize() {
if (this.key.contains("dir ")) {
flatNodes.add(this)
}
this.children?.forEach { child ->
child.getFlatListOfNodesDirWithTotalSize()
}
}
fun getaaa() {
val valueToRemove = 70000000 - globalRootNode.totalSize
globalRootNode.getFlatListOfNodesDirWithTotalSize()
val minValue = flatNodes.filterNot { it.key == "dir /" }.filter {
it.totalSize + valueToRemove >= 30000000
}.minBy { it.totalSize }
println("remove: " + valueToRemove)
println(minValue)
}
| 0 | Kotlin | 0 | 1 | f5ad4e601776de24f9a118a0549ac38c63876dbe | 7,398 | AoC-22 | Apache License 2.0 |
src/net/mlin/GLnext/data/BedRanges.kt | mlin | 421,269,634 | false | {"Kotlin": 129211, "Shell": 12192, "Python": 8907, "Makefile": 186} | package net.mlin.GLnext.data
import net.mlin.iitj.IntegerIntervalTree
/**
* Minimal in-memory data structure of a BED file indexed for overlap/containment queries. Can be
* broadcasted efficiently.
*/
class BedRanges : java.io.Serializable {
private val iit: Array<IntegerIntervalTree>
private val totalCounts: IntArray // cumulative interval count, for id offset
constructor(contigId: Map<String, Short>, ranges: Iterator<GRange>) {
val rangesByRid = Array<MutableList<Pair<Int, Int>>>(contigId.size) { mutableListOf() }
ranges.forEach {
check(it.beg >= 1 && it.beg <= it.end)
rangesByRid[it.rid.toInt()].add(it.beg to it.end)
}
var counter = 0
val totCounts = mutableListOf(0)
iit = rangesByRid.map {
ridRanges ->
val builder = IntegerIntervalTree.Builder()
ridRanges
.sortedWith(compareBy({ it.first }, { it.second }))
.forEach {
builder.add(it.first - 1, it.second)
counter++
}
check(builder.isSorted())
totCounts.add(counter)
builder.build()
}.toTypedArray()
totalCounts = totCounts.toIntArray()
}
constructor(contigId: Map<String, Short>, bed: java.io.Reader) :
this(contigId, parseBed(contigId, bed).iterator()) {}
public val size get() = totalCounts[iit.size]
public fun hasOverlapping(query: GRange): Boolean {
// nb: interval trees are zero-based & half-open (as in BED)
// GRange is one-based & closed
return iit[query.rid.toInt()].queryOverlapExists(query.beg - 1, query.end)
}
public fun queryOverlapping(query: GRange): List<IntegerIntervalTree.QueryResult> {
val ridi = query.rid.toInt()
return iit[ridi].queryOverlap(query.beg - 1, query.end).map {
IntegerIntervalTree.QueryResult(it.beg + 1, it.end, it.id + totalCounts[ridi])
}
}
public fun hasContaining(query: GRange): Boolean {
var ans = false
iit[query.rid.toInt()].queryOverlap(query.beg - 1, query.end, {
if (it.beg < query.beg && it.end >= query.end) {
ans = true
false
} else {
true
}
})
return ans
}
}
fun parseBed(contigId: Map<String, Short>, bed: java.io.Reader): Sequence<GRange> {
return sequence {
bed.useLines { lines ->
// nb: BED is whitespace-delimited, not tab-delimited!
val delim = "\\s+".toRegex()
lines.forEach {
if (it.trim().isNotEmpty() && !it.startsWith("#")) {
val tsv = it.splitToSequence(delim).take(3).toList().toTypedArray()
check(tsv.size == 3, { "[BED] invalid line: $it" })
val rid = contigId.get(tsv[0])
check(rid != null, { "[BED] unknown chromosome: ${tsv[0]}" })
val beg = tsv[1].toInt()
val end = tsv[2].toInt()
check(end >= beg, { "[BED] invalid range: $it" })
yield(GRange(rid, beg + 1, end))
}
}
}
}
}
| 0 | Kotlin | 0 | 3 | 08a13b1993eded11c4ca826c3644ac919c762a23 | 3,278 | GLnext | Apache License 2.0 |
Kotlin/Solucionando problemas em Kotlin/Figurinhas.kt | Pleiterson | 328,727,089 | false | null | // Figurinhas
/*
Ricardo e Vicente são aficionados por figurinhas. Nas horas vagas, eles arrumam
um jeito de jogar um “bafo” ou algum outro jogo que envolva tais figurinhas.
Ambos também têm o hábito de trocarem as figuras repetidas com seus amigos e
certo dia pensaram em uma brincadeira diferente. Chamaram todos os amigos e
propuseram o seguinte: com as figurinhas em mãos, cada um tentava fazer uma
troca com o amigo que estava mais perto seguindo a seguinte regra: cada um
contava quantas figurinhas tinha. Em seguida, eles tinham que dividir as
figurinhas de cada um em pilhas do mesmo tamanho, no maior tamanho que fosse
possível para ambos. Então, cada um escolhia uma das pilhas de figurinhas do
amigo para receber. Por exemplo, se Ricardo e Vicente fossem trocar as
figurinhas e tivessem respectivamente 8 e 12 figuras, ambos dividiam todas as
suas figuras em pilhas de 4 figuras (Ricardo teria 2 pilhas e Vicente teria 3
pilhas) e ambos escolhiam uma pilha do amigo para receber.
- Entrada
A primeira linha da entrada contém um único inteiro N (1 ≤ N ≤ 3000), indicando
o número de casos de teste. Cada caso de teste contém 2 inteiros F1
(1 ≤ F1 ≤ 1000) e F2 (1 ≤ F2 ≤ 1000) indicando, respectivamente, a quantidade
de figurinhas que Ricardo e Vicente têm para trocar.
- Saída
Para cada caso de teste de entrada haverá um valor na saída, representando o
tamanho máximo da pilha de figurinhas que poderia ser trocada entre dois
jogadores.
*/
fun main(args: Array<String>) {
val lista = mutableListOf<Int>()
for (i in 1..readLine()!!.toInt()) {
val input = readLine()!!.split(" ").map { it.toInt() }
if(input.size == 2){
val valorMdc = mdc(input[0], input[1])
lista.add(valorMdc)
}
}
for (i in lista){
println(i)
}
}
// máximo divisor comum (chamada recursiva)
fun mdc(n1: Int, n2: Int): Int {
var resto: Int
var n1 = n1
var n2 = n2
do{
resto = n1%n2
n1 = n2
n2 = resto
}while (resto != 0)
return n1
} | 3 | Java | 73 | 274 | 003eda61f88702e68670262d6c656f47a3f318b6 | 2,094 | desafios-bootcamps-dio | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FlipGame2.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
/**
* 294. Flip Game II
* @see <a href="https://leetcode.com/problems/flip-game-ii/">Source</a>
*/
fun interface FlipGame2 {
fun canWin(currentState: String): Boolean
}
class FG2BruteForce : FlipGame2 {
override fun canWin(currentState: String): Boolean {
for (i in 0 until currentState.length - 1) {
if (currentState[i] == '+' && currentState[i + 1] == '+' && !canWin(
currentState.substring(0, i) + "--" + currentState.substring(i + 2),
)
) {
return true
}
}
return false
}
}
/**
* Backtracking solution with time optimization through DP
*/
class FG2Backtracking : FlipGame2 {
override fun canWin(currentState: String): Boolean {
if (currentState.length < 2) {
return false
}
val winMap = HashMap<String, Boolean>()
return helper(currentState, winMap)
}
private fun helper(s: String, winMap: HashMap<String, Boolean>): Boolean {
if (winMap.containsKey(s)) {
return winMap[s]!!
}
for (i in 0 until s.length - 1) {
if (s.startsWith("++", i)) {
val t = s.substring(0, i) + "--" + s.substring(i + 2)
if (!helper(t, winMap)) {
winMap[s] = true
return true
}
}
}
winMap[s] = false
return false
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,100 | kotlab | Apache License 2.0 |
src/day04/Day04.kt | chskela | 574,228,146 | false | {"Kotlin": 9406} | package day04
import java.io.File
fun main() {
fun parseInput(input: String) = input
.lines()
.map {
it.split(",")
.map { s ->
s.split("-")
}
.map { (a, b) -> (a.toInt()..b.toInt()).toSet() }
}
fun part1(input: String): Int {
val data = parseInput(input).fold(0) { acc: Int, (l1, l2) ->
acc + if (l1.union(l2).size == l1.size || l2.union(l1).size == l2.size) 1 else 0
}
return data
}
fun part2(input: String): Int {
val data = parseInput(input).fold(0) { acc: Int, (l1, l2) ->
acc + if (l1.intersect(l2).isNotEmpty()) 1 else 0
}
return data
}
val testInput = File("src/day04/Day04_test.txt").readText()
println(part1(testInput))
println(part2(testInput))
val input = File("src/day04/Day04.txt").readText()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 951d38a894dcf0109fd0847eef9ff3ed3293fca0 | 981 | adventofcode-2022-kotlin | Apache License 2.0 |
src/Day10.kt | RandomUserIK | 572,624,698 | false | {"Kotlin": 21278} | fun main() {
fun part1(input: List<String>): Int {
var signalStrength = 0
var cycle = 1
var register = 1
fun calculateSignalStrength(currentCycle: Int, register: Int): Int =
currentCycle * register
fun increaseSignalStrength(currentCycle: Int, register: Int) {
if (currentCycle % 40 == 20)
signalStrength += calculateSignalStrength(currentCycle, register)
}
input.forEach { instruction ->
++cycle
increaseSignalStrength(cycle, register)
if (instruction != "noop") {
++cycle
register += instruction.split(" ").last().toInt()
increaseSignalStrength(cycle, register)
}
}
return signalStrength
}
fun part2(input: List<String>) {
var cycle = 1
var register = 1
fun overlapsSprite(position: Int, register: Int): Boolean = position % 40 in (register - 1..register + 1)
fun getCRTSymbol(position: Int, register: Int): String {
if (position % 40 == 0)
println()
return when {
overlapsSprite(position, register) -> "#"
else -> "."
}
}
input.forEach { instruction ->
print(getCRTSymbol(cycle - 1, register))
++cycle
if (instruction != "noop") {
print(getCRTSymbol(cycle - 1, register))
++cycle
register += instruction.split(" ").last().toInt()
}
}
}
val input = readInput("inputs/day10_input")
println(part1(input))
part2(input)
println()
} | 0 | Kotlin | 0 | 0 | f22f10da922832d78dd444b5c9cc08fadc566b4b | 1,358 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day02.kt | SimonMarquis | 724,825,757 | false | {"Kotlin": 30983} | import Day02.Color.blue
import Day02.Color.green
import Day02.Color.red
class Day02(private val input: List<String>) {
@Suppress("EnumEntryName")
enum class Color { red, green, blue }
private val regex = """(\d+) (${Color.entries.joinToString("|")})""".toRegex()
fun part1(
target: Map<Color, Int> = mapOf(red to 12, green to 13, blue to 14),
): Int = input.withIndex().filter { (_, line) ->
line.split(";")
.map { it.cubes() }
.all { it.validate(target) }
}.sumOf { it.index + 1 }
fun part2() = input.withIndex().sumOf { (_, line) ->
val cubes = line.split(";").map { it.cubes() }
fun maxOf(color: Color) = cubes.maxOf { it.getValue(color) }
maxOf(red) * maxOf(green) * maxOf(blue)
}
private fun String.cubes(): Map<Color, Int> = regex.findAll(this)
.map { it.destructured.let { (amount, color) -> Color.valueOf(color) to amount.toInt() } }
.foldInPlace(mutableMapOf<Color, Int>().withDefault { 0 }) { (color, amount) -> merge(color, amount, Int::plus) }
private fun Map<Color, Int>.validate(target: Map<Color, Int>) = target.all { (key, value) -> getValue(key) <= value }
}
| 0 | Kotlin | 0 | 1 | 043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e | 1,204 | advent-of-code-2023 | MIT License |
src/Day06.kt | pmellaaho | 573,136,030 | false | {"Kotlin": 22024} | fun main() {
fun String.allDifferent(): Boolean {
forEachIndexed { index, c ->
for (i in index + 1..lastIndex) {
if (this[i] == c) return false
}
}
return true
}
fun part1(input: List<String>): Int {
val windowSize = 4
val count = input.first().windowed(windowSize, 1)
.takeWhile {
!it.allDifferent()
}
return count.size + windowSize
}
fun part2(input: List<String>): Int {
val windowSize = 14
val count = input.first().windowed(windowSize, 1)
.takeWhile {
!it.allDifferent()
}
return count.size + windowSize
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day06_test")
// val res = part1(testInput)
// check(res == 11)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cd13824d9bbae3b9debee1a59d05a3ab66565727 | 997 | AoC_22 | Apache License 2.0 |
src/main/kotlin/kt/kotlinalgs/app/graph/BellmanFord.ws.kts | sjaindl | 384,471,324 | false | null | package kt.kotlinalgs.app.graph
println("Test")
data class Vertice(val value: String)
data class Edge(
val from: Vertice,
val to: Vertice,
val weight: Int
)
data class WeightedDirectedGraph(val vertices: List<Vertice>) {
var edges: MutableList<Edge> = mutableListOf()
fun addEdge(from: Vertice, to: Vertice, weight: Int) {
val edge = Edge(from, to, weight)
edges.add(edge)
}
}
/*
for each vertice in 0 until V - 1 (min path for each vertice is max V-1 edges long):
runtime: O(V*E)
*/
class BellmanFord() {
fun allShortestPaths(graph: WeightedDirectedGraph): MutableMap<Vertice, Int> {
val dist: MutableMap<Vertice, Int> = mutableMapOf()
graph.vertices.forEach {
dist.put(it, Int.MAX_VALUE)
}
dist.put(graph.vertices[0], 0)
//IntArray(graph.vertices.size) { Int.MAX_VALUE }
//dist[0] = 0
for (v in 0 until graph.vertices.size - 1) {
graph.edges.forEach {
val distFrom = dist[it.from] ?: return@forEach
val distTo = dist[it.to] ?: return@forEach
if (distFrom == Int.MAX_VALUE) return@forEach
val curValue = distFrom + it.weight
if (curValue < distTo) {
dist[it.to] = curValue
}
}
}
// check for negative cycle
graph.edges.forEach {
val distFrom = dist[it.from] ?: return@forEach
val distTo = dist[it.to] ?: return@forEach
if (distFrom == Int.MAX_VALUE) return@forEach
val curValue = distFrom + it.weight
if (curValue < distTo) {
println("Negative cycle found!")
return mutableMapOf()
}
}
return dist
}
}
//https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/
val verticeA = Vertice("A")
val verticeB = Vertice("B")
val verticeC = Vertice("C")
val verticeD = Vertice("D")
val verticeE = Vertice("E")
val graph = WeightedDirectedGraph(
listOf(
verticeA, verticeB, verticeC, verticeD, verticeE
)
)
graph.addEdge(verticeA, verticeB, -1)
graph.addEdge(verticeA, verticeC, 4)
graph.addEdge(verticeB, verticeC, 3)
graph.addEdge(verticeB, verticeD, 2)
graph.addEdge(verticeB, verticeE, 2)
graph.addEdge(verticeD, verticeB, 2)
graph.addEdge(verticeD, verticeC, 5)
graph.addEdge(verticeE, verticeD, -3)
val bellmanFord = BellmanFord()
bellmanFord.allShortestPaths(graph)
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 2,502 | KotlinAlgs | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/TwoSum.kt | ashtanko | 515,874,521 | false | {"Kotlin": 235302, "Shell": 755, "Makefile": 591} | /*
* MIT License
* Copyright (c) 2022 <NAME>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.shtanko.algorithms.leetcode
/**
* 1. Two Sum
* @link https://leetcode.com/problems/two-sum/
*/
fun interface TwoSumStrategy {
/**
* Performs the two-sum operation on the given array of integers.
*
* @param nums the array of integers.
* @param target the target sum.
* @return an array of indices representing the two numbers that add up to the target sum.
*/
operator fun invoke(
nums: IntArray,
target: Int,
): IntArray
}
/**
* Approach 1: Brute Force
* Time complexity: O(n^2).
* Space complexity: O(1).
*/
val twoSumBruteForce = TwoSumStrategy { nums: IntArray, target: Int ->
for (i in nums.indices) {
for (j in i + 1 until nums.size) {
if (nums[j] == target - nums[i]) {
return@TwoSumStrategy intArrayOf(i, j)
}
}
}
return@TwoSumStrategy intArrayOf()
}
/**
* Approach 2: Two-pass Hash Table
* Time complexity: O(n).
* Space complexity: O(n).
*/
val twoSumTwoPassHashTable = TwoSumStrategy { nums: IntArray, target: Int ->
val map: MutableMap<Int, Int> = HashMap()
for (i in nums.indices) {
map[nums[i]] = i
}
for (i in nums.indices) {
val complement = target - nums[i]
if (map.containsKey(complement) && map[complement] != i) {
return@TwoSumStrategy intArrayOf(i, map.getOrDefault(complement, 0))
}
}
return@TwoSumStrategy intArrayOf()
}
/**
* Approach 3: One-pass Hash Table
* Time complexity: O(n).
* Space complexity: O(n).
*/
val twoSumOnePassHashTable = TwoSumStrategy { nums: IntArray, target: Int ->
val map: MutableMap<Int, Int> = HashMap()
for (i in nums.indices) {
val complement = target - nums[i]
if (map.containsKey(complement)) {
return@TwoSumStrategy intArrayOf(map.getOrDefault(complement, 0), i)
}
map[nums[i]] = i
}
return@TwoSumStrategy intArrayOf()
}
/**
* Approach 4: Kotlin style One-pass Hash Table
* Time complexity: O(n).
* Space complexity: O(n).
*/
val twoSumOneHashMap = TwoSumStrategy { nums: IntArray, target: Int ->
val map: MutableMap<Int, Int> = HashMap()
nums.forEachIndexed { index, i ->
map[i]?.let { return@TwoSumStrategy intArrayOf(it, index) }
map[target - i] = index
}
return@TwoSumStrategy intArrayOf()
}
| 2 | Kotlin | 1 | 9 | 6a2d7ed76e2d88a3446f6558109809c318780e2c | 3,503 | the-algorithms | MIT License |
src/main/kotlin/dev/bogwalk/util/custom/SuDokuGame.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.util.custom
/**
* A class representing a Su Doku puzzle grid, with each cell value stored as a Set, so that
* options can be iterated over until a final value remains.
*/
class SuDokuGame(input: List<String>) {
private var puzzleCells: Array<Array<Set<Int>>>
private val hasUnfilledCells: Boolean
get() = puzzleCells.flatten().any { it.size != 1 }
init {
require(input.size == 9) { "Su Doku grid requires 9 rows" }
require(input.all { it.length == 9 && it.all { ch -> ch.isDigit() } }) {
"Input contains invalid characters"
}
puzzleCells = Array(9) { r ->
Array(9) { c ->
val digit = input[r][c].digitToInt()
if (digit != 0) setOf(digit) else setOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
}
}
}
fun getGrid(withOptions: Boolean = false): List<String> {
return if (withOptions) {
puzzleCells.map { it.joinToString("") }
} else {
puzzleCells.map { it.joinToString("") { s ->
if (s.size == 1) s.single().toString() else "0"
} }
}
}
/**
* Solves puzzle by attempting to reduce all possible values, until no changes are made, then
* a guess is made. So few puzzles make it to the guess stage, but the latter could
* potentially be optimised by finding the first unsolved cell with the least options.
*/
fun solve(): Boolean {
val (wasUpdated, isValid) = reduce()
if (!isValid) return false
if (!wasUpdated) {
val ogVersion = puzzleCells.map { it.toList() }
for (row in 0..8) {
for (col in 0..8) {
if (puzzleCells[row][col].size == 1) continue
val guesses = puzzleCells[row][col]
for (guess in guesses) {
puzzleCells[row][col] = setOf(guess)
clearDigits(row, col, setOf(guess))
if (solve() && puzzleCells.all { it.toSet().size == 9 }) {
return true
}
puzzleCells = Array(9) { r -> Array(9) { c-> ogVersion[r][c] } }
}
}
}
}
return true
}
fun reduce(): Pair<Boolean, Boolean> {
while (hasUnfilledCells) {
var updated = false
for (row in 0..8) {
for (col in 0..8) {
if (puzzleCells[row][col].size == 1) continue
val filtered = puzzleCells[row][col].gridFilter(row, col)
if (filtered.isEmpty()) return updated to false
puzzleCells[row][col] = filtered
if (filtered.size == 1) {
updated = true
clearDigits(row, col, filtered)
}
}
}
if (!updated) updated = clearByAssumption()
if (!updated) updated = clearByPairAssumption()
if (!updated) return false to true
}
return true to true
}
/**
* For situations when potential values in a box exist on a single column/row, thereby
* assuring that that column/row must contain the value. This assumption can be used to reduce
* set options in the corresponding column/row outside the box.
*/
private fun clearByAssumption(): Boolean {
var changed = false
for (boxI in 0..8) {
val (topRow, topCol) = boxI / 3 * 3 to boxI % 3 * 3
val rowOptions = List(3) {
puzzleCells[topRow + it].slice(topCol..topCol + 2).filter { s -> s.size > 1 }
}
val colOptions = List(3) {
listOf(puzzleCells[topRow][topCol + it], puzzleCells[topRow+1][topCol + it],
puzzleCells[topRow+2][topCol + it]).filter { s -> s.size > 1 }
}
for ((i, row) in rowOptions.withIndex()) {
if (row.size > 1) {
val options = row.reduce(Set<Int>::union)
val others = ((topRow..topRow + 2).toSet() - (topRow + i))
.flatMap { rowOptions[it % 3] }
val outliers = if (others.isEmpty()) options else options - others.reduce(Set<Int>::union)
if (outliers.isEmpty()) continue
if (clearDigits(
topRow + i, topCol, outliers, clearBox = false, clearCol = false
)) changed = true
}
}
for ((i, col) in colOptions.withIndex()) {
if (col.size > 1) {
val options = col.reduce(Set<Int>::union)
val others = ((topCol..topCol + 2).toSet() - (topCol + i))
.flatMap { colOptions[it % 3] }
val outliers = if (others.isEmpty()) options else options - others.reduce(Set<Int>::union)
if (outliers.isEmpty()) continue
if (clearDigits(
topRow, topCol + i, outliers, clearBox = false, clearRow = false
)) changed = true
}
}
}
return changed
}
/**
* For situations when potential values in a box exist as a pair; i.e. choosing one in a
* cell means the other cell must contain the other. If 2 cells have identical sets
* containing only 2 values, these values can be filtered from all other cells in the box.
* Could then be followed by another call to clearByAssumption() but this eventually occurs.
*/
private fun clearByPairAssumption(): Boolean {
var changed = false
for (boxI in 0..8) {
val (topRow, topCol) = boxI / 3 * 3 to boxI % 3 * 3
val emptyPairCells = List(9) { puzzleCells[topRow + it / 3][topCol + it % 3] }
.filter { it.size == 2 }
for (pair in emptyPairCells.distinct()) {
if (emptyPairCells.count { it == pair } == 2) {
for (i in 0..8) {
val cell = puzzleCells[topRow + i / 3][topCol + i % 3]
if (cell.size == 1 || cell == pair) continue
val cleared = cell - pair
if (cleared.size < cell.size) {
puzzleCells[topRow + i / 3][topCol + i % 3] = cleared
changed = true
if (cleared.size == 1) {
clearDigits(topRow + i / 3, topCol + i % 3, cleared)
}
}
}
}
}
}
return changed
}
/**
* Accesses the row, column, and box cells associated with a cell at [rowI][colI] and
* performs 2 actions:
* - Reduces the set of possible values based on already filled cell values.
* - Checks if the newly reduced set contains a value that is not present in any of the
* other cells for each group. This will be returned as a priority; otherwise, the
* reduced set will be returned.
*/
private fun Set<Int>.gridFilter(rowI: Int, colI: Int): Set<Int> {
val (rowF, rowE) = puzzleCells[rowI]
.filterIndexed { i, _ -> i != colI }
.partition { it.size == 1 }
val (colF, colE) = List(9) {
if (it != rowI) puzzleCells[it][colI] else emptySet()
}.partition { it.size == 1 }
val boxValues = mutableListOf<Set<Int>>()
val (topRow, topCol) = rowI / 3 * 3 to colI / 3 * 3
for (row in topRow..topRow + 2) {
if (row == rowI) {
val others = (topCol..topCol + 2).toSet() - colI
boxValues.addAll(others.map { puzzleCells[row][it] })
} else {
boxValues.addAll(puzzleCells[row].slice(topCol..topCol + 2))
}
}
val (boxF, boxE) = boxValues.partition { it.size == 1 }
val reduced = this - (boxF.flatten() union rowF.flatten() union colF.flatten())
for (group in listOf(boxE.flatten(), rowE.flatten(), colE.flatten())) {
val single = reduced - group.toSet()
if (single.size == 1) return single
}
return reduced
}
/**
* Supplementary action that clears the value of a newly filled cell from all associated row,
* column, and box cells. Speed has not been compared, but introducing this second step
* reduced the overall amount of iterations over the entire puzzle grid.
*/
private fun clearDigits(
rowI: Int, colI: Int, digits: Set<Int>,
clearBox: Boolean = true, clearRow: Boolean = true, clearCol: Boolean = true
): Boolean {
var changed = false
val (topRow, topCol) = rowI / 3 * 3 to colI / 3 * 3
val boxRowRange = topRow..topRow + 2
val boxColRange = topCol..topCol + 2
for (i in 0..8) {
var cleared: Set<Int>
if (clearBox) {
if (puzzleCells[i / 3 + topRow][i % 3 + topCol].size > 1) {
cleared = puzzleCells[i / 3 + topRow][i % 3 + topCol] - digits
puzzleCells[i / 3 + topRow][i % 3 + topCol] = cleared
if (cleared.size == 1) {
changed = true
clearDigits(i / 3 + topRow, i % 3 + topCol, cleared)
}
}
}
if (clearRow) {
if (i !in boxColRange && puzzleCells[rowI][i].size > 1) {
cleared = puzzleCells[rowI][i] - digits
puzzleCells[rowI][i] = cleared
if (cleared.size == 1) {
changed = true
clearDigits(rowI, i, cleared)
}
}
}
if (clearCol) {
if (i !in boxRowRange && puzzleCells[i][colI].size > 1) {
cleared = puzzleCells[i][colI] - digits
puzzleCells[i][colI] = cleared
if (cleared.size == 1) {
changed = true
clearDigits(i, colI, cleared)
}
}
}
}
return changed
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 10,499 | project-euler-kotlin | MIT License |
src/main/kotlin/ru/timakden/aoc/year2022/Day24.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2022
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
import kotlin.math.abs
/**
* [Day 24: <NAME>](https://adventofcode.com/2022/day/24).
*/
object Day24 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2022/Day24")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
val walls = mutableSetOf<Vector>()
val blizzards = mutableListOf<Pair<Vector, Char>>()
val tiles = mutableSetOf<Vector>()
var y = 0
var start = Vector(0, 0)
var goal = Vector(0, 0)
input.forEach { line ->
line.indices.forEach { i ->
when (line[i]) {
'#' -> walls += Vector(i, y)
'>', '<', '^', 'v' -> {
blizzards += Vector(i, y) to line[i]
tiles += Vector(i, y)
}
'.' -> {
tiles += Vector(i, y)
if (y == 0) start = Vector(i, y)
if (y == input.lastIndex) goal = Vector(i, y)
}
}
}
++y
}
return traverse(start, goal, walls, blizzards, tiles)
}
fun part2(input: List<String>): Int {
val walls = mutableSetOf<Vector>()
val blizzards = mutableListOf<Pair<Vector, Char>>()
val tiles = mutableSetOf<Vector>()
var y = 0
var start = Vector(0, 0)
var goal = Vector(0, 0)
input.forEach { line ->
line.indices.forEach { i ->
when (line[i]) {
'#' -> walls += Vector(i, y)
'>', '<', '^', 'v' -> {
blizzards += Vector(i, y) to line[i]
tiles += Vector(i, y)
}
'.' -> {
tiles += Vector(i, y)
if (y == 0) start = Vector(i, y)
if (y == input.lastIndex) goal = Vector(i, y)
}
}
}
++y
}
return traverse(start, goal, walls, blizzards, tiles) + traverse(goal, start, walls, blizzards, tiles) +
traverse(start, goal, walls, blizzards, tiles)
}
private fun traverse(
start: Vector,
goal: Vector,
walls: MutableSet<Vector>,
blizzards: MutableList<Pair<Vector, Char>>,
tiles: MutableSet<Vector>
): Int {
var time = 0
val players = mutableSetOf<Vector>()
players += start
val ans: Int
outer@ while (true) {
++time
blizzards.indices.forEach { i ->
var mov = when (blizzards[i].second) {
'>' -> Vector(1, 0)
'<' -> Vector(-1, 0)
'v' -> Vector(0, 1)
else -> Vector(0, -1)
}
if (blizzards[i].first + mov !in walls) {
blizzards[i] = blizzards[i].first + mov to blizzards[i].second
} else {
mov = -mov
do {
blizzards[i] = blizzards[i].first + mov to blizzards[i].second
} while (blizzards[i].first + mov !in walls)
}
}
val newPlayers = mutableSetOf<Vector>()
players.forEach { player ->
listOf(Vector(1, 0), Vector(-1, 0), Vector(0, -1), Vector(0, 1), Vector(0, 0)).forEach { mov ->
if (player + mov !in walls &&
player + mov in tiles &&
!blizzards.any { p -> p.first == player + mov }
) {
newPlayers += player + mov
}
}
}
players.clear()
val sortedPlayers = newPlayers.sortedBy { p -> abs(p.x - goal.x) + abs(p.y + goal.y) }.toList()
for (i in sortedPlayers.indices) {
if (i >= 2000)
break
if (sortedPlayers[i].x == goal.x && sortedPlayers[i].y == goal.y) {
ans = time
break@outer
}
players += sortedPlayers[i]
}
}
return ans
}
data class Vector(var x: Int, var y: Int) {
operator fun plus(b: Vector) = Vector(x + b.x, y + b.y)
operator fun minus(b: Vector) = Vector(x - b.x, y - b.y)
operator fun times(c: Int) = Vector(x * c, y * c)
operator fun unaryMinus() = Vector(-x, -y)
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 4,825 | advent-of-code | MIT License |
Problem Solving/Algorithms/Basic - Day of the Programmer.kt | MechaArms | 525,331,223 | false | {"Kotlin": 30017} | /*
Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700.
From 1700 to 1917, Russia's official calendar was the Julian calendar; since 1919 they used the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that in 1918, February 14th was the 32nd day of the year in Russia.
In both calendar systems, February is the only month with a variable amount of days; it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4; in the Gregorian calendar, leap years are either of the following:
Divisible by 400.
Divisible by 4 and not divisible by 100.
Given a year, y, find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.
For example, the given year = 1984. 1984 is divisible by 4, so it is a leap year. The 256th day of a leap year after 1918 is September 12, so the answer is 12.09.1984.
Function Description
Complete the dayOfProgrammer function in the editor below. It should return a string representing the date of the 256th day of the year given.
dayOfProgrammer has the following parameter(s):
year: an integer
Input Format
A single integer denoting year y.
Constraints
1700 \le y \le 2700
Output Format
Print the full date of Day of the Programmer during year y in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.
Sample Input 0
2017
Sample Output 0
13.09.2017
Explanation 0
In the year y = 2017, January has 31 days, February has 28 days, March has 31 days, April has 30 days, May has 31 days, June has 30 days, July has 31 days, and August has 31 days. When we sum the total number of days in the first eight months, we get 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 = 243. Day of the Programmer is the 256th day, so then calculate 256 - 243 = 13 to determine that it falls on day 13 of the 9th month (September). We then print the full date in the specified format, which is 13.09.2017.
Sample Input 1
2016
Sample Output 1
12.09.2016
Explanation 1
Year y = 2016 is a leap year, so February has 29 days but all the other months have the same number of days as in 2017. When we sum the total number of days in the first eight months, we get 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 = 244. Day of the Programmer is the 256th day, so then calculate 256 - 244 = 12 to determine that it falls on day 12 of the 9th month (September). We then print the full date in the specified format, which is 12.09.2016.
Sample Input 2
1800
Sample Output 2
12.09.1800
Explanation 2
Since 1800 is leap year as per Julian calendar. Day lies on 12 September.
*/
//My Solution
//===========
fun dayOfProgrammer(year: Int): String {
var result = ""
if (year >= 1700 && year <= 1917) {
result = if (year%4 == 0) "12.09.$year" else "13.09.$year"
} else if (year == 1918) {
result = "26.09.$year"
} else {
if (year%400 == 0) {
result = "12.09.$year"
} else if (year%4==0 && year%100 != 0) {
result = "12.09.$year"
} else {
result = "13.09.$year"
}
}
return result
}
fun main(args: Array<String>) {
val year = readLine()!!.trim().toInt()
val result = dayOfProgrammer(year)
println(result)
}
//Best Solution
//=============
fun dayOfProgrammer(year: Int): String {
if(year% 4 == 0 && (year < 1918 || year % 400 == 0 || year % 100 != 0))
return "12.09.$year"
else if(year == 1918)
return "26.09.$year"
else
return "13.09.$year"
}
fun main(args: Array<String>) {
val year = readLine()!!.trim().toInt()
val result = dayOfProgrammer(year)
println(result)
}
| 0 | Kotlin | 0 | 1 | eda7f92fca21518f6ee57413138a0dadf023f596 | 4,079 | My-HackerRank-Solutions | MIT License |
src/main/kotlin/com/askrepps/advent2021/day10/Day10.kt | askrepps | 726,566,200 | false | {"Kotlin": 302802} | /*
* MIT License
*
* Copyright (c) 2021-2023 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.askrepps.advent.advent2021.day10
import com.askrepps.advent.util.getInputLines
import java.io.File
private val OPENING_CHARACTERS = setOf('(', '[', '{', '<')
private val MATCHING_CHARACTERS = mapOf(
'(' to ')',
'[' to ']',
'{' to '}',
'<' to '>',
')' to '(',
']' to '[',
'}' to '{',
'>' to '<'
)
private val ILLEGAL_CHARACTER_SCORES = mapOf(
')' to 3L,
']' to 57L,
'}' to 1197L,
'>' to 25137L
)
private val COMPLETION_CHARACTER_SCORES = mapOf(
'(' to 1L,
'[' to 2L,
'{' to 3L,
'<' to 4L
)
data class LineResult(val score: Long, val isCorrupt: Boolean)
fun String.scoreLine(): LineResult {
val stack = mutableListOf<Char>()
for (c in this) {
when (c) {
in OPENING_CHARACTERS -> stack.add(c)
else -> {
if (stack.isEmpty() || stack.removeLast() != MATCHING_CHARACTERS[c]) {
val corruptionScore = ILLEGAL_CHARACTER_SCORES[c]
?: throw IllegalStateException("Unexpected char '$c'")
return LineResult(corruptionScore, isCorrupt = true)
}
}
}
}
val completionScore = stack.foldRight(0L) { c, score ->
val value = COMPLETION_CHARACTER_SCORES[c]
?: throw IllegalStateException("Unexpected stack char '$c'")
score * 5L + value
}
return LineResult(completionScore, isCorrupt = false)
}
fun List<String>.partitionResults() =
map { it.scoreLine() }
.partition { it.isCorrupt }
fun getPart1Answer(corruptResults: List<LineResult>) =
corruptResults.sumOf { it.score }
fun getPart2Answer(incompleteResults: List<LineResult>) =
incompleteResults.sortedBy { it.score }
.let { it[it.size / 2].score }
fun main() {
val (corruptResults, incompleteResults) = File("src/main/resources/2021/input-2021-day10.txt")
.getInputLines()
.partitionResults()
println("The answer to part 1 is ${getPart1Answer(corruptResults)}")
println("The answer to part 2 is ${getPart2Answer(incompleteResults)}")
}
| 0 | Kotlin | 0 | 0 | 89de848ddc43c5106dc6b3be290fef5bbaed2e5a | 3,256 | advent-of-code-kotlin | MIT License |
src/main/euler/solved/Task_536.kt | dzmitry-paulenka | 24,504,894 | false | {"Java": 805518, "Kotlin": 23071, "C#": 21356, "Ruby": 17045, "Scala": 6559, "Python": 4465, "Mathematica": 3529, "JavaScript": 1215, "Lua": 1075} | package solved
import tasks.AbstractTask
import tasks.Tester
import utils.MyMath
import utils.log.Logger
//Answer : 3557005261906288
class Task_536 : AbstractTask() {
val LIM = 1000000L;
// val LIM = 1000000000000L;
var sum = 11L;
var maxprime = 0L;
var primes: LongArray = LongArray(0);
var factors: LongArray = LongArray(0);
var isPrime: BooleanArray = BooleanArray(0);
override fun solving() {
MyMath.setMaxPrimesToCache(80000);
primes = MyMath.getPrimesBetween(0, Math.sqrt((LIM + 4).toDouble()).toLong() + 3L)
maxprime = primes.last()
factors = LongArray(primes.size);
isPrime = BooleanArray(maxprime.toInt() + 1)
for (p in primes) {
isPrime[p.toInt()] = true
}
println("go")
find(0, 1, 1L)
println(sum);
}
fun find(factInd: Int, ind: Int, n: Long) {
if (ind == primes.size) {
return;
}
if (factInd > 0) {
// solving n*x ≡ -3 (mod q-1), q is largest factor, than x is the next factor
// 1st case 3!|n and 3!|q-1 => n * x - k * (q-1) = -3
// 2nd case 3|n and 3|q-1 => (n/3)*x - k*(q-1)/3 = -1
val x: Long;
val g: Long;
val lastFactor = factors[factInd - 1]
var q = lastFactor - 1;
if (n % 3 == 0L && q % 3 == 0L) {
// x = -(n/3)^(-1) (mod (q-1)/3), n%3 == 0 && q-1 % 3 == 0
q /= 3;
val rr = MyMath.modInverseWithRem(n / 3 % q, q);
x = q - rr[1]
g = rr[0]
} else {
// x = -3*n^(-1) (mod q-1), n%3 != 0 || q-1 % 3 != 0
val rr = MyMath.modInverseWithRem(n % q, q);
x = (q - 3) * rr[1] % q;
g = rr[0]
}
if (g == 1L) {
// so possible future numbers are nn = x + k * q
// but also nn = n * prime, and prime > lastFactor
// find min candidate
var minprime = primes[ind];
var candidate = minprime / q * q + x;
if (candidate < minprime) {
candidate += q;
}
var nn = n * candidate;
TOP@ while (nn <= LIM && candidate <= maxprime) {
if (isPrime[candidate.toInt()]) {
if ((nn + 3) % (candidate - 1) != 0L) {
candidate += q;
nn = n * candidate
continue;
}
for (i in 0..factInd - 1) {
if ((nn + 3) % (factors[i] - 1) != 0L) {
candidate += q;
nn = n * candidate
continue@TOP;
}
}
sum += nn;
}
candidate += q;
nn = n * candidate
}
}
}
for (i in ind..primes.size - 1) {
var prime = primes[i];
var nn = n * prime;
if (nn * prime > LIM) {
break;
}
factors[factInd] = prime;
find(factInd + 1, i + 1, nn);
}
}
companion object {
@JvmStatic fun main(args: Array<String>) {
Logger.init("default.log")
Tester.test(Task_536())
Logger.close()
}
}
}
| 0 | Java | 0 | 0 | 1af096219a86d173ebcb23265885ab309802987d | 3,598 | project-euler | MIT License |
aoc-kotlin/src/main/kotlin/day08/Day08.kt | mahpgnaohhnim | 573,579,334 | false | {"Kotlin": 29246, "TypeScript": 1975, "Go": 1693, "Rust": 1520, "JavaScript": 123} | package day08
import java.io.File
class Day08 {
companion object {
val inputFile = File(this::class.java.getResource("input.txt")?.path.orEmpty())
fun countVisibleTrees(inputText: String): Int {
val data = createTreeList(inputText)
val visibleTrees = data.filter { it.visible ?: false }
return visibleTrees.size
}
fun getHighestScenicScore(inputText: String): Int {
val data = createTreeList(inputText)
return data.maxOf { it.scenicScore }
}
private fun createTreeList(inputText: String): List<Tree> {
val allTrees = inputText.lines().mapIndexed { index, line -> parseLine(line, index) }.flatten()
allTrees.forEach { findVisibility(it, allTrees) }
allTrees.forEach { calculateScenicScore(it, allTrees) }
return allTrees
}
private fun parseLine(line: String, rowIndex: Int): List<Tree> {
return line.mapIndexed { colIndex, c ->
Tree(
id = "$rowIndex$colIndex",
rowIndex = rowIndex,
colIndex = colIndex,
height = c.digitToInt()
)
}
}
private fun findVisibility(currentTree: Tree, allTrees: List<Tree>) {
val leftNeighbors =
allTrees.filter { it.rowIndex == currentTree.rowIndex && it.colIndex < currentTree.colIndex }
val rightNeighbors =
allTrees.filter { it.rowIndex == currentTree.rowIndex && it.colIndex > currentTree.colIndex }
val neighborsAbove =
allTrees.filter { it.rowIndex < currentTree.rowIndex && it.colIndex == currentTree.colIndex }
val neighborsBelow =
allTrees.filter { it.rowIndex > currentTree.rowIndex && it.colIndex == currentTree.colIndex }
val visibleAbove = neighborsAbove.isEmpty() || !neighborsAbove.any { it.height >= currentTree.height }
val visibleBelow = neighborsBelow.isEmpty() || !neighborsBelow.any { it.height >= currentTree.height }
val visibleFromLeft = leftNeighbors.isEmpty() || !leftNeighbors.any { it.height >= currentTree.height }
val visibleFromRight = rightNeighbors.isEmpty() || !rightNeighbors.any { it.height >= currentTree.height }
currentTree.visible = visibleAbove || visibleBelow || visibleFromLeft || visibleFromRight
}
private fun calculateScenicScore(currentTree: Tree, allTrees: List<Tree>) {
val colLength = allTrees.maxOf { it.colIndex }
val rowLength = allTrees.maxOf { it.rowIndex }
val unblockedTopTree = mutableSetOf<Tree>()
val unblockedBottomTree = mutableSetOf<Tree>()
val unblockedRightTree = mutableSetOf<Tree>()
val unblockedLeftTree = mutableSetOf<Tree>()
for (i in currentTree.rowIndex downTo 0) {
val targetTree = allTrees.find { it.rowIndex == i && it.colIndex == currentTree.colIndex } ?: continue
if (targetTree.id == currentTree.id) {
continue
}
unblockedTopTree.add(targetTree)
if (targetTree.height >= currentTree.height) {
break
}
}
for (i in currentTree.rowIndex..rowLength) {
val targetTree = allTrees.find { it.rowIndex == i && it.colIndex == currentTree.colIndex } ?: continue
if (targetTree.id == currentTree.id) {
continue
}
unblockedBottomTree.add(targetTree)
if (targetTree.height >= currentTree.height) {
break
}
}
for (i in currentTree.colIndex downTo 0) {
val targetTree = allTrees.find { it.rowIndex == currentTree.rowIndex && it.colIndex == i } ?: continue
if (targetTree.id == currentTree.id) {
continue
}
unblockedLeftTree.add(targetTree)
if (targetTree.height >= currentTree.height) {
break
}
}
for (i in currentTree.colIndex..colLength) {
val targetTree = allTrees.find { it.rowIndex == currentTree.rowIndex && it.colIndex == i } ?: continue
if (targetTree.id == currentTree.id) {
continue
}
unblockedRightTree.add(targetTree)
if (targetTree.height >= currentTree.height) {
break
}
}
currentTree.scenicScore =
unblockedTopTree.size * unblockedBottomTree.size * unblockedLeftTree.size * unblockedRightTree.size
}
}
}
fun main() {
val resultPart1 = Day08.countVisibleTrees(Day08.inputFile.readText())
val resultPart2 = Day08.getHighestScenicScore(Day08.inputFile.readText())
println(
"""
resultPart1:
$resultPart1
resultPart2:
$resultPart2
""".trimIndent()
)
} | 0 | Kotlin | 0 | 0 | c514152e9e2f0047514383fe536f7610a66aff70 | 5,224 | aoc-2022 | MIT License |
src/main/kotlin/days/Day10.kt | andilau | 573,139,461 | false | {"Kotlin": 65955} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2022/day/10",
date = Date(day = 10, year = 2022)
)
class Day10(val input: List<String>) : Puzzle {
private val instructions = input
.map { line -> line.substringBefore(' ') to (line.substringAfter(' ').toIntOrNull() ?: 0) }
private val cycles = setOf<Int>(20, 60, 100, 140, 180, 220)
override fun partOne(): Int {
var cycle = 1
var regX = 1
var sum = 0
for ((op, v) in instructions) {
when (op) {
"addx" -> {
repeat(2) {
if (cycle in cycles) sum += cycle * regX
cycle++;
}
regX += v
}
"noop" -> {
if (cycle in cycles) sum += cycle * regX
cycle++
}
}
}
return sum
}
override fun partTwo(): String {
val crt = BooleanArray(240)
var cycle = 1
var regX = 1
for ((op, v) in instructions) {
when (op) {
"noop" -> {
crt[cycle - 1] = (cycle - 1) % 40 in (regX - 1)..(regX + 1)
cycle++
}
"addx" -> {
repeat(2) {
crt[cycle - 1] = (cycle - 1) % 40 in (regX - 1)..(regX + 1)
cycle++
}
regX += v
}
}
}
return crt.map { if (it) '#' else '.' }.joinToString("").chunked(40).joinToString("\n")
}
}
| 0 | Kotlin | 0 | 0 | da824f8c562d72387940844aff306b22f605db40 | 1,691 | advent-of-code-2022 | Creative Commons Zero v1.0 Universal |
2021/src/test/kotlin/Day05.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import Util.towards
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertEquals
class Day05 {
data class Coord(val x: Int, val y: Int)
@Test
fun `run part 01`() {
val overlaps = getCoords().calcOverlaps()
assertEquals(8111, overlaps)
}
@Test
fun `run part 02`() {
val overlaps = getCoords().calcOverlaps(true)
assertEquals(22088, overlaps)
}
private fun getCoords() = Util.getInputAsListOfString("day05-input.txt")
.map {
it.split(" ", ",").let { s ->
Coord(s[0].toInt(), s[1].toInt()) to Coord(s[3].toInt(), s[4].toInt())
}
}
private fun List<Pair<Coord, Coord>>.calcOverlaps(includeDiagonals: Boolean = false) = this
.flatMap {
if (it.first.x == it.second.x)
(it.first.y towards it.second.y).map { y -> Coord(it.first.x, y) }
else if (it.first.y == it.second.y)
(it.first.x towards it.second.x).map { x -> Coord(x, it.first.y) }
else if (includeDiagonals && abs(it.first.x - it.second.x) == abs(it.first.y - it.second.y))
(it.first.x towards it.second.x).mapIndexed { index, x ->
Coord(x, (it.first.y towards it.second.y).elementAt(index))
}
else
listOf()
}
.groupingBy { it }
.eachCount()
.count { it.value >= 2 }
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 1,457 | adventofcode | MIT License |
kotest-assertions/kotest-assertions-core/src/commonMain/kotlin/io/kotest/matchers/ranges/Range.kt | kotest | 47,071,082 | false | {"Kotlin": 4460715, "CSS": 352, "Java": 145} | package io.kotest.matchers.ranges
data class Range<T: Comparable<T>>(
val start: RangeEdge<T>,
val end: RangeEdge<T>
) {
init {
require(start.value <= end.value) {
"${start.value} cannot be after ${end.value}"
}
}
override fun toString(): String {
return "${if(start.edgeType == RangeEdgeType.INCLUSIVE) "[" else "("}${start.value}, ${end.value}${if(end.edgeType == RangeEdgeType.INCLUSIVE) "]" else ")"}"
}
fun isEmpty() = start.value == end.value && (
start.edgeType == RangeEdgeType.EXCLUSIVE ||
end.edgeType == RangeEdgeType.EXCLUSIVE
)
fun intersect(other: Range<T>): Boolean = !this.lessThan(other) && !other.lessThan(this)
fun lessThan(other: Range<T>): Boolean {
val endOfThis: T = this.end.value
val startOfOther: T = other.start.value
return when {
(this.end.edgeType== RangeEdgeType.INCLUSIVE && other.start.edgeType == RangeEdgeType.INCLUSIVE) -> (endOfThis < startOfOther)
else -> (endOfThis <= startOfOther)
}
}
fun greaterThan(other: Range<T>) = other.lessThan(this)
companion object {
fun<T: Comparable<T>> ofClosedRange(range: ClosedRange<T>) = Range(
start = RangeEdge(range.start, RangeEdgeType.INCLUSIVE),
end = RangeEdge(range.endInclusive, RangeEdgeType.INCLUSIVE)
)
@OptIn(ExperimentalStdlibApi::class)
fun<T: Comparable<T>> ofOpenEndRange(range: OpenEndRange<T>) = Range(
start = RangeEdge(range.start, RangeEdgeType.INCLUSIVE),
end = RangeEdge(range.endExclusive, RangeEdgeType.EXCLUSIVE)
)
fun<T: Comparable<T>> openOpen(start: T, end: T) = Range(
start = RangeEdge(start, RangeEdgeType.EXCLUSIVE),
end = RangeEdge(end, RangeEdgeType.EXCLUSIVE)
)
fun<T: Comparable<T>> openClosed(start: T, end: T) = Range(
start = RangeEdge(start, RangeEdgeType.EXCLUSIVE),
end = RangeEdge(end, RangeEdgeType.INCLUSIVE)
)
fun<T: Comparable<T>> closedOpen(start: T, end: T) = Range(
start = RangeEdge(start, RangeEdgeType.INCLUSIVE),
end = RangeEdge(end, RangeEdgeType.EXCLUSIVE)
)
fun<T: Comparable<T>> closedClosed(start: T, end: T) = Range(
start = RangeEdge(start, RangeEdgeType.INCLUSIVE),
end = RangeEdge(end, RangeEdgeType.INCLUSIVE)
)
}
}
enum class RangeEdgeType { INCLUSIVE, EXCLUSIVE }
data class RangeEdge<T: Comparable<T>>(val value: T, val edgeType: RangeEdgeType)
| 102 | Kotlin | 615 | 4,198 | 7fee2503fbbdc24df3c594ac6b240c11b265d03e | 2,535 | kotest | Apache License 2.0 |
src/main/java/kt/day1/LargestTimeForGivenDigits.kt | surya-uppuluri | 292,050,828 | false | {"Java": 9862, "Kotlin": 5746} | package kt.day1
import jv.day1.prerequisites.PermutationGenerator
import lombok.extern.slf4j.Slf4j
import java.util.*
@Slf4j
class LargestTimeForGivenDigits {
/**
* 949. Largest Time for Given Digits
* Easy
*
*
* 271
*
*
* 565
*
*
* Add to List
*
*
* Share
* Given an array of 4 digits, return the largest 24 hour time that can be made.
*
*
* The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.
*
*
* Return the answer as a string of length 5. If no valid time can be made, return an empty string.
*
*
*
*
*
*
* Example 1:
*
*
* Input: [1,2,3,4]
* Output: "23:41"
* Example 2:
*
*
* Input: [5,5,5,5]
* Output: ""
*
*
*
*
* Note:
*
*
* A.length == 4
* 0 <= A[i] <= 9
*/
fun largestTimeFromDigits(input: IntArray?): String {
val permutationGenerator = PermutationGenerator()
val permutations = permutationGenerator.generatePermutations(input)
val validTimes: MutableList<String> = ArrayList()
for (permutation in permutations) {
val permutedString = getStringFromList(permutation)
if (isValidTime(permutedString)) {
validTimes.add(permutedString)
}
}
validTimes.sortWith(Collections.reverseOrder())
var res = ""
if (validTimes.size > 0) {
val longestTime = validTimes[0]
res = longestTime.substring(0, 2) + ":" + longestTime.substring(2) //format the result in HH:MM format
}
return res
}
private fun isValidTime(permutedString: String): Boolean {
if (permutedString[0] > '2') return false //3H:MM is just invalid
if (permutedString[0] == '2') { //23:MM case
if (permutedString[1] > '3') return false
}
return if (permutedString[2] > '5') false else true //HH:5M is max possible, then it should get reset. SHould be really careful in char comparison. Compare with '5' not 5
//log.info("Returning true");
}
private fun getStringFromList(permutation: List<Int>): String {
var s = ""
for (i in permutation.indices) s += permutation[i]
return s
}
} | 0 | Java | 0 | 0 | 5cddbecb5502294537137b6864aaf54eb001be5d | 2,432 | september-leetcode-challenge | Apache License 2.0 |
app/src/main/kotlin/aoc2021/day10/NavigationLine.kt | dbubenheim | 435,284,482 | false | {"Kotlin": 31242} | package aoc2021.day10
import kotlin.streams.asSequence
data class NavigationLine(val value: String) {
val syntaxCheck: SyntaxCheck = value.checkSyntax()
override fun toString(): String = "$value: $syntaxCheck"
}
private fun String.checkSyntax(): SyntaxCheck {
val errorScores: Map<Char, Int> = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137,
)
val middleScores: Map<Char, Long> = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
val openers = listOf('(', '{', '[', '<')
val closerToOpener = mapOf(
')' to '(',
'}' to '{',
']' to '[',
'>' to '<'
)
val openerToCloser = closerToOpener.entries.associate { (k, v) -> v to k }
val openingStack = ArrayDeque<Char>()
val errorScore = chars()
.asSequence()
.map { it.toChar() }
.firstOrNull { character ->
val isClosing = character !in openers
if (!isClosing) openingStack.addFirst(character)
isClosing && closerToOpener[character] != openingStack.removeFirst()
}
?.let { errorScores[it] } ?: 0
val hasIncorrectChar = errorScore > 0
val middleScore = if (hasIncorrectChar) 0 else chars()
.asSequence()
.map { it.toChar() }
.fold(ArrayDeque<Char>()) { queue, character ->
val isClosing = character !in openers
if (!isClosing) queue.addFirst(character) else queue.removeFirst()
queue
}
.mapNotNull { openerToCloser[it] }
.also { println(it) }
.fold(0L) { score, char -> score * 5 + (middleScores[char] ?: 0) }
return SyntaxCheck(errorScore > 0, errorScore, middleScore)
}
| 9 | Kotlin | 0 | 0 | 83a93845ebbc1a6405f858214bfa79b3448b932c | 1,752 | advent-of-code-2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinPairSum.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 1877. Minimize Maximum Pair Sum in Array
* @see <a href="https://leetcode.com/problems/minimize-maximum-pair-sum-in-array">Source</a>
*/
fun interface MinPairSum {
operator fun invoke(nums: IntArray): Int
}
class MinPairSumSorting : MinPairSum {
override fun invoke(nums: IntArray): Int {
nums.sort()
var maxSum = 0
val n = nums.size
for (i in 0 until n / 2) {
val currentSum = nums[i] + nums[n - 1 - i]
maxSum = maxOf(maxSum, currentSum)
}
return maxSum
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,197 | kotlab | Apache License 2.0 |
src/main/kotlin/g2001_2100/s2096_step_by_step_directions_from_a_binary_tree_node_to_another/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2096_step_by_step_directions_from_a_binary_tree_node_to_another
// #Medium #String #Depth_First_Search #Tree #Binary_Tree
// #2023_06_28_Time_690_ms_(93.33%)_Space_95.9_MB_(66.67%)
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 {
private fun find(n: TreeNode?, `val`: Int, sb: StringBuilder): Boolean {
if (n!!.`val` == `val`) {
return true
}
if (n.left != null && find(n.left, `val`, sb)) {
sb.append("L")
} else if (n.right != null && find(n.right, `val`, sb)) {
sb.append("R")
}
return sb.isNotEmpty()
}
fun getDirections(root: TreeNode?, startValue: Int, destValue: Int): String {
val s = StringBuilder()
val d = StringBuilder()
find(root, startValue, s)
find(root, destValue, d)
var i = 0
val maxI = d.length.coerceAtMost(s.length)
while (i < maxI && s[s.length - i - 1] == d[d.length - i - 1]) {
++i
}
val result = StringBuilder()
for (j in 0 until s.length - i) {
result.append("U")
}
result.append(d.reverse().substring(i))
return result.toString()
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,428 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/info/jukov/adventofcode/y2022/Day16.kt | jukov | 572,271,165 | false | {"Kotlin": 78755} | package info.jukov.adventofcode.y2022
import info.jukov.adventofcode.Day
import info.jukov.adventofcode.util.fixHashCode
import java.io.BufferedReader
import kotlin.math.max
class Day16 : Day() {
override val year: Int = 2022
override val day: Int = 16
private val cache1 = HashMap<CacheKey1, Int>()
private val cache2 = HashMap<CacheKey2, Int>()
private val activated = HashSet<Int>()
private lateinit var weights: Array<IntArray>
private lateinit var valves: IntArray
override fun part1(reader: BufferedReader): String {
var nodes = readGraph(reader)
val indices = nodes.withIndex().associate { (index, node) -> node.name to index }
var graphMatrix = Array(nodes.size) { IntArray(nodes.size) }
buildGraphMatrix(graphMatrix, nodes, indices)
ignoreEmptyNodes(graphMatrix, nodes)
nodes = nodes.filter { it.value != 0 || it.name == "AA" }
graphMatrix = dropEmptyNodes(graphMatrix, nodes)
this.weights = floydWarshall(graphMatrix)
//Last index is always AA
return solve(valves.lastIndex, time = 30).toString()
}
private fun readGraph(reader: BufferedReader) = reader
.readLines()
.map { line ->
val split = line.split(
"Valve ",
" has flow rate=",
"; tunnels lead to valves ",
"; tunnel leads to valve ",
", "
)
.drop(1)
Valve(
name = split.component1(),
value = max(0, split.component2().toInt()),
next = split.drop(2)
)
}
.sortedByDescending { it.value }
private fun dropEmptyNodes(
graphMatrix: Array<IntArray>,
valves: List<Valve>
): Array<IntArray> {
this.valves = valves.map { it.value }.toIntArray()
val weights = graphMatrix.filter { i -> !i.all { j: Int -> j == -1 } }.toTypedArray()
for (i in weights.indices) {
weights[i] = weights[i].filter { it != -1 }.toIntArray()
}
return weights
}
private fun ignoreEmptyNodes(
outArray: Array<IntArray>,
valves: List<Valve>
) {
for (i in outArray.indices) {
if (valves[i].value == 0 && valves[i].name != "AA") {
val edgeIndices = outArray[i].withIndex().filter { it.value > 0 }.map { it.index }
edgeIndices.forEach { j ->
edgeIndices.forEach { k ->
if (j != k) {
outArray[j][k] = max(outArray[j][k], outArray[j][i] + 1)
outArray[k][j] = max(outArray[k][j], outArray[i][j] + 1)
}
}
}
for (j in outArray.indices) {
outArray[i][j] = -1
outArray[j][i] = -1
}
}
}
}
private fun buildGraphMatrix(
ourArray: Array<IntArray>,
valves: List<Valve>,
indices: Map<String, Int>
): Array<IntArray> {
valves.forEach { node ->
node.next.forEach { next ->
ourArray[indices[node.name]!!][indices[next]!!] = 1
}
}
return ourArray
}
override fun part2(reader: BufferedReader): String {
var nodes = readGraph(reader)
val indices = nodes.withIndex().associate { (index, node) -> node.name to index }
var graphMatrix = Array(nodes.size) { IntArray(nodes.size) }
buildGraphMatrix(graphMatrix, nodes, indices)
ignoreEmptyNodes(graphMatrix, nodes)
nodes = nodes.filter { it.value != 0 || it.name == "AA" }
graphMatrix = dropEmptyNodes(graphMatrix, nodes)
this.weights = floydWarshall(graphMatrix)
return solve2(
current1 = valves.lastIndex,//Last index is always AA
current2 = valves.lastIndex,
time1 = 26,
time2 = 26
).toString()
}
private fun floydWarshall(weights: Array<IntArray>): Array<IntArray> {
val fw = Array(weights.size) { IntArray(weights.size) }
for (i in weights.indices) {
for (j in weights.indices) {
if (weights[i][j] == 0) {
fw[i][j] = 9999
} else {
fw[i][j] = weights[i][j]
}
}
}
for (k in fw.indices) {
for (i in fw.indices) {
for (j in fw.indices) {
if (fw[i][k] + fw[k][j] < fw[i][j]) {
fw[i][j] = fw[i][k] + fw[k][j]
}
}
}
fw[k][k] = 0
}
return fw
}
private fun solve(current: Int, time: Int): Int {
if (time <= 0) return 0
cache1[CacheKey1(activated.fixHashCode(), current, time)]?.let { return it }
val weights = weights[current]
var best = 0
for (next in 0 until (weights.size - 1)) {
if (next == current) continue
val nextWeight = weights[next]
if (!activated.contains(next)) {
activated += next
val nextTime = max(0, time - nextWeight - 1)
val result = valves[next] * nextTime + solve(next, nextTime)
activated -= next
best = max(result, best)
}
}
cache1[CacheKey1(activated.fixHashCode(), current, time,)] = best
return best
}
private fun solve2(
current1: Int,
current2: Int,
time1: Int,
time2: Int
): Int {
if (time1 <= 0 && time2 <= 0) return 0
cache2[
CacheKey2(activated.fixHashCode(), current1, current2, time1, time2)
]
?.let { return it }
val weights1 = weights[current1]
val weights2 = weights[current2]
var best = 0
for (next1 in 0 until (weights1.size - 1)) {
if (next1 == current1) continue
var localBest = 0
val nextWeight1 = weights1[next1]
for (next2 in 0 until (weights2.size - 1)) {
if (next2 == current2) continue
if (next1 == next2) continue
val nextWeight2 = weights2[next2]
if (!activated.contains(next1) && !activated.contains(next2) &&
time1 > 0 && time2 > 0
) {
activated += next1
activated += next2
val nextTime1 = max(0, time1 - nextWeight1 - 1)
val nextTime2 = max(0, time2 - nextWeight2 - 1)
val result = valves[next1] * nextTime1 + valves[next2] * nextTime2 +
solve2(next1, next2, nextTime1, nextTime2)
activated -= next1
activated -= next2
if (localBest / 2 > result) {
break
}
localBest = max(result, localBest)
}
}
best = max(best, localBest)
}
cache2[
CacheKey2(activated.fixHashCode(), current1, current2, time1, time2)
] = best
return best
}
@Suppress("unused")
private fun debug(valves: List<Valve>): String {
val iter = valves.iterator()
return buildString {
append(valves.joinToString(prefix = " ", separator = "\t") { it.name })
append("\n")
append(weights.joinToString(separator = "") { row ->
iter.next().name + " " + row.joinToString(separator = "\t", postfix = "\n")
})
append(this@Day16.valves.joinToString(prefix = " ", separator = "\t"))
}
}
data class CacheKey1(
val activatedHash: Int,
val current: Int,
val time: Int,
)
data class CacheKey2(
val activatedHash: Int,
val current1: Int,
val current2: Int,
val time1: Int,
val time2: Int
)
data class Valve(
val name: String,
var value: Int,
val next: List<String>
)
} | 0 | Kotlin | 1 | 0 | 5fbdaf39a508dec80e0aa0b87035984cfd8af1bb | 8,302 | AdventOfCode | The Unlicense |
src/main/kotlin/com/sk/topicWise/tree/easy/437. Path Sum III.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.topicWise.tree.easy
import com.sk.topicWise.tree.TreeNode
private fun pathSum(root: TreeNode?, sum: Int): Int {
var ans = 0
fun dfs(root: TreeNode?): MutableList<ArrayList<Int>> {
root?.let {
var l = dfs(it.left)
var r = dfs(it.right)
var lret = mutableListOf<ArrayList<Int>>()
var rret = mutableListOf<ArrayList<Int>>()
for (list in l) {
var lsum = list.sum()
if (lsum + it.`val` == sum) ans++
else if (lsum + it.`val` < sum) {
list.add(it.`val`)
lret.add(list)
}
}
for (list in r) {
var lsum = list.sum()
if (lsum + it.`val` == sum) ans++
else if (lsum + it.`val` < sum) {
list.add(it.`val`)
rret.add(list)
}
}
for (list in lret) {
for (list2 in rret) {
if (list.sum() + list2.sum() == sum) ans++
}
}
lret.addAll(rret)
return lret
}
return mutableListOf<ArrayList<Int>>()
}
dfs(root)
return ans
}
private fun pathSum2(root: TreeNode?, sum: Int): Int {
var count = 0
fun dfs(root: TreeNode?, paths: MutableList<Int>) {
root?.let {
for (i in paths.indices) paths[i] += it.`val`
paths.add(it.`val`)
for (pathsum in paths) if (pathsum == sum) count++
val copyPath = mutableListOf<Int>()
paths.forEach { copyPath.add(it) }
dfs(it.left, paths)
dfs(it.right, copyPath)
}
}
dfs(root, mutableListOf())
return count
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,796 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2023/day21/Day21.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day21
import com.jacobhyphenated.advent2023.Day
class Day21: Day<List<List<Char>>> {
override fun getInput(): List<List<Char>> {
return readInputFile("21").lines().map { it.toCharArray().toList() }
}
override fun part1(input: List<List<Char>>): Any {
return countPossibleLocations(input, 64)
}
override fun part2(input: List<List<Char>>): Any {
TODO("Not yet implemented")
}
fun countPossibleLocations(grid: List<List<Char>>, steps: Int): Int {
val start = grid.flatMapIndexed { r, row -> List(row.size) { c -> Pair(r,c) } }
.first { (r,c) -> grid[r][c] == 'S' }
var current = setOf(start)
repeat(steps) {
current = current.flatMap { (row, col) ->
findAdjacent(row, col, grid)
}.toSet()
println("$it ${current.size}")
}
return current.size
}
private fun findAdjacent(row: Int, col: Int, grid: List<List<Char>>): List<Pair<Int,Int>> {
val adjacent = mutableListOf<Pair<Int,Int>>()
for (r in (row - 1).coerceAtLeast(0) .. (row + 1).coerceAtMost(grid.size - 1)) {
if (r == row || grid[r][col] == '#') {
continue
}
adjacent.add(Pair(r, col))
}
for (c in (col - 1).coerceAtLeast(0) .. (col + 1).coerceAtMost(grid[0].size - 1)) {
if (c == col || grid[row][c] == '#'){
continue
}
adjacent.add(Pair(row, c))
}
return adjacent
}
} | 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 1,427 | advent2023 | The Unlicense |
src/Day10.kt | kipwoker | 572,884,607 | false | null | class Operation(val cycles: Int, val add: Int)
fun main() {
fun parse(input: List<String>): List<Operation> {
return input.map { line ->
if (line == "noop") {
Operation(1, 0)
} else {
val modifier = line.split(' ')[1].toInt()
Operation(2, modifier)
}
}
}
fun part1(input: List<String>): Long {
val ops = parse(input)
var x = 1
var result = 0L
val maxIndex = 220
var seekIndex = 20
val hop = 40
var cycleCounter = 0
for (op in ops) {
for (cycle in 1..op.cycles) {
++cycleCounter
if (cycleCounter == seekIndex) {
result += x * seekIndex
if (seekIndex == maxIndex) {
return result
}
seekIndex += hop
}
}
x += op.add
}
return result
}
fun isSprite(cycleCounter: Int, x: Int, lineIndex: Int, hop: Int): Boolean {
val lineValue = cycleCounter - (hop * lineIndex)
return lineValue >= x - 1 && lineValue <= x + 1
}
fun part2(input: List<String>): Long {
val ops = parse(input)
var x = 1
var lineIndex = 0
val maxIndex = 240
var seekIndex = 40
val hop = 40
var cycleCounter = 0
for (op in ops) {
for (cycle in 1..op.cycles) {
if (isSprite(cycleCounter, x, lineIndex, hop)) {
print("#")
} else {
print(".")
}
++cycleCounter
if (cycleCounter == seekIndex) {
println()
if (seekIndex == maxIndex) {
return 0
}
seekIndex += hop
++lineIndex
}
}
x += op.add
}
return 0
}
val testInput = readInput("Day10_test")
assert(part1(testInput), 13140L)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 2,229 | aoc2022 | Apache License 2.0 |
src/main/kotlin/days/Day14.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() {
val input = readInput()
val template = input.first()
val rules = input.drop(2)
.map { it.split(" -> ") }
.associateBy(
keySelector = { it[0] },
valueTransform = { it[1] }
)
fun steps(): Sequence<Map<String, Long>> =
generateSequence(template.windowed(size = 2).groupingBy { it }.eachCount().mapValues { (_, count) -> count.toLong() }) { prev ->
prev.flatMap { (pair, count) ->
val inserted = rules[pair] ?: error("No matching rule for pattern '$pair'")
listOf("${pair[0]}$inserted" to count, "$inserted${pair[1]}" to count)
}.groupingBy { it.first }
.fold(0L) { acc, (_, count) -> acc + count }
}
fun Map<String, Long>.eachCount(): Map<Char, Long> =
flatMap { (pair, count) -> listOf(pair[0] to count, pair[1] to count) }
.groupingBy { it.first }
.fold(0L) { acc, (_, count) -> acc + count }
.mapValues { (polymer, count) ->
var actualCount = count / 2
if (polymer == template.first())
actualCount++
if (polymer == template.last())
actualCount++
actualCount
}
fun resultAfter(steps: Int): Long {
val counts = steps().drop(steps).first().eachCount()
val min = counts.minOf { (_, count) -> count }
val max = counts.maxOf { (_, count) -> count }
return max - min
}
println("Part 1: ${resultAfter(steps = 10)}")
println("Part 2: ${resultAfter(steps = 40)}")
} | 0 | Kotlin | 0 | 1 | dfc91afab12d6dad01de552a77fc22a83237c21d | 2,790 | AdventOfCode2021 | MIT License |
src/Day10.kt | mlidal | 572,869,919 | false | {"Kotlin": 20582} | import kotlin.math.abs
import kotlin.text.StringBuilder
fun main() {
fun part1(input: List<String>): Int {
var cycle = 1
var signalStrength = 1
val signalStrengths = mutableListOf<Int>()
input.forEach { line ->
if (line.startsWith("addx")) {
cycle += 1
if (listOf(20, 60, 100, 140, 180, 220).contains(cycle)) {
signalStrengths.add(cycle * signalStrength)
}
val param = line.substring("addx ".length).toInt()
cycle += 1
signalStrength += param
if (listOf(20, 60, 100, 140, 180, 220).contains(cycle)) {
signalStrengths.add(cycle * signalStrength)
}
} else if (line == "noop"){
cycle += 1
if (listOf(20, 60, 100, 140, 180, 220).contains(cycle)) {
signalStrengths.add(cycle * signalStrength)
}
} else {
throw IllegalArgumentException("Unknown operation $line")
}
}
return signalStrengths.sum()
}
fun part2(input: List<String>): List<String> {
val result = mutableListOf<String>()
var cycle = 1
var linePosition = 0
val lineLength = 40
var signalStrength = 1
val lineText = StringBuilder()
lineText.append('#')
input.forEach { line ->
if (line.startsWith("addx")) {
cycle += 1
if (linePosition < lineLength - 1) {
linePosition += 1
} else {
result.add(lineText.toString())
lineText.clear()
linePosition = 0
}
if (abs(linePosition - signalStrength) <= 1) {
lineText.append('#')
} else {
lineText.append('.')
}
val param = line.substring("addx ".length).toInt()
cycle += 1
if (linePosition < lineLength - 1) {
linePosition += 1
} else {
result.add(lineText.toString())
lineText.clear()
linePosition = 0
}
signalStrength += param
if (abs(linePosition - signalStrength) <= 1) {
lineText.append('#')
} else {
lineText.append('.')
}
} else if (line == "noop"){
cycle += 1
if (linePosition < lineLength - 1) {
linePosition += 1
} else {
result.add(lineText.toString())
lineText.clear()
linePosition = 0
}
if (abs(linePosition - signalStrength) <= 1) {
lineText.append('#')
} else {
lineText.append('.')
}
} else {
throw IllegalArgumentException("Unknown operation $line")
}
}
result.forEach {
println(it)
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val part2Result = """##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent()
//check(part2(testInput).joinToString("") == part2Result)
println()
println()
println()
val input = readInput("Day10")
println(part1(input))
part2(input).forEach { println(it) }
}
| 0 | Kotlin | 0 | 0 | bea7801ed5398dcf86a82b633a011397a154a53d | 4,081 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2020/Day10.kt | tginsberg | 315,060,137 | false | null | /*
* Copyright (c) 2020 by <NAME>
*/
/**
* Advent of Code 2020, Day 10 - Adapter Array
* Problem Description: http://adventofcode.com/2020/day/10
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day10/
*/
package com.ginsberg.advent2020
class Day10(input: List<Int>) {
private val adapters: List<Int> = input.plus(0).plus(input.maxOrNull()!! + 3).sorted()
fun solvePart1(): Int =
adapters
.asSequence()
.zipWithNext()
.map { it.second - it.first }
.groupingBy { it }
.eachCount()
.run {
getOrDefault(1, 1) * getOrDefault(3, 1)
}
fun solvePart2(): Long {
val pathsByAdapter: MutableMap<Int,Long> = mutableMapOf(0 to 1L)
adapters.drop(1).forEach { adapter ->
pathsByAdapter[adapter] = (1 .. 3).map { lookBack ->
pathsByAdapter.getOrDefault(adapter - lookBack, 0)
}.sum()
}
return pathsByAdapter.getValue(adapters.last())
}
}
| 0 | Kotlin | 2 | 38 | 75766e961f3c18c5e392b4c32bc9a935c3e6862b | 1,068 | advent-2020-kotlin | Apache License 2.0 |
src/Day10.kt | frango9000 | 573,098,370 | false | {"Kotlin": 73317} | fun main() {
val input = readInput("Day10")
printTime { println(Day10.part1(input)) }
printTime { println(Day10.part2(input)) }
}
class Day10 {
companion object {
fun part1(input: List<String>): Int {
var signalStrength = 0
var x = 1
var cycle = 1
for (command in input) {
cycle++
if ((cycle - 20) % 40 == 0) {
signalStrength += cycle * x
}
if (command != "noop") {
x += command.substring(5).toInt()
cycle++
if ((cycle - 20) % 40 == 0) {
signalStrength += cycle * x
}
}
}
return signalStrength
}
fun part2(input: List<String>): String {
var crt = ""
var x = 1
var cycle = 1
for (command in input) {
val lineOffset = (cycle / 40) * 40
crt += if (cycle - lineOffset - 1 in (x + -1..x + 1)) "▓" else "░"
cycle++
if (command != "noop") {
crt += if (cycle - lineOffset - 1 in (x - 1..x + 1)) "▓" else "░"
x += command.substring(5).toInt()
cycle++
}
}
return crt.chunked(40).joinToString("\n")
}
}
}
| 0 | Kotlin | 0 | 0 | 62e91dd429554853564484d93575b607a2d137a3 | 1,451 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/com/kishor/kotlin/algo/recursion/LowestCommonManager.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.algo.recursion
class OrgChart(name: Char) {
val name = name
val directReports = mutableListOf<OrgChart>()
}
//fun getLowestCommonManager(topManager: OrgChart, empOne: OrgChart, empTwo: OrgChart): OrgChart? {
// val managerStack = Stack<OrgChart>()
//
// for (report in topManager.directReports) {
// if (isBothReportsAvailable(empOne, empTwo, report)) {
// managerStack.push(report)
// }
// }
//
// if (managerStack.size > 0) return managerStack.pop()
// else return topManager
//
//}
fun isBothReportsAvailable(empOne: OrgChart, empTwo: OrgChart, newManager: OrgChart): Boolean {
var manager = newManager
return isReportAvailable(manager, empOne) && isReportAvailable(manager, empTwo)
}
fun isReportAvailable(currentManager: OrgChart, emp: OrgChart): Boolean {
var manager = currentManager
if (manager == null) return false
if (manager.name == emp.name) return true
else {
for (child in manager.directReports) {
isReportAvailable(child, emp)
}
}
return true
}
// ---------------------------------------//
data class OrgInfo(
val lowestCommonManager: OrgChart?,
val numRelatedReports: Int
)
// time O(n) space O(n) for recursion stack
fun getLowestCommonManager(topManager: OrgChart, reportOne: OrgChart, reportTwo: OrgChart): OrgChart? {
return getReportsInfo(topManager, reportOne, reportTwo).lowestCommonManager
}
fun getReportsInfo(manager: OrgChart, reportOne: OrgChart, reportTwo: OrgChart): OrgInfo {
// base case - if manager has null value or it's a report // itself
var numOfRelatedReport = 0
for (directReport in manager.directReports) {
val orgInfo = getReportsInfo(directReport, reportOne, reportTwo)
if (orgInfo.lowestCommonManager != null) return orgInfo
numOfRelatedReport += orgInfo.numRelatedReports
}
if (manager == reportOne || manager == reportOne) numOfRelatedReport++
val lowestCommonManger: OrgChart? = if (numOfRelatedReport == 2) manager else null
val newOrgInfo = OrgInfo(lowestCommonManger, numOfRelatedReport)
return newOrgInfo
}
| 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 2,176 | DS_Algo_Kotlin | MIT License |
year2023/day09/part2/src/main/kotlin/com/curtislb/adventofcode/year2023/day09/part2/Year2023Day09Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
Of course, it would be nice to have even more history included in your report. Surely it's safe to
just extrapolate backwards as well, right?
For each history, repeat the process of finding differences until the sequence of differences is
entirely zero. Then, rather than adding a zero to the end and filling in the next values of each
previous sequence, you should instead add a zero to the beginning of your sequence of zeroes, then
fill in new first values for each previous sequence.
In particular, here is what the third example history looks like when extrapolating back in time:
```
5 10 13 16 21 30 45
5 3 3 5 9 15
-2 0 2 4 6
2 2 2 2
0 0 0
```
Adding the new values on the left side of each sequence from bottom to top eventually reveals the
new left-most history value: 5.
Doing this for the remaining example data above results in previous values of -3 for the first
history and 0 for the second history. Adding all three new values together produces 2.
Analyze your OASIS report again, this time extrapolating the previous value for each history. What
is the sum of these extrapolated values?
*/
package com.curtislb.adventofcode.year2023.day09.part2
import com.curtislb.adventofcode.common.io.mapLines
import com.curtislb.adventofcode.common.parse.parseInts
import com.curtislb.adventofcode.year2023.day09.oasis.OasisReport
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2023, day 9, part 2.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
val reports = inputPath.toFile().mapLines { OasisReport(it.parseInts()) }
return reports.sumOf { it.extrapolatePrevious() }
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 1,854 | AdventOfCode | MIT License |
kotlin/104.Maximum Depth of Binary Tree(二叉树的最大深度).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>Given a binary tree, find its maximum depth.</p>
<p>The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.</p>
<p><strong>Note:</strong> A leaf is a node with no children.</p>
<p><strong>Example:</strong></p>
<p>Given binary tree <code>[3,9,20,null,null,15,7]</code>,</p>
<pre>
3
/ \
9 20
/ \
15 7</pre>
<p>return its depth = 3.</p>
<p>给定一个二叉树,找出其最大深度。</p>
<p>二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。</p>
<p><strong>说明:</strong> 叶子节点是指没有子节点的节点。</p>
<p><strong>示例:</strong><br>
给定二叉树 <code>[3,9,20,null,null,15,7]</code>,</p>
<pre> 3
/ \
9 20
/ \
15 7</pre>
<p>返回它的最大深度 3 。</p>
<p>给定一个二叉树,找出其最大深度。</p>
<p>二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。</p>
<p><strong>说明:</strong> 叶子节点是指没有子节点的节点。</p>
<p><strong>示例:</strong><br>
给定二叉树 <code>[3,9,20,null,null,15,7]</code>,</p>
<pre> 3
/ \
9 20
/ \
15 7</pre>
<p>返回它的最大深度 3 。</p>
**/
/**
* Definition for a binary tree node.
* class TreeNode(var `val`: Int = 0) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun maxDepth(root: TreeNode?): Int {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 1,519 | leetcode | MIT License |
src/main/kotlin/days/Day18.kt | nuudles | 316,314,995 | false | null | package days
class Day18 : Day(18) {
enum class Operator {
SUM,
PRODUCT
}
sealed class Token {
data class Value(val value: Long) : Token()
object StartParen : Token()
object EndParen : Token()
object Plus : Token()
object Times : Token()
companion object {
fun tokensFromString(string: String): List<Token> =
string
.split(" ")
.flatMap { substring ->
when {
substring == "+" ->
listOf(Plus)
substring == "*" ->
listOf(Times)
substring.startsWith("(") -> {
val list = MutableList<Token>(substring.count { it == '(' }) {
StartParen
}
list.add(Value(substring.trim('(').toLong()))
list
}
substring.endsWith(")") -> {
val list = MutableList<Token>(substring.count { it == ')' }) {
EndParen
}
list.add(0, Value(substring.trim(')').toLong()))
list
}
else ->
listOf(Value(substring.toLong()))
}
}
fun addPrecedence(tokens: List<Token>): List<Token> {
val toInsert = mutableSetOf<Pair<Int, Token>>()
tokens
.withIndex()
.filter { it.value == Plus }
.map { it.index }
.forEach { index ->
// Find where to add the StartParen
if (tokens[index - 1] is Value) {
toInsert.add(index - 1 to StartParen)
} else if (tokens[index - 1] == EndParen) {
var nest = 1
var searchIndex = index - 1
while (nest > 0) {
searchIndex--
if (tokens[searchIndex] == StartParen) {
nest--
} else if (tokens[searchIndex] == EndParen) {
nest++
}
}
toInsert.add(searchIndex to StartParen)
}
// Find where to add the EndParen
if (tokens[index + 1] is Value) {
toInsert.add(index + 2 to EndParen)
} else if (tokens[index + 1] == StartParen) {
var nest = 1
var searchIndex = index + 1
while (nest > 0) {
searchIndex++
if (tokens[searchIndex] == EndParen) {
nest--
} else if (tokens[searchIndex] == StartParen) {
nest++
}
}
toInsert.add(searchIndex + 1 to EndParen)
}
}
val newTokens = tokens.toMutableList()
toInsert
.sortedByDescending { it.first }
.forEach { (index, token) ->
newTokens.add(index, token)
}
return newTokens
}
}
}
sealed class Expression {
data class Value(val value: Long) : Expression()
data class Operation(
val left: Expression,
val right: Expression,
val operator: Operator
) : Expression()
fun evaluate(): Long =
when (this) {
is Value -> value
is Operation -> when (operator) {
Operator.SUM -> left.evaluate() + right.evaluate()
Operator.PRODUCT -> left.evaluate() * right.evaluate()
}
}
companion object {
fun fromTokens(tokens: List<Token>): Expression {
if (tokens.count() == 1) {
return Value((tokens.last() as? Token.Value)?.value ?: 0)
}
var index = tokens.count() - 1
when (val lastToken = tokens[index]) {
is Token.Value ->
return Operation(
left = fromTokens(tokens.dropLast(2)),
right = Value(lastToken.value),
operator = when (tokens[index - 1]) {
Token.Plus -> Operator.SUM
else -> Operator.PRODUCT
}
)
is Token.EndParen -> {
var nest = 1
while (nest > 0) {
index--
if (tokens[index] == Token.StartParen) {
nest--
} else if (tokens[index] == Token.EndParen) {
nest++
}
}
return if (index == 0) {
fromTokens(tokens.subList(index + 1, tokens.count() - 1))
} else {
Operation(
left = fromTokens(tokens.subList(0, index - 1)),
right = fromTokens(tokens.subList(index + 1, tokens.count() - 1)),
operator = when (tokens[index - 1]) {
Token.Plus -> Operator.SUM
else -> Operator.PRODUCT
}
)
}
}
else ->
throw Exception("Unexpected!")
}
}
}
}
override fun partOne(): Any =
inputList
.map { Expression.fromTokens(Token.tokensFromString(it)).evaluate() }
.sum()
override fun partTwo(): Any =
inputList
.map {
Expression.fromTokens(
Token.addPrecedence(Token.tokensFromString(it))
).evaluate()
}
.sum()
} | 0 | Kotlin | 0 | 0 | 5ac4aac0b6c1e79392701b588b07f57079af4b03 | 6,956 | advent-of-code-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/Day14.kt | Yeah69 | 317,335,309 | false | {"Kotlin": 73241} | import java.lang.Exception
class Day14 : Day() {
override val label: String get() = "14"
interface Instruction {
fun execute(mask: Mask, map: MutableMap<Long, Long>): Mask
}
abstract class Mask(private val mask: String) : Instruction {
override fun execute(mask: Mask, map: MutableMap<Long, Long>): Mask = this
abstract fun transform(value: String): String
protected fun transformInner(value: String, map: (Pair<Char, Char>) -> Char): String =
mask.zip(value).map(map).joinToString("")
}
class MaskZero(maskParam: String) : Mask(maskParam) {
override fun transform(value: String): String = transformInner(value) {
(c1, c2) -> when (c1) {
'0' -> '0'
'1' -> '1'
else -> c2 } }
}
class MaskOne(maskParam: String) : Mask(maskParam) {
override fun transform(value: String): String = transformInner(value) {
(c1, c2) -> when (c1) {
'0' -> c2
'1' -> '1'
else -> 'X' } }
}
abstract class MemoryWrite : Instruction {
fun String.toMaskValue(): Long = this
.replace("_", "")
.reversed()
.asSequence()
.mapIndexed { i, c -> Pair(i, c) }
.filter { p -> p.second == '1' }
.map { p -> 1L.shl(p.first) }
.sum()
}
data class MemoryWriteZero(val address: String, val value: String) : MemoryWrite() {
override fun execute(mask: Mask, map: MutableMap<Long, Long>): Mask {
map[address.toMaskValue()] = mask.transform(value).toMaskValue()
return mask
}
}
data class MemoryWriteOne(val address: String, val value: String) : MemoryWrite() {
private fun recursive(text: String) : Sequence<String> =
if (text.contains('X').not())
sequenceOf(text)
else
(recursive(text.replaceFirst('X', '0'))
+ recursive(text.replaceFirst('X', '1')))
override fun execute(mask: Mask, map: MutableMap<Long, Long>): Mask {
recursive(mask.transform(address)).forEach { map[it.toMaskValue()] = value.toMaskValue() }
return mask
}
}
class Program(private val instructions: List<Instruction>) {
private var mask: Mask = MaskZero("111111111111111111111111111111111111")
val map = mutableMapOf<Long, Long>()
fun run(): Long {
instructions.forEach { mask = it.execute(mask, map) }
return map.values.sum()
}
}
private val maskRegex: Regex = """^mask = ([01X]{36})$""".toRegex()
private val memRegex: Regex = """^mem\[([0-9]+)] = ([0-9]+)$""".toRegex()
private fun Long.toBinaryText() = (35 downTo 0)
.asSequence()
.map { if((1L.shl(it).and(this).shr(it)) == 1L) '1' else '0' }
.joinToString("")
private fun getInstruction(
createMemoryWrite: (String, String) -> MemoryWrite,
createMask: (String) -> Mask): List<Instruction> =
input
.lineSequence()
.mapNotNull {
val memMatch = memRegex.matchEntire(it)
if (memMatch != null) {
val (address, value) = memMatch.destructured
createMemoryWrite(address.toLong().toBinaryText(), value.toLong().toBinaryText()) }
else {
val (mask) = maskRegex.find(it)?.destructured ?: throw Exception()
createMask(mask) } }
.toList()
private val programZero by lazy { Program(getInstruction(::MemoryWriteZero, ::MaskZero)) }
private val programOne by lazy { Program(getInstruction(::MemoryWriteOne, ::MaskOne)) }
override fun taskZeroLogic(): String = programZero.run().toString()
override fun taskOneLogic(): String = programOne.run().toString()
} | 0 | Kotlin | 0 | 0 | 23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec | 3,952 | AdventOfCodeKotlin | The Unlicense |
src/main/kotlin/g0101_0200/s0115_distinct_subsequences/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0101_0200.s0115_distinct_subsequences
// #Hard #String #Dynamic_Programming #2022_09_29_Time_285_ms_(88.89%)_Space_34.2_MB_(100.00%)
class Solution {
fun numDistinct(s: String, t: String): Int {
if (s.length < t.length) {
return 0
}
if (s.length == t.length) {
return if (s == t) 1 else 0
}
val move = s.length - t.length + 2
// Only finite number of character in s can occupy first position in T. Same applies for
// every character in T.
val dp = IntArray(move)
var j = 1
var k = 1
for (i in 0 until t.length) {
var firstMatch = true
while (j < move) {
if (t[i] == s[i + j - 1]) {
if (firstMatch) {
// Keep track of first match. To avoid useless comparisons on next
// iteration.
k = j
firstMatch = false
}
if (i == 0) {
dp[j] = 1
}
dp[j] += dp[j - 1]
} else {
dp[j] = dp[j - 1]
}
j++
}
// No match found for current character of t in s. No point in checking others.
if (dp[move - 1] == 0) {
return 0
}
j = k
}
return dp[move - 1]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,488 | LeetCode-in-Kotlin | MIT License |
src/day2/second/Solution.kt | verwoerd | 224,986,977 | false | null | package day2.second
import tools.timeSolution
fun main() = timeSolution {
val code = readLine()!!.split(",").map { it.toInt() }.toIntArray()
val target = 19690720
loop@ for (noun in 0..100) {
for (verb in 0..100) {
if (executeProgram(code.copyOf(), noun, verb) == target) {
println("Solution: ${100 * noun + verb}")
break@loop
}
}
}
}
fun executeProgram(code: IntArray, noun: Int, verb: Int): Int {
var pointer = 0
code[1] = noun
code[2] = verb
while (code[pointer] != 99) {
code[code[pointer + 3]] = when (code[pointer]) {
1 -> code[code[pointer + 1]] + code[code[pointer + 2]]
2 -> code[code[pointer + 1]] * code[code[pointer + 2]]
else -> throw IllegalArgumentException("Invalid opcode ${code[pointer]}")
}
pointer += 4
}
return code[0]
}
// Observed behaviour
// verb only increased the outcome by 1
fun maybeFasterSearch() = timeSolution {
val code = readLine()!!.split(",").map { it.toInt() }.toIntArray()
val target = 19690720
val rangeEnd = 100
loop@ for (noun in 0..rangeEnd) {
when (val verb = target - executeProgram(code.copyOf(), noun, 0) ) {
in 0..rangeEnd -> {
println("Solution: ${100 * noun + verb}")
break@loop
}
}
}
}
| 0 | Kotlin | 0 | 0 | 554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7 | 1,275 | AoC2019 | MIT License |
year2020/day13/bus/src/main/kotlin/com/curtislb/adventofcode/year2020/day13/bus/BusSchedule.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2020.day13.bus
/**
* A schedule that lists the IDs of in-service buses at various offsets.
*
* All in-service buses initially depart at timestamp 0, and the ID of each bus indicates the time
* between this and each
* subsequent departure.
*
* @param schedule A string representation of the schedule, with integer bus IDs (or out-of-service
* buses, represented by `x`) separated by commas.
*/
class BusSchedule(schedule: String) {
/**
* A map from the schedule index of each in-service bus to its ID.
*/
val busIDs: Map<Int, Long> = mutableMapOf<Int, Long>().apply {
schedule.trim().split(',').forEachIndexed { index, busIDString ->
if (busIDString != "x") {
this[index] = busIDString.toLong()
}
}
}
/**
* Finds the first bus to depart after (or at) [arrivalTime] and returns a pair containing its
* ID and the number of minutes after [arrivalTime] that it departs.
*/
fun findShortestWait(arrivalTime: Long): Pair<Long, Long>? {
return busIDs.values.map { Pair(it, it - (arrivalTime % it)) }.minByOrNull { it.second }
}
/**
* Returns the earliest time `t` (in minutes) such that each in-service bus with schedule index
* `i` departs at time `t + i`.
*/
fun findEarliestAlignedDepartureTime(): Long {
val (time, _) = busIDs.entries.sortedBy { it.value }
.foldRight(Pair(0L, 1L)) { (offset, busID), (time, step) ->
var newTime = time
var remainder = (time + offset) % busID
while (remainder != 0L) {
newTime += step
remainder = (remainder + step) % busID
}
Pair(newTime, step * busID)
}
return time
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 1,853 | AdventOfCode | MIT License |
src/main/kotlin/days/Day12.kt | andilau | 573,139,461 | false | {"Kotlin": 65955} | package days
import java.util.PriorityQueue
@AdventOfCodePuzzle(
name = "Hill Climbing Algorithm",
url = "https://adventofcode.com/2022/day/12",
date = Date(day = 12, year = 2022)
)
class Day12(val input: List<String>) : Puzzle {
lateinit var start: Point
lateinit var end: Point
private val heightMap = buildMap {
input.forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
val p = Point(x, y)
val height: Int = when (c) {
in 'a'..'z' -> c - 'a'
'S' -> 0.also { start = p }
'E' -> 25.also { end = p }
else -> error("Unhandled character: $c")
}
put(p, height)
}
}
}
override fun partOne(): Int {
val queue = PriorityQueue<Pair<Point, Int>> { a, b -> a.second.compareTo(b.second) }
queue.add(start to 0)
val seen = mutableSetOf<Point>()
while (queue.isNotEmpty()) {
val (next, cost) = queue.poll()
if (next in seen) continue
seen += next
if (next == end) return cost
next.neighbours()
.filter { it in heightMap }
.filter { heightMap[it]!! - heightMap[next]!! <= 1 }
.forEach { queue.add(it to cost + 1) }
}
error("No path found!")
}
override fun partTwo(): Int {
val queue = PriorityQueue<Pair<Point, Int>> { a, b -> a.second.compareTo(b.second) }
queue.add(end to 0)
val seen = mutableSetOf<Point>()
while (queue.isNotEmpty()) {
val (next, cost) = queue.poll()
if (next in seen) continue
seen += next
if (heightMap[next] == 0) return cost
next.neighbours()
.filter { it in heightMap }
.filter { heightMap[next]!! - heightMap[it]!! <= 1 }
.forEach { queue.add(it to cost + 1) }
}
error("No path found!")
}
}
| 0 | Kotlin | 0 | 0 | da824f8c562d72387940844aff306b22f605db40 | 2,060 | advent-of-code-2022 | Creative Commons Zero v1.0 Universal |
kotori/src/main/kotlin/com/github/wanasit/kotori/Dictionary.kt | wanasit | 262,215,376 | false | null | package com.github.wanasit.kotori
import com.github.wanasit.kotori.optimized.DefaultDictionary
import com.github.wanasit.kotori.optimized.DefaultTermFeatures
open class Dictionary <out TermFeatures> (
open val terms: TermDictionary<TermFeatures>,
open val connection: ConnectionCost,
open val unknownExtraction: UnknownTermExtractionStrategy<TermFeatures>? = null
) {
companion object {
@JvmStatic
fun readDefaultFromResource(): Dictionary<DefaultTermFeatures> {
return DefaultDictionary.readFromResource()
}
}
}
/**
* TermDictionary (単語辞書)
*
* e.g.
* - 木, 1285 (Noun), 1285 (Noun), 7283
* - 切る, 772 (Verb-ru), 772 (Verb-ru), 7439
* - きる, 772 (Verb-ru), 772 (Verb-ru), 12499
* - ...
*/
interface TermEntry<out Features> {
val surfaceForm: String
val leftId: Int
val rightId: Int
val cost: Int
val features: Features
}
typealias TermID = Int
interface TermDictionary<out TermFeatures> : Iterable<Pair<TermID, TermEntry<TermFeatures>>>{
operator fun get(id: TermID): TermEntry<TermFeatures>?
fun size() : Int = this.asSequence().count()
}
/**
* ConnectionCost (連接コース) or Connectivity ()
*
* e.g.
* - 1285 (Noun) to 1285 (Noun) => 62
* - 772 (Verb-ru) to 1285 (Noun) => 335
* - 772 (Verb-ru) to 772 (Verb-ru) => -3713
*/
interface ConnectionCost {
fun lookup(fromRightId: Int, toLeftId: Int): Int
}
/**
* Unknown or Out-of-Vocabulary terms handling strategy
*/
interface UnknownTermExtractionStrategy<out TermFeatures> {
/**
* Extract unknown terms from `text` at `index`
*
* @param forceExtraction at least one term is expected to be extracted when this flag is enforced
*/
fun extractUnknownTerms(text: String, index: Int, forceExtraction: Boolean): Iterable<TermEntry<TermFeatures>>
}
| 0 | Kotlin | 4 | 41 | 7ca4f352e6bf4fb314828d36a217953ec5006b20 | 1,869 | kotori | MIT License |
src/Day06.kt | emmanueljohn1 | 572,809,704 | false | {"Kotlin": 12720} |
fun main() {
fun findMarker(chars: String, countUniq: Int = 4): Pair<Int, List<Char>> {
val windows = chars.asSequence().windowed(countUniq, 1)
val foundMarker = windows.mapIndexed{ idx, value ->
Pair(idx+1, value)
}.filter { (_, marker) -> marker.toSet().size == countUniq }
return foundMarker.first()
}
fun part1(input: List<String>): Int {
return findMarker(input.first()).first + 3 // because we are always stepping up by one
}
fun part2(input: List<String>): Int {
return findMarker(input.first(), 14).first + 13
}
println("----- Test input -------")
val testInput = readInput("inputs/Day06_test")
println(part1(testInput))
println(part2(testInput))
println("----- Real input -------")
val input = readInput("inputs/Day06")
println(part1(input))
println(part2(input))
}
//----- Test input -------
//7
//19
//----- Real input -------
//1909
//3380
| 0 | Kotlin | 0 | 0 | 154db2b1648c9d12f82aa00722209741b1de1e1b | 978 | advent22 | Apache License 2.0 |
src/day4/Day4.kt | gautemo | 317,316,447 | false | null | package day4
import shared.getText
fun validPassports(input: String, validate: Boolean = false): Int{
val regex = Regex("""^\s*${'$'}""", RegexOption.MULTILINE)
val passports = input.split(regex)
return passports.count { if(validate) hasValidRequiredFields(it) else hasRequiredFields(it) }
}
fun hasRequiredFields(passport: String): Boolean{
val requiredFields = listOf(
"byr",
"iyr",
"eyr",
"hgt",
"hcl",
"ecl",
"pid"
)
return requiredFields.all { passport.contains(it) }
}
fun hasValidRequiredFields(passport: String): Boolean{
val end = """(\s|${'$'})"""
val byr = passport.contains(Regex("""byr:((19[2-9]\d)|(200[0-2]))${end}"""))
val iyr = passport.contains(Regex("""iyr:20((1\d)|20)${end}"""))
val eyr = passport.contains(Regex("""eyr:20((2\d)|30)${end}"""))
val hgt = passport.contains(Regex("""hgt:((1[5-8]\d|19[0-3])cm|(59|6\d|7[0-6])in)${end}"""))
val hcl = passport.contains(Regex("""hcl:#([0-9]|[a-f]){6}${end}"""))
val ecl = passport.contains(Regex("""ecl:(amb|blu|brn|gry|grn|hzl|oth)${end}"""))
val pid = passport.contains(Regex("""pid:(\d){9}${end}"""))
return byr && iyr && eyr && hgt && hcl && ecl && pid
}
fun main(){
val input = getText("day4.txt")
val fieldsPresent = validPassports(input)
println(fieldsPresent)
val fieldsPresentAndValid = validPassports(input, true)
println(fieldsPresentAndValid)
} | 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 1,491 | AdventOfCode2020 | MIT License |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2017/2017-06.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2017
fun main() {
println("Part1+2:")
println(solve(testInput1))
println(solve(input))
}
private fun solve(input: String): Pair<Int, Int> {
var memory = input.split("""\s+""".toRegex()).map { it.toInt() }
val visited = mutableMapOf<List<Int>, Int>()
var counter = 0
while (memory !in visited) {
visited += memory to counter
memory = memory.redistribute()
counter++
}
return counter to (counter - visited[memory]!!)
}
private fun List<Int>.redistribute(): List<Int> {
val max = maxOrNull()!!
val from = indexOfFirst { it == max }
val result = toMutableList()
val count = get(from)
result[from] = 0
var index = from.inc() % size
repeat(count) {
result[index] = result[index].inc()
index = index.inc() % size
}
return result
}
private const val testInput1 = """0 2 7 0"""
private const val input = """14 0 15 12 11 11 3 5 1 6 8 4 9 1 8 4"""
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,001 | advent-of-code | MIT License |
src/main/kotlin/com/staricka/adventofcode2023/days/Day9.kt | mathstar | 719,656,133 | false | {"Kotlin": 107115} | package com.staricka.adventofcode2023.days
import com.staricka.adventofcode2023.framework.Day
class Day9: Day {
private fun produceDiffSequence(original: List<Int>): List<List<Int>> {
val result = ArrayList<List<Int>>()
result.add(original)
while (result.last().any { it != 0 }) {
result.add(
result.last()
.indices
.filter { it != 0 }
.map { result.last()[it] - result.last()[it - 1] }
)
}
return result
}
private fun extrapolate(sequences: List<List<Int>>): Int {
return sequences.reversed()
.fold(0) {acc, n -> acc + n.last()}
}
private fun extrapolateReverse(sequences: List<List<Int>>): Int {
return sequences.reversed()
.fold(0) {acc, n -> n.first() - acc}
}
override fun part1(input: String): Int {
return input.lines()
.filter { it.isNotBlank() }
.map { it.split(" ").map {n -> n.toInt() } }
.map { produceDiffSequence(it) }
.sumOf { extrapolate(it) }
}
override fun part2(input: String): Int {
return input.lines()
.filter { it.isNotBlank() }
.map { it.split(" ").map {n -> n.toInt() } }
.map { produceDiffSequence(it) }
.sumOf { extrapolateReverse(it) }
}
} | 0 | Kotlin | 0 | 0 | 8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa | 1,406 | adventOfCode2023 | MIT License |
2021/05/main.kt | chylex | 433,239,393 | false | null | import java.io.File
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.system.measureTimeMillis
fun main() {
val lineRegex = Regex("^(\\d+),(\\d+) -> (\\d+),(\\d+)$")
val lines = File("input.txt").readLines()
.mapNotNull(lineRegex::matchEntire)
.map { it.groupValues.takeLast(4).map(String::toInt) }
.map { Line(it[0], it[1], it[2], it[3]) }
println("(Took ${measureTimeMillis { part1(lines) }} ms)")
println("(Took ${measureTimeMillis { part2(lines) }} ms)")
}
@Suppress("MemberVisibilityCanBePrivate")
data class Line(val x1: Int, val y1: Int, val x2: Int, val y2: Int) {
val minX = min(x1, x2)
val minY = min(y1, y2)
val maxX = max(x1, x2)
val maxY = max(y1, y2)
init {
require(isStraight || is45Degrees) { "Line must be straight or have a slope of 45 degrees!" }
}
val isStraight
get() = x1 == x2 || y1 == y2
val is45Degrees
get() = abs(x2 - x1) == abs(y2 - y1)
val length = 1 + max(abs(x2 - x1), abs(y2 - y1))
private val slopeX = Integer.signum(x2 - x1)
private val slopeY = Integer.signum(y2 - y1)
fun contains(x: Int, y: Int): Boolean {
if (x1 == x2) {
return x == x1 && y in minY..maxY
}
if (y1 == y2) {
return y == y1 && x in minX..maxX
}
if (x !in minX..maxX || y !in minY..maxY) {
return false
}
for (i in 0 until length) {
if (x == x1 + (slopeX * i) && y == y1 + (slopeY * i)) {
return true
}
}
return false
}
}
class Floor(private val lines: List<Line>) {
private val minX = lines.minOf { min(it.x1, it.x2) }
private val maxX = lines.maxOf { max(it.x1, it.x2) }
private val minY = lines.minOf { min(it.y1, it.y2) }
private val maxY = lines.maxOf { max(it.y1, it.y2) }
fun countPointsWithOverlap(minOverlap: Int): Int {
val xs = minX..maxY
val ys = minY..maxY
val xy = xs.flatMap { x -> ys.map { y -> x to y } }
return xy.parallelStream().filter { (x, y) -> hasOverlapOf(x, y, minOverlap) }.count().toInt()
}
private fun hasOverlapOf(x: Int, y: Int, minOverlap: Int): Boolean {
var count = 0
for (line in lines) {
if (line.contains(x, y) && ++count >= minOverlap) {
return true
}
}
return false
}
@Suppress("unused")
fun printDiagram() {
for (y in minY..maxY) {
for (x in minX..maxX) {
val count = lines.count { it.contains(x, y) }
if (count == 0) {
print('.')
}
else {
print(count)
}
}
println()
}
}
}
fun part1(lines: List<Line>) {
val straightLines = lines.filter(Line::isStraight).ifEmpty { return }
val straightLineFloor = Floor(straightLines)
println("Points where at least 2 straight lines overlap: ${straightLineFloor.countPointsWithOverlap(2)}")
}
fun part2(lines: List<Line>) {
val floor = Floor(lines)
println("Points where at least 2 lines overlap: ${floor.countPointsWithOverlap(2)}")
}
| 0 | Rust | 0 | 0 | 04e2c35138f59bee0a3edcb7acb31f66e8aa350f | 2,843 | Advent-of-Code | The Unlicense |
2017/src/twentyfive/PortBridgeChallenge.kt | Mattias1 | 116,139,424 | false | null | package twentyfive
fun portBridgeInput(): List<String> = listOf(
"31/13", "34/4", "49/49", "23/37", "47/45", "32/4", "12/35", "37/30", "41/48", "0/47",
"32/30", "12/5", "37/31", "7/41", "10/28", "35/4", "28/35", "20/29", "32/20", "31/43",
"48/14", "10/11", "27/6", "9/24", "8/28", "45/48", "8/1", "16/19", "45/45", "0/4",
"29/33", "2/5", "33/9", "11/7", "32/10", "44/1", "40/32", "2/45", "16/16", "1/18",
"38/36", "34/24", "39/44", "32/37", "26/46", "25/33", "9/10", "0/29", "38/8", "33/33",
"49/19", "18/20", "49/39", "18/39", "26/13", "19/32"
)
class PortBridgeChallenge {
fun strongestBridge(input: List<String>): Int {
val components = getComponents(input)
return maxBridge(components, 0L, 0, 0, { it.strength })
}
fun strongestLongestBridge(input: List<String>): Int {
val components = getComponents(input)
val maxLength = maxBridge(components, 0L, 0, 0, { 1 })
return maxBridge(components, 0L, 0, maxLength, { it.strength })
}
private fun getComponents(input: List<String>): List<Component> = input
.map { it.split('/').map { it.toInt() } }
.mapIndexed { i, s -> Component(s[0], s[1], 1L shl i) }
private fun maxBridge(components: List<Component>, bits: Long, port: Int, minLength: Int, transformer: (Component) -> Int): Int {
val possibleComponents = components.filter { it.isUnmarked(bits) && it.hasPort(port) }
if (minLength > 0 && possibleComponents.isEmpty()) {
return if (countMarks(bits) < minLength) Int.MIN_VALUE else 0
}
return possibleComponents
.map {
transformer(it) + maxBridge(components, it.mark(bits), it.otherPort(port), minLength, transformer)
}.max() ?: 0
}
private fun countMarks(bits: Long): Int = (0..62).count { bits and (1L shl it) != 0L }
class Component(private val portA: Int, private val portB: Int, private val bitmask: Long) {
fun isUnmarked(bits: Long): Boolean = bits and bitmask == 0L
fun mark(bits: Long): Long = bits or bitmask
val strength: Int get() = portA + portB
fun hasPort(port: Int): Boolean = portA == port || portB == port
fun otherPort(port: Int): Int = if (port == portA) portB else portA
}
} | 0 | Kotlin | 0 | 0 | 6bcd889c6652681e243d493363eef1c2e57d35ef | 2,398 | advent-of-code | MIT License |
kotlin/src/katas/kotlin/adventofcode/day7/Part2.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.adventofcode.day7
import katas.kotlin.adventofcode.day5.*
import nonstdlib.*
import java.io.*
fun main() {
val program = File("src/katas/kotlin/adventofcode/day7/input.txt")
.readText().split(",").map(String::toInt).toMutableList()
val maxOutput = (5..9).permutations()
.map { (phase1, phase2, phase3, phase4, phase5) ->
var output5: Sequence<Int> = emptySequence()
val mixedInput = sequence {
yield(0)
output5.forEach { yield(it) }
}
val output1 = SequencingAmp(input = mixedInput, phase = phase1).run(program)
val output2 = SequencingAmp(input = output1, phase = phase2).run(program)
val output3 = SequencingAmp(input = output2, phase = phase3).run(program)
val output4 = SequencingAmp(input = output3, phase = phase4).run(program)
output5 = SequencingAmp(input = output4, phase = phase5).run(program)
output5.last()
}
.maxOrNull()
println(maxOutput) // 76211147
}
class SequencingAmp(val input: Sequence<Int>, val phase: Int) {
fun run(program: MutableList<Int>): Sequence<Int> = sequence {
val allInputs = (sequenceOf(phase) + input).iterator()
execute(
program,
read = { allInputs.next() },
write = { yield(it) }
)
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,404 | katas | The Unlicense |
src/Day01.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | fun main() {
fun part1(input: List<String>): Int {
val output = mutableListOf<Int>()
var count = 0
input.forEach {
if (it.isEmpty()) {
output.add(count)
count = 0
} else {
count += it.toInt()
}
}
return output.max()
}
fun part2(input: List<String>): Int {
val output = mutableListOf<Int>()
var count = 0
input.forEach {
if (it.isEmpty()) {
output.add(count)
count = 0
} else {
count += it.toInt()
}
}
return output.sortedDescending().slice(0 .. 2).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 968 | aoc2022 | Apache License 2.0 |
src/main/kotlin/io/binarysearch/FindKClosestElements.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | @file:Suppress("MemberVisibilityCanBePrivate")
package io.binarysearch
// https://leetcode.com/explore/learn/card/binary-search/135/template-iii/945/
class FindKClosestElements {
fun execute(input: IntArray, k: Int, target: Int): List<Int> = when {
input.isEmpty() -> emptyList()
k == input.size -> input.toList()
else ->
searchElement(input, target).let { targetIndex ->
searchClosestElements(input, targetIndex, k, target).let { (start, end) ->
input.toList().subList(start, minOf(end + 1, input.size))
}
}
}
fun searchClosestElements(input: IntArray, targetIndex: Int, k: Int, target: Int): Pair<Int, Int> {
var left = targetIndex
var right = targetIndex
repeat(k - 1) {
if (left < 1) {
right++
} else if (input.size - 1 <= right) {
left--
} else if (input[right + 1] - target < target - input[left - 1]) {
right++
} else {
left--
}
}
return left to right
}
fun searchElement(input: IntArray, target: Int): Int {
var start = 0
var end = input.size - 1
while (start < end) {
val pivot = start + (end - start) / 2
val value = input[pivot]
if (value == target) {
return pivot
} else if (value < target) {
start = pivot + 1
} else {
end = pivot - 1
}
}
return start
}
data class Wrapper(@Suppress("ArrayInDataClass") val input: IntArray, val k: Int, val target: Int, val solution: List<Int>)
}
fun main() {
val findKClosestElements = FindKClosestElements()
listOf(
FindKClosestElements.Wrapper((1..9).toList().toIntArray(), 4, 3, (1..4).toList()),
FindKClosestElements.Wrapper((1..9).toList().toIntArray(), 4, -1, (1..4).toList()),
FindKClosestElements.Wrapper(intArrayOf(1, 1, 1, 10, 10, 10), 1, 9, listOf(10)),
FindKClosestElements.Wrapper(intArrayOf(0, 1, 1, 1, 2, 3, 6, 7, 8, 9), 9, 4, listOf(0, 1, 1, 1, 2, 3, 6, 7, 8)),
FindKClosestElements.Wrapper(intArrayOf(0, 0, 1, 2, 3, 3, 4, 7, 7, 8), 3, 5, listOf(3, 3, 4)),
FindKClosestElements.Wrapper(intArrayOf(0, 0, 0, 1, 3, 5, 6, 7, 8, 8), 2, 2, listOf(1, 3)),
FindKClosestElements.Wrapper(intArrayOf(0, 1, 2, 2, 2, 3, 6, 8, 8, 9), 5, 9, listOf(3, 6, 8, 8, 9)),
FindKClosestElements.Wrapper(intArrayOf(1, 2, 3, 3, 6, 6, 7, 7, 9, 9), 8, 8, listOf(3, 3, 6, 6, 7, 7, 9, 9))
).map { (input, k, target, result) ->
val output = findKClosestElements.execute(input, k, target)
if (output == result) {
println("Input ${input.toList()} k $k target $target , solution is valid")
} else {
println("INVALID Solution: $output, expected $result")
}
}
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 2,708 | coding | MIT License |
src/test/kotlin/com/igorwojda/tree/multiway/traversal/breathfirst/Solution.kt | igorwojda | 159,511,104 | false | {"Kotlin": 254856} | package com.igorwojda.tree.multiway.traversal.breathfirst
private object Solution1 {
private fun traverseBreathFirst(tree: BinarySearchTree<Char>): List<Char> {
val queue = Queue<BinaryNode<Char>>()
val result = mutableListOf<Char>()
if (tree.isEmpty()) {
return result
} else {
tree.root?.let { queue.add(it) }
}
while (queue.isNotEmpty()) {
val current = queue.remove() ?: break
result.add(current.data)
current.left?.let { queue.add(it) }
current.right?.let { queue.add(it) }
}
return result
}
private class BinarySearchTree<E : Comparable<E>> {
var root: BinaryNode<E>? = null
private set
fun add(element: E) {
val newNode = BinaryNode(element)
if (root == null) {
root = newNode
return
}
var current: BinaryNode<E> = root ?: return
while (true) {
when {
current.data == element -> {
return
}
element < current.data -> {
if (current.left == null) {
current.left = newNode
return
}
current.left?.let { current = it }
}
element > current.data -> {
if (current.right == null) {
current.right = newNode
return
}
current.right?.let { current = it }
}
}
}
}
fun contains(element: E): Boolean {
var current = root
while (true) {
if (current == null) {
break
} else if (current.data == element) {
return true
} else if (element < current.data) {
current = current.left
} else if (element > current.data) {
current = current.right
}
}
return false
}
fun isEmpty() = root == null
}
private data class BinaryNode<E : Comparable<E>>(
val data: E,
var left: BinaryNode<E>? = null,
var right: BinaryNode<E>? = null,
)
/*
Queue can be used as helper class to implement breath first traversal. This is not the most optimal queue implementation,
however it's enough for this task. Check "Queue challenge" solution for more details and more efficient queue
implementation.
*/
private class Queue<E> {
private val list = mutableListOf<E>()
fun add(element: E) {
list.add(element)
}
fun remove() = if (list.isEmpty()) null else list.removeAt(0)
fun peek() = list.firstOrNull()
fun isEmpty() = list.isEmpty()
fun isNotEmpty() = list.isNotEmpty()
val size get() = list.size
}
}
private object KtLintWillNotComplain
| 9 | Kotlin | 225 | 895 | b09b738846e9f30ad2e9716e4e1401e2724aeaec | 3,215 | kotlin-coding-challenges | MIT License |
src/main/kotlin/day23/Code.kt | fcolasuonno | 317,324,330 | false | null | package day23
import isDebug
import java.io.File
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val parsed = parse(input)
part1(parsed)
part2(parsed)
}
fun parse(input: List<String>) = input.single().map { it - '0' }
fun part1(input: List<Int>) {
val res = (input + input.first()).play().take(8).joinToString("")
println("Part 1 = $res")
}
fun part2(input: List<Int>) {
val res = (input + 10).play(1000000, 10000000).take(2).fold(1L) { acc, i -> acc * i }
println("Part 2 = $res")
}
private fun List<Int>.play(num: Int = size - 1, rounds: Int = 100) = IntArray(num) { it + 1 }
.also { list ->
map { it - 1 }.zipWithNext().forEach { list[it.first] = it.second }
var index = first() - 1
if (num > size) {
list[list.size - 1] = index
}
repeat(rounds) {
val p1 = list[index]
val p2 = list[p1]
val p3 = list[p2]
val next = list[p3]
var destination = index
do {
destination--
if (destination == -1) destination = (list.size - 1)
} while (destination == p1 || destination == p2 || destination == p3)
list[index] = next
list[p3] = list[destination]
list[destination] = p1
index = next
}
}.let { list ->
generateSequence(list[0]) { list[it] }.map { it + 1 }
}
| 0 | Kotlin | 0 | 0 | e7408e9d513315ea3b48dbcd31209d3dc068462d | 1,594 | AOC2020 | MIT License |
src/main/kotlin/game/GameBoard.kt | kevinpbaker | 512,335,324 | false | {"Kotlin": 44698} | import koma.abs
import koma.ceil
import koma.extensions.forEachIndexed
import koma.extensions.get
import koma.fill
import koma.floor
import koma.matrix.Matrix
interface GameBoard {
val rows: Int
val cols: Int
var colors: Array<IntArray>
fun isFilled(x: Int, y: Int): Boolean {
return when {
(y < 0) && (x < cols) && (x >= 0) -> false
else -> (x >= cols) || (x < 0) || (y >= rows) || (colors[x][y] != 0)
}
}
fun getBoardAsMatrix(): Matrix<Double> {
return fill(rows, cols) { row, col ->
if (isFilled(col, row)) 1.0 else 0.0
}
}
fun getPeaks(): List<Int> {
return getBoardAsMatrix().mapColsToList {
val indexes = mutableListOf<Int>()
it.forEachIndexed { rowIndex, _, ele ->
when {
ele > 0 -> {
val endRowIndex = rows - 1
indexes.add(endRowIndex - rowIndex)
}
else -> indexes.add(0)
}
}
return@mapColsToList indexes.maxOrNull() ?: 0
}
}
fun nPits(): Int {
return getPeaks().sumOf { (if (it == 0) return 1 else 0) as Int }
}
fun highestPeak(): Int {
return getPeaks().maxOrNull() ?: 0
}
fun lowestPeak(): Int {
return getPeaks().minOrNull() ?: 0
}
fun aggregatedHeight(): Int {
return getPeaks().sum()
}
fun getHolesPerColumn(): List<Int> {
val peaks = getPeaks()
val board = getBoardAsMatrix()
val holes = mutableListOf<Int>()
repeat(board.numCols()) { holes.add(0) }
board.forEachIndexed { rowIndex, colIndex, _ ->
val endRowIndex = rows - 1
val isBelowPeak = rowIndex > (endRowIndex - peaks[colIndex])
if (isBelowPeak && !isFilled(colIndex, rowIndex)) holes[colIndex] += 1
}
return holes
}
fun nHoles(): Int {
return getHolesPerColumn().sum()
}
fun getBumpiness(): Int {
val p = getPeaks()
var bumpiness = 0
for (i in 0 until cols-2) {
bumpiness += abs(p[i] - p[i+1]).toInt()
}
return bumpiness
}
fun nColsWithHoles(): Int {
return getHolesPerColumn().sumOf { (if (it > 0) return 1 else 0) as Int }
}
fun getBoardRowBalance(): Double {
// higher row is lower on board
return fill(rows, cols) { row, col ->
if (isFilled(col, row)) {
when (row) {
in 0..floor(row/2.0) -> { -25.0 }
in ceil(row*(3/4.0))..(rows) -> { (row*2).toDouble() }
else -> 0.0
}
} else 0.0
}.elementSum()
}
fun getRowTransitions(): Int {
val highest = (rows-1) - highestPeak()
val board = getBoardAsMatrix()
var rowTransitions = 0
for (r in 0 until highest) {
val row = board.getRow((rows-1)-r)
var current = row[0]
for (x in 0 until (cols-1)) {
if (row[x+1] != current) rowTransitions++
current = row[x+1]
}
}
return rowTransitions
}
fun getColumnTransitions(): Int {
val highest = (rows-1) - highestPeak()
val board = getBoardAsMatrix()
var colTransitions = 0
for (c in 0 until cols) {
val col = board.getCol(c)
for (h in (rows-1)-highest until rows-1) {
var current = col[h]
if (col[h+1] != current) colTransitions++
current = col[h+1]
}
}
return colTransitions
}
} | 0 | Kotlin | 0 | 2 | cf5b5f595b8e25e88b7cd7979230df804173332d | 3,740 | TetrisAI | MIT License |
src/Day22.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.io.File
// Advent of Code 2022, Day 22: Monkey Map
class Day22(input: String) {
private val moveInstructions: String
private val maze: Array<CharArray>
init {
val inputParts = input.split("\n\n")
moveInstructions = inputParts[1]
val mazeInput = inputParts[0].split("\n")
val maxLen = mazeInput.maxOf { it.length }
maze = Array (mazeInput.size) { CharArray(maxLen){' '} }
mazeInput.forEachIndexed { idx, s ->
s.toCharArray().mapIndexed { index, c ->
maze[idx][index] = c
}
}
}
private fun Array<CharArray>.print() {
this.forEach {
println(it)
}
}
enum class Direction(val num: Int, val c: Char, val vec: Pair<Int, Int>) {
RIGHT(0, '>', Pair(0, 1)),
DOWN(1, 'V', Pair(1, 0)),
LEFT(2, '<', Pair(0, -1)),
UP(3, '^', Pair(-1, 0));
fun turnRight() : Direction {
return when (this) {
RIGHT -> DOWN
DOWN -> LEFT
LEFT -> UP
UP -> RIGHT
}
}
fun turnLeft() : Direction {
return when (this) {
RIGHT -> UP
DOWN -> RIGHT
LEFT -> DOWN
UP -> LEFT
}
}
}
private fun move(moveAmt: Int, startPos: Pair<Int, Int>, dir: Direction) : Pair<Int, Int> {
// println("move is $moveAmt in ${dir.name} direction, start pos $startPos")
var moves = moveAmt
var pos = startPos
while (moves > 0) {
moves--
var next = Pair(pos.first + dir.vec.first, pos.second + dir.vec.second)
next = clamp(next, pos)
// wrap around
while (maze[next.first][next.second] !in listOf('.', '#', '^', 'V', '>', '<') ) {
next = Pair(next.first + dir.vec.first, next.second + dir.vec.second)
next = clamp(next, pos)
}
if (maze[next.first][next.second] == '#') {
break
} else {
maze[next.first][next.second] = dir.c
pos = next
}
}
return pos
}
private fun clamp(
next: Pair<Int, Int>,
pos: Pair<Int, Int>
): Pair<Int, Int> {
var next1 = next
if (next1.second > maze[pos.first].lastIndex) {
next1 = pos.first to 0
}
if (next1.second < 0) {
next1 = pos.first to maze[pos.first].lastIndex
}
if (next1.first > maze.lastIndex) {
next1 = 0 to pos.second
}
if (next1.first < 0) {
next1 = maze.lastIndex to pos.second
}
return next1
}
fun part1(): Long {
val startCol = maze[0].indexOfFirst { it == '.' }
var pos = Pair(0, startCol)
var dir = Direction.RIGHT
maze[pos.first][pos.second] = Direction.RIGHT.c
// if reach end of array, if reach end of ., if reach wall
var moveAmt = 0
moveInstructions.forEach { c ->
if (c.isDigit()) {
moveAmt = moveAmt * 10 + (c.code - '0'.code)
} else {
if (c.code == 10 ) return@forEach // line feed
// do the move
pos = move(moveAmt, pos, dir)
// maze.print()
// println()
moveAmt = 0
check(c == 'L' || c == 'R')
dir = if (c == 'L') {
dir.turnLeft()
} else {
dir.turnRight()
}
// println("turning $c, new dir is ${dir.name}")
maze[pos.first][pos.second] = dir.c
}
}
// do last move
pos = move(moveAmt, pos, dir)
// maze.print()
return (pos.first + 1) * 1000L + (pos.second + 1) * 4 + dir.num
}
fun part2(): Long = 0L
}
fun main() {
fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText()
val testSolver = Day22(readInputAsOneLine("Day22_test"))
check(testSolver.part1()==6032L)
val solver = Day22(readInputAsOneLine("Day22"))
println(solver.part1())
} | 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 4,279 | AdventOfCode2022 | Apache License 2.0 |
hackerrank/abbr/Solution.kts | shengmin | 5,972,157 | false | null | import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import kotlin.collections.*
import kotlin.comparisons.*
import kotlin.io.*
import kotlin.jvm.*
import kotlin.jvm.functions.*
import kotlin.jvm.internal.*
import kotlin.ranges.*
import kotlin.sequences.*
import kotlin.text.*
// Complete the abbreviation function below.
fun abbreviation(aString: String, bString: String): String {
val matches = Array(aString.length + 1) { BooleanArray(bString.length + 1) }
// Empty string is the same as empty string
matches[0][0] = true
for (i in 1..aString.length) {
matches[i][0] = aString[i - 1].isLowerCase() && matches[i - 1][0]
}
for (i in 1..aString.length) {
for (j in 1..bString.length) {
val a = aString[i - 1]
val b = bString[j - 1]
if (a == b) {
// Same char
matches[i][j] = matches[i - 1][j - 1]
} else if (a.isLowerCase()) {
if (b.toLowerCase() == a) {
// We can transform lowercase a into uppercase A or discard current A
matches[i][j] = matches[i - 1][j - 1] || matches[i - 1][j]
} else {
// Or we can discard current a
matches[i][j] = matches[i - 1][j]
}
} else {
// a is uppercase, and the two don't match, nothing we can do
matches[i][j] = false
}
}
}
return if (matches[aString.length][bString.length]) "YES" else "NO"
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val q = scan.nextLine().trim().toInt()
for (qItr in 1..q) {
val a = scan.nextLine()
val b = scan.nextLine()
val result = abbreviation(a, b)
println(result)
}
}
main(arrayOf())
| 0 | Java | 18 | 20 | 08e65546527436f4bd2a2014350b2f97ac1367e7 | 1,816 | coding-problem | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MergeStringsAlternately.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 1768. Merge Strings Alternately
* @see <a href="https://leetcode.com/problems/merge-strings-alternately/">Source</a>
*/
fun interface MergeStringsAlternately {
fun mergeAlternately(word1: String, word2: String): String
}
class MergeStringsAlternatelyTwoPointers : MergeStringsAlternately {
override fun mergeAlternately(word1: String, word2: String): String {
val m: Int = word1.length
val n: Int = word2.length
val result = java.lang.StringBuilder()
var i = 0
var j = 0
while (i < m || j < n) {
if (i < m) {
result.append(word1[i++])
}
if (j < n) {
result.append(word2[j++])
}
}
return result.toString()
}
}
class MergeStringsAlternatelyOnePointer : MergeStringsAlternately {
override fun mergeAlternately(word1: String, word2: String): String {
val m: Int = word1.length
val n: Int = word2.length
val result = StringBuilder()
for (i in 0 until max(m, n)) {
if (i < m) {
result.append(word1[i])
}
if (i < n) {
result.append(word2[i])
}
}
return result.toString()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,941 | kotlab | Apache License 2.0 |
src/day09/Day09.kt | Frank112 | 572,910,492 | false | null | import day08.Direction
import day08.MoveCommand
import day08.Rope
fun main() {
val moveCommandRegex = Regex("^([DULR]) (\\d+)$")
fun mapDirection(s: String): Direction {
return when(s) {
"D" -> Direction.DOWN
"U" -> Direction.UP
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> { throw IllegalArgumentException("Could not map direction '$s'")}
}
}
fun parseInput(input: List<String>): List<MoveCommand> {
return input.map { moveCommandRegex.matchEntire(it)!! }
.map { MoveCommand(mapDirection(it.groupValues[1]), it.groupValues[2].toInt()) }
}
fun part1(input: List<MoveCommand>): Int {
val rope = Rope(2)
input.forEach { rope.handle(it) }
return rope.tailPositionHistory.toSet().size
}
fun part2(input: List<MoveCommand>): Int {
val rope = Rope(10)
input.forEach { rope.handle(it) }
return rope.tailPositionHistory.toSet().size
}
// test if implementation meets criteria from the description, like:
val testInput = parseInput(readInput("day09/Day09_test"))
println("Parsed test input: $testInput")
assertThat(part1(testInput), 13)
assertThat(part2(testInput), 1)
assertThat(part2(parseInput(readInput("day09/Day09_test2"))), 36)
val input = parseInput(readInput("day09/Day09"))
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1e927c95191a154efc0fe91a7b89d8ff526125eb | 1,452 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day05.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.ints
import se.saidaspen.aoc.util.removeFirst
fun main() = Day05.run()
object Day05 : Day(2022, 5) {
override fun part1(): Any {
val stacks = mutableMapOf<Int, ArrayDeque<Char>>().withDefault { ArrayDeque() }
input.split("\n\n")[0].dropLast(1).lines().forEach {
var i = 0
while (i * 4 + 1 < it.length) {
val stack = stacks.getValue(i + 1)
val c = it[1 + i * 4]
if (c.isLetter()) stack.addLast(c)
stacks[i + 1] = stack
i += 1
}
}
val instructions = input.split("\n\n")[1].lines()
for (l in instructions) {
val (n, f, t) = ints(l)
repeat(n) {
val elem = stacks[f]!!.removeFirst()
stacks[t]!!.addFirst(elem)
}
}
return stacks.values.map { it.first() }.joinToString("")
}
override fun part2(): Any {
val stacks = mutableMapOf<Int, ArrayDeque<Char>>().withDefault { ArrayDeque() }
input.split("\n\n")[0].dropLast(1).lines().forEach {
var i = 0
while (i * 4 + 1 < it.length) {
val stack = stacks.getValue(i + 1)
val c = it[1 + i * 4]
if (c.isLetter()) stack.addLast(c)
stacks[i + 1] = stack
i += 1
}
}
val instructions = input.split("\n\n")[1].lines()
for (l in instructions) {
val (n, f, t) = ints(l)
val moved = stacks[f]!!.removeFirst(n).reversed()
for (elem in moved) {
stacks[t]!!.addFirst(elem)
}
}
return stacks.values.map { it.first() }.joinToString("")
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,859 | adventofkotlin | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[17]电话号码的字母组合.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
//
// 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
//
//
//
//
//
// 示例 1:
//
//
//输入:digits = "23"
//输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
//
//
// 示例 2:
//
//
//输入:digits = ""
//输出:[]
//
//
// 示例 3:
//
//
//输入:digits = "2"
//输出:["a","b","c"]
//
//
//
//
// 提示:
//
//
// 0 <= digits.length <= 4
// digits[i] 是范围 ['2', '9'] 的一个数字。
//
// Related Topics 深度优先搜索 递归 字符串 回溯算法
// 👍 1326 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun letterCombinations(digits: String): List<String> {
if(digits.isEmpty()) return ArrayList<String>()
var map = HashMap<Char,String>()
map['2'] = "abc"
map['3'] = "def"
map['4'] = "ghi"
map['5'] = "jkl"
map['6'] = "mno"
map['7'] = "pqrs"
map['8'] = "tuv"
map['9'] = "wxyz"
//返回值
var res = ArrayList<String>()
dealDigits(0,"",digits,map,res)
return res
}
//递归遍历获取
private fun dealDigits(level: Int, str: String, digits: String, map: java.util.HashMap<Char, String>, res: java.util.ArrayList<String>) {
//递归退出条件
if (level == digits.length) {
res.add(str)
return
}
//逻辑处理,进入下层循环
//获取当前 key
var key = digits[level]
//获取key 对应的 字母值
var strDigits = map[key]!!
//循环组合
for (i in strDigits.indices){
dealDigits(level+1,str+strDigits[i],digits,map,res)
}
//数据reverse
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 2,010 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/ru/nsu/lupa/ChainProcessor.kt | lilvadim | 576,661,907 | false | {"Kotlin": 22514, "Java": 836} | package ru.nsu.lupa
class ChainProcessor: ResultProcessor {
/**
* Convert match graph to list of chains from longest to shortest
*/
private lateinit var g: Map<Profile, Map<Profile, Set<MatchCriteria>>>
private lateinit var rootChainNode: ChainNode<Set<MatchCriteria>, Profile>
private var chainList = mutableListOf<Pair<ChainNode<Set<MatchCriteria>, Profile>, Int>>()
override fun process(matchGraph: MatchGraph, rootProfile: Profile): List<ChainNode<Set<MatchCriteria>, Profile>> {
chainList = mutableListOf()
rootChainNode = ChainNode(null, null, null)
g = matchGraph.asAdjacencyList()
if (g[rootProfile]!!.isEmpty()) {
return emptyList()
}
dfs(rootProfile, rootChainNode)
return chainList.sortedBy { (_, len) -> len }.map { (chain, _) -> chain }.reversed()
}
private fun dfs(node: Profile, previousChainNode: ChainNode<Set<MatchCriteria>, Profile>) {
if (g[node]!!.isEmpty()) {
var currentChainNode: ChainNode<Set<MatchCriteria>, Profile> = ChainNode(node, null, null)
previousChainNode.next = currentChainNode
val rootChainNodeCopy = rootChainNode.copy()
currentChainNode = rootChainNodeCopy
var currentLength = 0
while (currentChainNode.next != null) {
currentChainNode.next = currentChainNode.next!!.copy()
currentChainNode = currentChainNode.next!!
currentLength++
}
chainList.add(Pair(rootChainNodeCopy.next!!, currentLength))
return
}
for ((key, value) in g[node]!!) {
val currentChainNode = ChainNode(node, null, value)
previousChainNode.next = currentChainNode
dfs(key, currentChainNode)
}
}
} | 0 | Kotlin | 0 | 0 | 9388aa69457bc625317a3732f2afcd52e02ef1a1 | 1,844 | lupa | Apache License 2.0 |
src/Day06/Day06.kt | G-lalonde | 574,649,075 | false | {"Kotlin": 39626} | package Day06
import readInput
fun main() {
fun part1(input: List<String>): Int {
val signal = input[0]
val queue = Queue<Char>()
for ((i, c) in signal.withIndex()) {
if (queue.size() == 4) {
return i
}
if (queue.contains(c)) {
while (queue.dequeue() != c) {
}
}
queue.enqueue(c)
}
return -1
}
fun part2(input: List<String>): Int {
val signal = input[0]
val queue = Queue<Char>()
for ((i, c) in signal.withIndex()) {
if (queue.size() == 14) {
return i
}
if (queue.contains(c)) {
while (queue.dequeue() != c) {
}
}
queue.enqueue(c)
}
return -1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06/Day06_test")
check(part1(testInput) == 10) { "Got instead : ${part1(testInput)}" }
check(part2(testInput) == 29) { "Got instead : ${part2(testInput)}" }
val input = readInput("Day06/Day06")
println("Answer for part 1 : ${part1(input)}")
println("Answer for part 2 : ${part2(input)}")
}
class Queue<T> {
private val list = mutableListOf<T>()
fun enqueue(element: T) {
list.add(element)
}
fun dequeue(): T? {
if (list.isEmpty()) {
return null
}
return list.removeAt(0)
}
fun size(): Int {
return list.size
}
fun contains(element: T): Boolean {
return list.contains(element)
}
fun indexOf(element: T): Int {
return list.indexOf(element)
}
}
| 0 | Kotlin | 0 | 0 | 3463c3228471e7fc08dbe6f89af33199da1ceac9 | 1,756 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinOperationsBinaryString.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* 1758. Minimum Changes To Make Alternating Binary String
* @see <a href="https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string">Source</a>
*/
fun interface MinOperationsBinaryString {
operator fun invoke(s: String): Int
}
/**
* Approach 1: Start with Zero or Start with One
*/
class MinOperationsBinaryStringStart : MinOperationsBinaryString {
override fun invoke(s: String): Int {
var start0 = 0
var start1 = 0
for (i in s.indices) {
if (i % 2 == 0) {
if (s[i] == '0') {
start1++
} else {
start0++
}
} else {
if (s[i] == '1') {
start1++
} else {
start0++
}
}
}
return min(start0.toDouble(), start1.toDouble()).toInt()
}
}
class MinOperationsBinaryStringCheck : MinOperationsBinaryString {
override fun invoke(s: String): Int {
var start0 = 0
for (i in s.indices) {
if (i % 2 == 0) {
if (s[i] == '1') {
start0++
}
} else {
if (s[i] == '0') {
start0++
}
}
}
return start0.coerceAtMost(s.length - start0)
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,059 | kotlab | Apache License 2.0 |
src/iii_conventions/MyDate.kt | EugenIvanushkin | 90,234,259 | true | {"Kotlin": 77289, "Java": 4952} | package iii_conventions
import java.time.Month
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(date: MyDate): Int {
if (this.year.compareTo(date.year) == 0) {
if (this.month.compareTo(date.month) == 0) {
if (this.dayOfMonth.compareTo(date.dayOfMonth) == 0) {
return 0
}else{
return this.dayOfMonth.compareTo(date.dayOfMonth)
}
} else {
return this.month.compareTo(date.month)
}
}
return this.year.compareTo(date.year)
}
}
operator fun MyDate.plus(b: MyDate) = MyDate(this.year + b.year, this.month + b.month, this.dayOfMonth + b.dayOfMonth)
operator fun MyDate.plus(b: TimeInterval) = when (b) {
TimeInterval.DAY -> MyDate(this.year, this.month, this.dayOfMonth + 1)
TimeInterval.WEEK -> MyDate(this.year + 1, this.month, this.dayOfMonth)
TimeInterval.YEAR -> MyDate(this.year + 1, this.month, this.dayOfMonth)
else -> MyDate(this.year, this.month, this.dayOfMonth)
}
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
enum class TimeInterval {
DAY,
WEEK,
YEAR
}
class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> {
override fun iterator(): Iterator {
return Iterator
}
companion object Iterator : kotlin.collections.Iterator<MyDate> {
override fun next(): MyDate {
if (this.hasNext()) {
}
return MyDate(1, 1, 1)
}
override fun hasNext(): Boolean {
return false;
}
}
}
operator fun DateRange.contains(other: MyDate): Boolean {
return other.compareTo(start) in 0..1 && other.compareTo(endInclusive) in -1..0
}
| 0 | Kotlin | 0 | 0 | 321e41c17ba3dab01ee7f182ec1a1f4494ba232d | 1,857 | kotlin-koans | MIT License |
src/sat.kt | JoelEager | 126,541,542 | false | null | import kotlin.math.pow
class Vector(var x: Double, var y: Double)
/**
* @param poly1, poly2 The two polygons described as arrays of points as Vectors
* Note: The points list must go in sequence around the polygon
* @param maxDist The maximum distance between any two points of any two polygons that can be touching
* If this null then the optimization check that uses it will be skipped
*/
fun hasCollided(poly1: Array<Vector>, poly2: Array<Vector>, maxDist: Double?=null): Boolean {
// Do an optimization check using the maxDist
if (maxDist != null) {
if ((poly1[1].x - poly2[0].x).pow(2) + (poly1[1].y - poly2[0].y).pow(2) <= maxDist.pow(2)) {
// Collision is possible so run SAT on the polys
return runSAT(poly1, poly2)
} else {
return false
}
} else {
// No maxDist so run SAT on the polys
return runSAT(poly1, poly2)
}
}
fun runSAT(poly1: Array<Vector>, poly2: Array<Vector>): Boolean {
// Implements the actual SAT algorithm
val edges = polyToEdges(poly1) + polyToEdges(poly2)
val axes = Array(edges.size, { index -> orthogonal(edges[index])})
for (axis in axes) {
if (!overlap(project(poly1, axis), project(poly2, axis))) {
// The polys don't overlap on this axis so they can't be touching
return false
}
}
// The polys overlap on all axes so they must be touching
return true
}
/**
* Returns a vector going from point1 to point2
*/
fun edgeVector(point1: Vector, point2: Vector) = Vector(point2.x - point1.x, point2.y - point1.y)
/**
* Returns an array of the edges of the poly as vectors
*/
fun polyToEdges(poly: Array<Vector>) = Array(poly.size,
{ index -> edgeVector(poly[index], poly[(index + 1) % poly.size]) })
/**
* Returns a new vector which is orthogonal to the given vector
*/
fun orthogonal(vector: Vector) = Vector(vector.y, -vector.x)
/**
* Returns the dot (or scalar) product of the two vectors
*/
fun dotProduct(vector1: Vector, vector2: Vector) = vector1.x * vector2.x + vector1.y * vector2.y
/**
* Returns a vector showing how much of the poly lies along the axis
*/
fun project(poly: Array<Vector>, axis: Vector): Vector {
val dots = Array(poly.size, { index -> dotProduct(poly[index], axis) })
return Vector(dots.min()!!, dots.max()!!)
}
/**
* Returns a boolean indicating if the two projections overlap
*/
fun overlap(projection1: Vector, projection2: Vector) = projection1.x <= projection2.y &&
projection2.x <= projection1.y | 0 | Kotlin | 0 | 0 | 2c05f92310d25d638cf36d54a82522e7c85eacc6 | 2,568 | Kotlin-Collision-Detector | MIT License |
src/main/kotlin/adventofcode2017/Day21FractalArt.kt | n81ur3 | 484,801,748 | false | {"Kotlin": 476844, "Java": 275} | package adventofcode2017
class Day21FractalArt
data class FractalRule(val original: String, val transformed: String)
class FractalArt(ruleLines: List<String>) {
val rules: List<FractalRule>
val fractals: MutableList<Fractal> = mutableListOf()
val activePixels: Int
get() = fractals.sumOf { it.activePixels }
val startingFractal = Fractal(
mutableListOf(
mutableListOf('.', '#', '.'),
mutableListOf('.', '.', '#'),
mutableListOf('#', '#', '#')
)
)
init {
rules = ruleLines.map { FractalRule(it.substringBefore(" ="), it.substringAfter("> ")) }
fractals.add(startingFractal)
}
fun enhance() {
val result = mutableListOf<Fractal>()
fractals.forEach { fractal ->
result.addAll(transformFractal(fractal))
}
fractals.clear()
fractals.addAll(result)
}
fun transformFractal(origin: Fractal): List<Fractal> {
val result = mutableListOf<Fractal>()
if (origin.size < 4) {
result.add(Fractal.fromLine(transform(origin)))
} else {
result.add(Fractal.fromLine(transform(origin.topLeft)))
result.add(Fractal.fromLine(transform(origin.topRight)))
result.add(Fractal.fromLine(transform(origin.bottomLeft)))
result.add(Fractal.fromLine(transform(origin.bottomRight)))
}
return result
}
fun printFractals() {
fractals.forEach { print(it) }
}
private fun transform(origin: String): String {
return transform(Fractal.fromLine(origin))
}
private fun transform(origin: Fractal): String {
val patterns = mutableListOf<String>()
repeat(if (origin.size == 2) 4 else 8) {
origin.rotateRight()
patterns.add(origin.toString())
}
origin.flipVertical()
patterns.add(origin.toString())
origin.flipVertical()
origin.flipHorizontal()
patterns.add(origin.toString())
origin.flipHorizontal()
val result = rules.firstOrNull { it.original in patterns }?.transformed ?: ""
if (result == "") {
println("No Match")
}
return result
}
}
data class Fractal(var lines: List<MutableList<Char>>) {
val size: Int = lines[0].size
val activePixels: Int
get() = lines.sumOf { line -> line.count { it == '#' } }
val topLeft: String
get() {
return buildString {
append(lines[0][0])
append(lines[0][1])
append("/")
append(lines[1][0])
append(lines[1][1])
}
}
val topRight: String
get() {
return buildString {
append(lines[0][2])
append(lines[0][3])
append("/")
append(lines[1][2])
append(lines[1][3])
}
}
val bottomLeft: String
get() {
return buildString {
append(lines[2][0])
append(lines[2][1])
append("/")
append(lines[3][0])
append(lines[3][1])
}
}
val bottomRight: String
get() {
return buildString {
append(lines[2][2])
append(lines[2][3])
append("/")
append(lines[3][2])
append(lines[3][3])
}
}
fun rotateRight() {
if (size == 2) {
val tmp = lines[0][0]
lines[0][0] = lines[1][0]
lines[1][0] = lines[1][1]
lines[1][1] = lines[0][1]
lines[0][1] = tmp
} else {
val tmp = lines[0][0]
lines[0][0] = lines[1][0]
lines[1][0] = lines[2][0]
lines[2][0] = lines[2][1]
lines[2][1] = lines[2][2]
lines[2][2] = lines[1][2]
lines[1][2] = lines[0][2]
lines[0][2] = lines[0][1]
lines[0][1] = tmp
}
}
fun rotateLeft() {
if (size == 2) {
val tmp = lines[0][0]
lines[0][0] = lines[0][1]
lines[0][1] = lines[1][1]
lines[1][1] = lines[1][0]
lines[1][0] = tmp
} else {
val tmp = lines[0][0]
lines[0][0] = lines[0][1]
lines[0][1] = lines[0][2]
lines[0][2] = lines[1][2]
lines[1][2] = lines[2][2]
lines[2][2] = lines[2][1]
lines[2][1] = lines[2][0]
lines[2][0] = lines[1][0]
lines[1][0] = tmp
}
}
fun flipHorizontal() {
if (size == 2) {
var tmp = lines[0][0]
lines[0][0] = lines[1][0]
lines[1][0] = tmp
tmp = lines[0][1]
lines[0][1] = lines[1][1]
lines[1][1] = tmp
} else {
var tmp = lines[0][0]
lines[0][0] = lines[2][0]
lines[2][0] = tmp
tmp = lines[0][1]
lines[0][1] = lines[2][1]
lines[2][1] = tmp
tmp = lines[0][2]
lines[0][2] = lines[2][2]
lines[2][2] = tmp
}
}
fun flipVertical() {
if (size == 2) {
var tmp = lines[0][0]
lines[0][0] = lines[0][1]
lines[0][1] = tmp
tmp = lines[1][0]
lines[1][0] = lines[1][1]
lines[1][1] = tmp
} else {
var tmp = lines[0][0]
lines[0][0] = lines[0][2]
lines[0][2] = tmp
tmp = lines[1][0]
lines[1][0] = lines[1][2]
lines[1][2] = tmp
tmp = lines[2][0]
lines[2][0] = lines[2][2]
lines[2][2] = tmp
}
}
fun displayAsGrid() {
lines.forEach { println(it.joinToString("")) }
}
override fun toString(): String {
return lines.map { it.joinToString("") }.joinToString("/")
}
companion object {
fun fromLine(input: String) = Fractal(input.split("/").map { it.toCharArray().toMutableList() })
}
} | 0 | Kotlin | 0 | 0 | fdc59410c717ac4876d53d8688d03b9b044c1b7e | 6,211 | kotlin-coding-challenges | MIT License |
src/main/kotlin/year2022/Day01.kt | simpor | 572,200,851 | false | {"Kotlin": 80923} | import AoCUtils
import AoCUtils.test
fun main() {
fun part1(input: String, debug: Boolean = false): Long {
val elves = input.split("\n\n")
return elves.map { s ->
s.split("\n")
.sumOf { it.toInt() }
}.max().toLong()
}
fun part2(input: String, debug: Boolean = false): Long {
val elves = input.split("\n\n")
return elves.map { s ->
s.split("\n")
.sumOf { it.toInt() }
}
.sorted()
.asReversed()
.take(3)
.sum().toLong()
}
val testInput = "1000\n" +
"2000\n" +
"3000\n" +
"\n" +
"4000\n" +
"\n" +
"5000\n" +
"6000\n" +
"\n" +
"7000\n" +
"8000\n" +
"9000\n" +
"\n" +
"10000"
val input = AoCUtils.readText("year2022/day01.txt")
part1(testInput) test Pair(24000L, "test 1 part 1")
part1(input) test Pair(68775L, "part 1")
part2(testInput) test Pair(45000L, "test 2 part 2")
part2(input) test Pair(202585L, "part 2")
}
| 0 | Kotlin | 0 | 0 | 631cbd22ca7bdfc8a5218c306402c19efd65330b | 1,170 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/year2022/Day18.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2022
import utils.Point3D
class Day18(input: String) {
enum class Plane {
XY, YZ, XZ
}
data class Face(val point: Point3D, val plane: Plane)
private val Point3D.faces
get() = setOf(
Face(this, Plane.XY),
Face(this, Plane.XZ),
Face(this, Plane.YZ),
Face(this.move(dz = 1), Plane.XY),
Face(this.move(dy = 1), Plane.XZ),
Face(this.move(dx = 1), Plane.YZ)
)
private val cubes = input.lines().map(Point3D::parse).toSet()
fun part1(): Int = buildSet {
cubes.flatMap { it.faces }.forEach { face ->
if (!remove(face)) {
add(face)
}
}
}.size
fun part2(): Int {
val faces = cubes.flatMap { it.faces }.toSet()
val maxX = cubes.maxOf { it.x } + 1
val minX = cubes.minOf { it.x } - 1
val maxY = cubes.maxOf { it.y } + 1
val minY = cubes.minOf { it.y } - 1
val maxZ = cubes.maxOf { it.z } + 1
val minZ = cubes.minOf { it.z } - 1
val visitedCubes = mutableSetOf<Point3D>()
val visitedFaces = mutableSetOf<Face>()
with(ArrayDeque<Point3D>()) {
add(Point3D.ORIGIN)
while (isNotEmpty()) {
with(removeFirst()) {
if (this !in cubes && this !in visitedCubes) {
visitedCubes.add(this)
visitedFaces.addAll(faces.intersect(this.faces))
addAll(listOf(
move(dx = 1),
move(dx = -1),
move(dy = 1),
move(dy = -1),
move(dz = 1),
move(dz = -1)
).filter { it.x in minX..maxX && it.y in minY..maxY && it.z in minZ..maxZ })
}
}
}
}
return visitedFaces.size
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 2,005 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/ch/uzh/ifi/seal/bencher/prioritization/search/PermutationNeighborhood.kt | chrstphlbr | 227,602,878 | false | {"Kotlin": 918163, "Java": 29153} | package ch.uzh.ifi.seal.bencher.prioritization.search
import org.uma.jmetal.solution.permutationsolution.PermutationSolution
import org.uma.jmetal.util.neighborhood.Neighborhood
// Implementation of a test suite neighborhood as defined in Li et al. "Search Algorithms for Regression Test Case Prioritization"
// The neighborhood is defined by all orderings where the first variable is swapped with each other variable
class PermutationNeighborhood<T> : Neighborhood<PermutationSolution<T>> {
// do not pick neighbors within the solutionList, but compute the neighbors for the solution at the index
override fun getNeighbors(
solutionList: List<PermutationSolution<T>>,
solutionIndex: Int,
): List<PermutationSolution<T>> {
if (solutionList.isEmpty()) {
throw IllegalArgumentException("solutionList is empty")
}
if (solutionIndex < 0 || solutionIndex >= solutionList.size) {
throw IllegalArgumentException("illegal solutionIndex $solutionIndex (solutionList.size == ${solutionList.size})")
}
val s = solutionList[solutionIndex]
return getNeighbors(s)
}
private fun getNeighbors(s: PermutationSolution<T>): List<PermutationSolution<T>> {
val l = s.variables().size
if (l == 1) {
return listOf()
}
val first = s.variables()[0]
return (1 until l).map { i ->
val neighbor = s.copy() as PermutationSolution<T>
neighbor.variables()[0] = neighbor.variables()[i]
neighbor.variables()[i] = first
neighbor
}
}
}
| 0 | Kotlin | 2 | 4 | 06601fb4dda3b2996c2ba9b2cd612e667420006f | 1,629 | bencher | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2017/Day23.kt | tginsberg | 112,672,087 | false | null | /*
* Copyright (c) 2017 by <NAME>
*/
package com.ginsberg.advent2017
/**
* AoC 2017, Day 23
*
* Problem Description: http://adventofcode.com/2017/day/23
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day23/
*/
class Day23(private val input: List<String>) {
fun solvePart1(): Long =
Machine().runUntilStop(input).debug["mul"] ?: 0
fun solvePart2(): Int {
val b = input.first().split(" ")[2].toInt() * 100 + 100000
return (b.. b+17000 step 17).count {
!it.toBigInteger().isProbablePrime(2)
}
}
data class Machine(private val registers: MutableMap<String, Long> = mutableMapOf(),
private var pc: Int = 0,
val debug: MutableMap<String, Long> = mutableMapOf()) {
fun runUntilStop(instructions: List<String>): Machine {
do {
instructions.getOrNull(pc)?.let {
execute(it)
}
} while (pc in 0 until instructions.size)
return this
}
private fun execute(instruction: String) {
val parts = instruction.split(" ")
debug[parts[0]] = debug.deref(parts[0]) + 1
when (parts[0]) {
"set" -> registers[parts[1]] = registers.deref(parts[2])
"sub" -> registers[parts[1]] = registers.deref(parts[1]) - registers.deref(parts[2])
"mul" -> registers[parts[1]] = registers.deref(parts[1]) * registers.deref(parts[2])
"jnz" -> if (registers.deref(parts[1]) != 0L) {
pc += registers.deref(parts[2]).toInt().dec()
}
else -> throw IllegalArgumentException("No such instruction ${parts[0]}")
}
pc += 1
}
}
}
| 0 | Kotlin | 0 | 15 | a57219e75ff9412292319b71827b35023f709036 | 1,833 | advent-2017-kotlin | MIT License |
src/main/List.kt | ivan-moto | 162,077,405 | false | {"Kotlin": 21137} | import java.util.Objects
import kotlin.math.max
fun <T> all(list: List<T>, predicate: (T) -> Boolean): Boolean =
list.all(predicate)
fun <T> allEqual(list: List<T>): Boolean =
if (list.isEmpty()) false else list.all { it == list[0] }
fun <T> any(list: List<T>, predicate: (T) -> Boolean): Boolean =
list.any(predicate)
fun <T> bifurcate(list: List<T>, filter: List<Boolean>): Pair<List<T>, List<T>> {
require(list.size == filter.size)
return list.zip(filter).partition { it.second }
.let { (list1, list2) -> list1.map { it.first } to list2.map { it.first } }
}
fun <T> bifurcateBy(list: List<T>, predicate: (T) -> Boolean): Pair<List<T>, List<T>> =
list.partition(predicate)
fun <T> chunk(list: List<T>, size: Int): List<List<T>> =
list.chunked(size)
fun <T> combinations(list: List<T>): List<List<T>> = TODO()
fun <T> compact(list: List<T?>): List<T> {
fun isTruthy(t: T?): Boolean = when(t) {
null -> false
is Boolean -> t
is Double -> !t.isNaN()
is Number -> t.toInt() != 0
is String -> !t.isEmpty()
is Array<*> -> t.size != 0
is Collection<*> -> !t.isEmpty()
else -> true
}
@Suppress("UNCHECKED_CAST")
return list.filter(::isTruthy) as List<T>
}
fun <T, K> countBy(list: List<T>, function: (T) -> K): Map<K, Int> =
list.groupingBy(function).eachCount()
fun <T> countOccurrences(list: List<T>, target: T, equals: (T, T) -> Boolean = Objects::equals): Int =
list.count { equals(target, it) }
fun <T> concat(first: List<T>, vararg others: List<T>): List<T> =
first.asSequence().plus(others.asSequence().flatten()).toList()
fun <T, U> corresponds(first: List<T>, second: List<U>, predicate: (T, U) -> Boolean): Boolean =
(first.size == second.size) && (first.zip(second).all { (t, u) -> predicate(t, u) })
fun <T, U> crossProduct(first: List<T>, second: List<U>): List<Pair<T, U>> =
first.flatMap { a -> second.map { b -> a to b } }
fun <T> cycle(list: List<T>): Sequence<T> =
generateSequence(if (list.isNotEmpty()) 0 else null) { (it + 1) % list.size }
.map { list[it] }
fun <T> difference(first: List<T>, second: List<T>): List<T> =
(first subtract second).toList()
fun <T, R> differenceBy(first: List<T>, second: List<T>, function: (T) -> R): List<T> =
with(second.toSet().map(function)) {
first.filterNot { contains(function(it)) }
}
fun <T> differenceWith(first: List<T>, second: List<T>, function: (T, T) -> Boolean): List<T> =
first.filter { a -> second.none { b -> function(a, b) } }
fun <T> distinct(list: List<T>): List<T> =
list.distinct()
fun <T> drop(list: List<T>, n: Int): List<T> =
list.drop(n)
fun <T> dropRight(list: List<T>, n: Int): List<T> =
list.dropLast(n)
fun <T> dropRightWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.dropLastWhile(predicate)
fun <T> dropWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.dropWhile(predicate)
fun <T> endsWith(list: List<T>, subList: List<T>): Boolean =
list.takeLast(subList.size) == subList
fun <T> everyNth(list: List<T>, nth: Int): List<T> =
list.windowed(nth, nth, partialWindows = false).map { it.last() }
fun <T> existsUnique(list: List<T>, predicate: (T) -> Boolean): Boolean {
var exists = false
for (t in list) {
if (predicate(t)) {
if (exists) {
return false
} else {
exists = true
}
}
}
return exists
}
fun <T> filterNonUnique(list: List<T>): List<T> =
list.distinct()
fun <T, K> filterNonUniqueBy(list: List<T>, function: (T) -> K): List<T> =
list.distinctBy(function)
fun <T> findLast(list: List<T>, predicate: (T) -> Boolean): T? =
list.findLast(predicate)
fun <T> findLastIndex(list: List<T>, predicate: (T) -> Boolean): Int =
list.indexOfLast(predicate)
fun <T> forEachRight(list: List<T>, action: (T) -> Unit): Unit =
list.reversed().forEach(action)
fun <T, K> groupBy(list: List<T>, function: (T) -> K): Map<K, List<T>> =
list.groupBy(function)
fun <T> hasDuplicates(list: List<T>): Boolean =
list.toSet().size != list.size
tailrec fun <T> hasSubList(list: List<T>, subList: List<T>): Boolean =
when {
subList.isEmpty() -> true
list.isEmpty() -> subList.isEmpty()
list.take(subList.size) == subList -> true
else -> hasSubList(list.drop(1), subList)
}
fun <T> head(list: List<T>): T =
list.first()
fun <T> indexOfAll(list: List<T>, target: T): List<Int> =
list.withIndex().filter { it.value == target }.map { it.index }
fun <T> initial(list: List<T>): List<T> =
list.dropLast(1)
fun <T> initialize2DList(width: Int, height: Int, value: T): List<List<T>> =
List(height) { List(width) { value } }
fun initializeListWithRange(start: Int, stop: Int, step: Int): List<Int> =
(start..stop step step).toList()
fun <T> initializeListWithValue(size: Int, value: T): List<T> =
List(size) { value }
fun <T> intersection(first: List<T>, second: List<T>): List<T> =
(first intersect second).toList()
fun <T, R> intersectionBy(first: List<T>, second: List<T>, function: (T) -> R): List<T> =
with(second.toSet().map(function)) {
first.filter { contains(function(it)) }
}
fun <T> intersectionWith(first: List<T>, second: List<T>, function: (T, T) -> Boolean): List<T> =
first.filter { a -> second.any { b -> function(a, b) } }
fun <T> intersperse(list: List<T>, element: T): List<T> =
List(list.size) { index -> listOf(list[index], element) }.flatten().dropLast(1)
fun <T> join(list: List<T>, separator: String = ", "): String =
list.joinToString(separator)
fun <T> last(list: List<T>): T =
list.last()
fun <T> longest(list: List<Collection<T>>): Collection<T>? =
list.maxBy { it.size }
fun <T, R> mapObject(list: List<T>, function: (T) -> R): Map<T, R> =
list.associateWith(function)
fun <T : Comparable<T>> maxN(list: List<T>, n: Int): List<T> =
list.sortedDescending().take(n)
fun <T : Comparable<T>> minN(list: List<T>, n: Int): List<T> =
list.sorted().take(n)
fun <T> none(list: List<T>, predicate: (T) -> Boolean): Boolean =
list.none(predicate)
fun <T> nthElement(list: List<T>, n: Int): T =
list[n]
fun <T> permutations(list: List<T>): List<List<T>> {
fun <T> List<T>.removeAtIndex(index: Int): List<T> = take(index) + drop(index + 1)
fun <T> List<T>.prepend(element: T): List<T> = listOf(element) + this
return when {
list.isEmpty() -> emptyList()
list.size == 1 -> listOf(list)
else -> list.foldIndexed(mutableListOf()) { index, acc, t ->
acc.apply {
addAll(permutations(list.removeAtIndex(index)).map { it.prepend(t) })
}
}
}
}
fun <T> partition(list: List<T>, predicate: (T) -> Boolean): Pair<List<T>, List<T>> =
list.partition(predicate)
fun <T> partitioningBy(list: List<T>, predicate: (T) -> Boolean): Map<Boolean, List<T>> =
list.groupBy(predicate)
fun <T, U, R> product(first: List<T>, second: List<U>, function: (T, U) -> R): List<R> =
first.flatMap { t -> second.map { u -> function(t, u) } }
fun <T> pull(list: List<T>, vararg elements: T): List<T> =
with(elements.toSet()) {
list.filterNot { contains(it) }
}
fun <T> pullAtIndex(list: List<T>, vararg indices: Int): List<T> =
with(indices.toSet()) {
list.filterIndexed { index, _ -> !contains(index) }
}
fun <T> pullAtValue(list: List<T>, vararg elements: T): List<T> =
with(elements.toSet()) {
list.filter { contains(it) }
}
fun <T, R> reduceSuccessive(list: List<T>, identity: R, function: (R, T) -> R): List<R> {
fun <T> List<T>.lastOrElse(t: T): T = lastOrNull() ?: t
return list.fold(emptyList()) { acc, t -> acc + function(acc.lastOrElse(identity), t) }
}
fun <T> reject(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.filterNot(predicate)
fun <T> remove(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.filter(predicate)
fun <T> rotateLeft(list: List<T>, n: Int): List<T> =
list.drop(n % list.size) + list.take(n % list.size)
fun <T> rotateRight(list: List<T>, n: Int): List<T> =
list.takeLast(n % list.size) + list.dropLast(n % list.size)
fun <T> sample(list: List<T>): T =
list.random()
fun <T> sampleSize(list: List<T>, n: Int): List<T> =
list.shuffled().take(n)
fun <T> segmentLength(list: List<T>, predicate: (T) -> Boolean): Int =
list.fold(0 to 0) { (longest, current), t -> if (predicate(t)) longest to current + 1 else max(longest, current) to 0 }.first
fun <T> shank(list: List<T>, start: Int = 0, deleteCount: Int = 0, vararg elements: T): List<T> =
list.slice(0 until start) + elements + list.drop(start + deleteCount)
fun <T> shuffle(list: List<T>): List<T> =
list.shuffled()
fun <T, R> slideBy(list: List<T>, classifier: (T) -> R): List<List<T>> {
tailrec fun slideBy_(list: List<T>, acc: MutableList<List<T>>): MutableList<List<T>> =
if (list.isEmpty())
acc
else
slideBy_(list.dropWhile { classifier(it) == classifier(list.first()) }, acc.apply { add(list.takeWhile { classifier(it) == classifier(list.first()) } )} )
return slideBy_(list, mutableListOf())
}
fun <T> segmentLength1(list: List<T>, predicate: (T) -> Boolean): Int =
list.windowed(max(list.size, 1), partialWindows = true)
.map { it.takeWhile(predicate).size }
.max() ?: 0
fun <T : Comparable<T>> sortOrder(list: List<T>): Int =
with(list.sorted()) {
when {
this == list -> 1
this.asReversed() == list -> -1
else -> 0
}
}
fun <T> span(list: List<T>, predicate: (T) -> Boolean): Pair<List<T>, List<T>> =
list.takeWhile(predicate) to list.dropWhile(predicate)
fun <T> splitAt(list: List<T>, predicate: (T) -> Boolean): Pair<List<T>, List<T>> =
list.takeWhile { !predicate(it) } to list.dropWhile { !predicate(it) }
fun <T> startsWith(list: List<T>, subList: List<T>): Boolean =
list.take(subList.size) == subList
fun <T> symmetricDifference(first: List<T>, second: List<T>): List<T> =
((first subtract second) + (second subtract first)).toList()
fun <T, R> symmetricDifferenceBy(first: List<T>, second: List<T>, function: (T) -> R): List<T> {
val mapFirst = first.toSet().map(function)
val mapSecond = second.toSet().map(function)
return first.filterNot { mapSecond.contains(function(it)) } + second.filterNot { mapFirst.contains(function(it)) }
}
fun <T> symmetricDifferenceWith(first: List<T>, second: List<T>, function: (T, T) -> Boolean): List<T> =
first.filter { a -> second.none { b -> function(a ,b) } } +
second.filter { b -> first.none { a -> function(a, b) } }
fun <T> tail(list: List<T>): List<T> =
list.drop(1)
fun <T> take(list: List<T>, n: Int): List<T> =
list.take(n)
fun <T> takeRight(list: List<T>, n: Int): List<T> =
list.takeLast(n)
fun <T> takeRightWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.takeLastWhile(predicate)
fun <T> takeWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.takeWhile(predicate)
fun <T> union(first: List<T>, second: List<T>): List<T> =
(first union second).toList()
fun <T, R> unionBy(first: List<T>, second: List<T>, function: (T) -> R): List<T> {
val mapFirst = first.toSet().map(function)
return (first.toSet() + second.toSet().filterNot { mapFirst.contains(function(it)) }).toList()
}
fun <T> unionWith(first: List<T>, second: List<T>, function: (T, T) -> Boolean): List<T> =
(first.filter { a -> second.any { b -> function(a, b) } } union
second.filter { b -> first.any { a -> function(a, b) } }).toList()
fun <T, U> unzip(list: List<Pair<T, U>>): Pair<List<T>, List<U>> =
list.unzip()
fun <T, U> zip(first: List<T>, second: List<U>): List<Pair<T, U>> =
first.zip(second)
fun <T, U> zipAll(first: List<T>, defaultT: T, second: List<U>, defaultU: U): List<Pair<T, U>> {
val firstIt = first.iterator()
val secondIt = second.iterator()
return object : Iterator<Pair<T, U>> {
override fun hasNext(): Boolean =
firstIt.hasNext() || secondIt.hasNext()
override fun next(): Pair<T, U> {
val t = if (firstIt.hasNext()) firstIt.next() else defaultT
val u = if (secondIt.hasNext()) secondIt.next() else defaultU
return t to u
}
}.asSequence().toList()
}
fun <K, V> zipKeysValues(keys: List<K>, values: List<V>): Map<K, V> =
keys.zip(values).toMap()
fun <T, U, R> zipWith(first: List<T>, second: List<U>, function: (T, U) -> R): List<R> =
first.zip(second).map { (t, u) -> function(t, u) }
fun <T> zipWithIndex(list: List<T>): List<Pair<Int, T>> =
list.withIndex().map { it.index to it.value }
fun <T> zipWithNext(list: List<T>): List<Pair<T, T>> =
list.zipWithNext()
| 0 | Kotlin | 17 | 251 | 772896cb8d835c66a6e543c0c5a3f0aacea492c2 | 12,974 | 30-seconds-of-kotlin | MIT License |
src/main/kotlin/g0301_0400/s0388_longest_absolute_file_path/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0301_0400.s0388_longest_absolute_file_path
// #Medium #String #Depth_First_Search #Stack
// #2022_11_24_Time_150_ms_(100.00%)_Space_33.6_MB_(100.00%)
import java.util.ArrayDeque
import java.util.Deque
class Solution {
fun lengthLongestPath(input: String): Int {
val stack: Deque<Int> = ArrayDeque()
var longestLen = 0
var currDirLen = 0
var i = 0
var currLevel: Int
var nextLevel = 0
var isFile = false
val period = '.'
val space = ' '
while (i < input.length) {
currLevel = nextLevel
var currStrLen = 0
while (i < input.length &&
(Character.isLetterOrDigit(input[i]) || period == input[i] || space == input[i])
) {
if (period == input[i]) {
isFile = true
}
i++
currStrLen++
}
if (isFile) {
longestLen = Math.max(longestLen, currDirLen + currStrLen)
} else {
currDirLen += currStrLen + 1
stack.push(currStrLen + 1)
}
nextLevel = 0
// increment one to let it pass "\n" and start from "\t"
i = i + 1
while (i < input.length - 1 && input[i] == '\t') {
nextLevel++
i = i + 1
}
if (nextLevel < currLevel) {
var j = 0
if (isFile) {
while (stack.isNotEmpty() && j < currLevel - nextLevel) {
currDirLen -= stack.pop()
j++
}
} else {
while (stack.isNotEmpty() && j <= currLevel - nextLevel) {
currDirLen -= stack.pop()
j++
}
}
} else if (nextLevel == currLevel && !isFile && stack.isNotEmpty()) {
currDirLen -= stack.pop()
}
if (nextLevel == 0) {
currDirLen = 0
stack.clear()
}
isFile = false
}
return longestLen
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,220 | LeetCode-in-Kotlin | MIT License |
src/com/ncorti/aoc2023/Day06.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
fun main() {
fun part1(): Int {
val (time, distance) = getInputAsText("06") {
split("\n").filter(String::isNotBlank).map {
it.split(" ").filter(String::isNotBlank).drop(1).map(String::toInt)
}
}
val wins = IntArray(time.size) { 0 }
for (i in time.indices) {
val timeLimit = time[i]
val record = distance[i]
for (speed in 1..timeLimit) {
if (((timeLimit - speed) * speed) > record) {
wins[i]++
}
}
}
return wins.fold(1) { acc, i -> acc * i }
}
fun part2(): Long {
val (time, distance) = getInputAsText("06") {
split("\n").filter(String::isNotBlank).map {
it.split(" ").filter(String::isNotBlank).drop(1).joinToString("").toLong()
}
}
var wins = 0L
for (speed in 1..time) {
if (((time - speed) * speed) > distance) {
wins++
}
}
return wins
}
println(part1())
println(part2())
}
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 1,146 | adventofcode-2023 | MIT License |
tasks-3/lib/src/main/kotlin/flows/algo/NetworkPathFinder.kt | AzimMuradov | 472,473,231 | false | {"Kotlin": 127576} | package flows.algo
import flows.algo.PathFindingMode.BFS
import flows.algo.PathFindingMode.DFS
import flows.structures.Matrix
import flows.structures.Network
/**
* Find path in the [network][this] that can be valid flow in the [residual network][residualNetworkCapacities] using given [mode].
*/
internal fun <V> Network<V>.findPosPath(
mode: PathFindingMode,
residualNetworkCapacities: Matrix<V, UInt>,
) = when (mode) {
DFS -> dfsOrBfs(residualNetworkCapacities, popOp = ArrayDeque<V>::removeLast)
BFS -> dfsOrBfs(residualNetworkCapacities, popOp = ArrayDeque<V>::removeFirst)
}
/**
* Path finding mode. Either [Depth-First Search][DFS] or [Breadth-First Search][BFS].
*/
internal enum class PathFindingMode { DFS, BFS }
private inline fun <V> Network<V>.dfsOrBfs(
residualNetworkCapacities: Matrix<V, UInt>,
popOp: (ArrayDeque<V>) -> V,
): Sequence<Pair<V, V>> {
val parents: MutableMap<V, V?> = graph.vertices.associateWithTo(mutableMapOf()) { null }
val isVisited = graph.vertices.associateWithTo(mutableMapOf()) { false }.apply {
set(source, true)
}
val deque = ArrayDeque<V>().apply {
add(source)
}
while (deque.isNotEmpty()) {
val v = popOp(deque)
for ((u, cap) in residualNetworkCapacities[v]) {
if (!isVisited.getValue(u) && cap != 0u) {
parents[u] = v
if (u != sink) {
isVisited[u] = true
deque.add(u)
} else {
break
}
}
}
}
return generateSequence(sink) { v -> parents.getValue(v) }.zipWithNext()
}
| 0 | Kotlin | 0 | 0 | 01c0c46df9dc32c2cc6d3efc48b3a9ee880ce799 | 1,668 | discrete-math-spbu | Apache License 2.0 |
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day08/HauntedWasteland.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2023.day08
import de.havox_design.aoc.utils.kotlin.model.directions.LeftRightDirection
import java.util.regex.Pattern
class HauntedWasteland(private var filename: String) {
private val PATTERN_GROUP_NODE_NAME = "nodeName"
private val PATTERN_GROUP_LEFT_NODE_NAME = "leftNodeName"
private val PATTERN_GROUP_RIGHT_NODE_NAME = "rightNodeName"
private val NODE_PATTERN = Pattern.compile(
"^(?<${PATTERN_GROUP_NODE_NAME}>\\w+) = " +
"\\((?<${PATTERN_GROUP_LEFT_NODE_NAME}>\\w+), (?<${PATTERN_GROUP_RIGHT_NODE_NAME}>\\w+)\\)$"
)
private val INSTRUCTIONS = ArrayList<LeftRightDirection>()
private val NODES = HashSet<Node>()
fun solvePart1(): Long {
convertInput()
val startNodeName = "AAA"
val endNodeName = "ZZZ"
var steps = 0L
var currentNode = NODES.first { node -> node.name == startNodeName }
var instructionIndex = 0
while (currentNode.name != endNodeName) {
val currentInstruction = INSTRUCTIONS[instructionIndex]
instructionIndex++
instructionIndex %= INSTRUCTIONS.size
currentNode = currentNode.getNode(currentInstruction)
steps++
}
return steps
}
fun solvePart2(): Long {
convertInput()
val startNodeSuffix = "A"
val endNodeSuffix = "Z"
val startNodes = NODES.filter { node -> node.name.endsWith(startNodeSuffix) }
return startNodes
.map { node -> findLoop(node, endNodeSuffix) }
.fold(1L) { acc, i ->
computeLeastCommonMultiple(acc, i.toLong())
}
}
private fun findLoop(start: Node, endNodeSuffix: String): Int {
var index = 0
var current = start
var steps = 0
do {
current = current.getNode(INSTRUCTIONS[index])
index = (index + 1) % INSTRUCTIONS.size
steps++
} while (!current.name.endsWith(endNodeSuffix))
return steps
}
private fun computeLeastCommonMultiple(a: Long, b: Long): Long =
a * b / computeGreatestCommonDivisor(a, b)
private fun computeGreatestCommonDivisor(a: Long, b: Long): Long =
if (b == 0L) {
a
} else {
computeGreatestCommonDivisor(b, a % b)
}
private fun convertInput() {
val input = getResourceAsText(filename)
parseInstructions(input[0])
parseNodes(input)
}
private fun parseInstructions(input: String) {
for (char in input.toCharArray()) {
INSTRUCTIONS.add(LeftRightDirection.from(char))
}
}
private fun parseNodes(input: List<String>) {
val nodeInput = ArrayList<Triple<String, String, String>>()
for (index in input.indices) {
if (index <= 1) {
continue
}
val row = input[index]
val matcher = NODE_PATTERN.matcher(row)
matcher.matches()
val nodeName = matcher.group(PATTERN_GROUP_NODE_NAME)
val leftNodeName = matcher.group(PATTERN_GROUP_LEFT_NODE_NAME)
val rightNodeName = matcher.group(PATTERN_GROUP_RIGHT_NODE_NAME)
nodeInput.add(Triple(nodeName, leftNodeName, rightNodeName))
NODES.add(Node(nodeName, null, null))
}
for (entry in nodeInput) {
val nodeName = entry.first
val leftName = entry.second
val rightName = entry.third
val node = NODES.first { n -> n.name == nodeName }
val left = NODES.first { n -> n.name == leftName }
val right = NODES.first { n -> n.name == rightName }
node.setNodes(left, right)
}
}
private fun getResourceAsText(path: String): List<String> =
this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines()
} | 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 3,941 | advent-of-code | Apache License 2.0 |
src/kotlin2022/Day07.kt | egnbjork | 571,981,366 | false | {"Kotlin": 18156} | package kotlin2022
import readInput
const val CD = "$ cd "
const val TOTAL_SPACE = 70000000
const val UPDATE_SPACE = 30000000
fun main() {
val gameInput = readInput("Day07_test")
val currentDirectoryPath = mutableListOf<String>("")
val dirSizes = mutableMapOf<String, Int>()
for (line in gameInput) {
if (line.contains(CD) && line.contains("..")) {
currentDirectoryPath.removeLast()
} else if (line.contains(CD) && !line.contains("/")) {
val directory = line.replace(CD, "")
currentDirectoryPath.add("${currentDirectoryPath.last()}/$directory")
} else if (line[0].isDigit()) {
for(path in currentDirectoryPath) {
val oldSize = (dirSizes[path] ?: 0)
val newSize = oldSize + line.split(" ")[0].toInt()
dirSizes[path] = newSize
}
}
}
println("part1")
println(dirSizes.toList().sortedBy { (_, v) -> v }.filter{ (_, v) -> v < 100_000}.sumOf { (_, v) -> v })
val usedSpace = dirSizes.toList().map{ (_, v) -> v }.maxByOrNull { it } ?: 0
val neededSpace = usedSpace + UPDATE_SPACE - TOTAL_SPACE
println("part2")
if(neededSpace < UPDATE_SPACE) {
println(
dirSizes.toList()
.map { it.second }
.filter { it > neededSpace }.minOf { it }
)
}
} | 0 | Kotlin | 0 | 0 | 1294afde171a64b1a2dfad2d30ff495d52f227f5 | 1,385 | advent-of-code-kotlin | Apache License 2.0 |
src/Day01.kt | bin-wang | 572,801,360 | false | {"Kotlin": 19395} | fun main() {
fun getCalories(input: List<String>): List<Int> {
return input
.split { it.isBlank() }
.map { it.sumOf(Integer::parseInt) }
}
fun part1(input: List<String>): Int {
val calories = getCalories(input)
return calories.max()
}
fun part2(input: List<String>): Int {
val calories = getCalories(input)
return calories.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dca2c4915594a4b4ca2791843b53b71fd068fe28 | 730 | aoc22-kt | Apache License 2.0 |
src/aoc23/Day04.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc23.day04
import kotlin.math.min
import lib.Solution
import lib.Strings.extractInts
import lib.Strings.ints
data class Card(val id: Int, val winningNumbers: Set<Int>, val numbersInHand: Set<Int>) {
fun matches(): Int = (numbersInHand intersect winningNumbers).size
fun point(): Int = (1 shl matches()) / 2
companion object {
fun parse(cardStr: String): Card {
val (idPart, winPart, handPart) = cardStr.split(":", "|")
val id = idPart.extractInts().single()
val winningNumbers = winPart.ints().toSet()
val numbersInHand = handPart.ints().toSet()
return Card(id, winningNumbers, numbersInHand)
}
}
}
typealias Input = List<Card>
typealias Output = Int
private val solution = object : Solution<Input, Output>(2023, "Day04") {
override fun parse(input: String): Input = input.lines().map { Card.parse(it) }
override fun format(output: Output): String = "$output"
override fun part1(input: Input): Output = input.sumOf(Card::point)
override fun part2(input: Input): Output {
val n = input.size
val cards = (1..n).associateWith { 1 }.toMutableMap()
for (id in 1..n) {
val m = input[id - 1].matches()
for (id2 in id + 1..min(id + m, n)) {
cards[id2] = cards[id]!! + cards[id2]!!
}
}
return cards.values.sum()
}
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 1,405 | aoc-kotlin | Apache License 2.0 |
src/Day01.kt | pmellaaho | 573,136,030 | false | {"Kotlin": 22024} | fun main() {
fun part1(input: List<String>): Int {
var max = 0
val value = input.fold(0) { r, t ->
try {
t.toInt() + r
} catch (e: Exception) {
if (r > max) max = r
0
}
}
return if (max > value) max else value
}
fun part2(input: List<String>): Int {
val list = mutableListOf<Int>()
val value = input.fold(0) { r, t ->
try {
t.toInt() + r
} catch (e: Exception) {
list.add(r)
0
}
}
list.add(value)
list.sortDescending()
return list.take(3)
.reduce { s,t -> s+t }
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// val res = part2(testInput)
// check(res == 45000)
val input = readInput("Day01")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cd13824d9bbae3b9debee1a59d05a3ab66565727 | 1,015 | AoC_22 | Apache License 2.0 |
src/main/kotlin/com/leetcode/P241.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package com.leetcode
// https://leetcode.com/problems/different-ways-to-add-parentheses/
class P241 {
private val ops = setOf('+', '-', '*')
fun diffWaysToCompute(expression: String): List<Int> {
val values = mutableListOf<Int>()
// 연산자를 만나면 왼쪽 계산식과 오른쪽 계산식을 나눠서 재귀
expression.forEachIndexed { i, ch ->
if (ch in ops) {
val left = diffWaysToCompute(expression.substring(0, i))
val right = diffWaysToCompute(expression.substring(i + 1))
values += merge(left, right, ch)
}
}
// 연산자가 없고 숫자만 있을 경우
if (values.isEmpty()) {
values += expression.toInt()
}
return values
}
private fun merge(left: List<Int>, right: List<Int>, op: Char) = mutableListOf<Int>().apply {
for (l in left) {
for (r in right) {
when (op) {
'+' -> this += l + r
'-' -> this += l - r
'*' -> this += l * r
}
}
}
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,161 | algorithm | MIT License |
src/main/kotlin/aoc2021/Day18.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.max
private sealed class SnailfishNumber(var parent: SnailfishPair?) {
protected abstract fun explode(currentLevel: Int): Boolean
abstract fun split(): Boolean
abstract fun getMostRightPrimitive(): SnailfishPrimitive
abstract fun getMostLeftPrimitive(): SnailfishPrimitive
fun reduce(): SnailfishNumber {
var changed: Boolean
do {
do {
changed = explode(0)
} while (changed)
changed = split()
} while (changed)
return this
}
protected fun replaceMeWith(other: SnailfishNumber) {
if (parent?.left == this) {
parent?.left = other
} else if (parent?.right == this) {
parent?.right = other
}
if (this is SnailfishPair && other is SnailfishPair) {
this.left.parent = other
this.right.parent = other
}
}
protected fun getRoot(): SnailfishNumber = (parent as SnailfishNumber?)?.getRoot() ?: this
operator fun plus(other: SnailfishNumber): SnailfishPair {
var root = getRoot()
val result = SnailfishPair(this, other, parent)
if (parent == null) {
// we are already the root -> create new one
root = result
this.parent = root
} else {
replaceMeWith(result)
}
other.parent = result
root.reduce()
return result
}
abstract fun getMagnitude(): Int
companion object {
fun parseString(input: String): SnailfishNumber {
if (input.startsWith("[")) {
var braces = 0
for (i in input.withIndex()) {
val c = i.value
if (c == '[') {
braces++
} else if (c == ']') {
braces--
} else if (c == ',' && braces == 1) {
val left = parseString(input.substring(1, i.index))
val right = parseString(input.substring(i.index + 1, input.length - 1))
val newPair = SnailfishPair(left, right, null)
newPair.right.parent = newPair
newPair.left.parent = newPair
return newPair
}
}
throw IllegalArgumentException("Can not parse Snailfish number for input '$input'")
} else {
return SnailfishPrimitive(input.toInt(), null)
}
}
}
}
private class SnailfishPrimitive(var value: Int, parent: SnailfishPair?) : SnailfishNumber(parent) {
override fun explode(currentLevel: Int) = false
override fun split(): Boolean {
if (value > 9) {
val left = SnailfishPrimitive(floor(value / 2f).toInt(), null)
val right = SnailfishPrimitive(ceil(value / 2f).toInt(), null)
val newNumber = SnailfishPair(left, right, parent)
left.parent = newNumber
right.parent = newNumber
replaceMeWith(newNumber)
return true
}
return false
}
override fun getMostRightPrimitive() = this
override fun getMostLeftPrimitive() = this
override fun getMagnitude() = value
override fun toString() = "$value"
}
private class SnailfishPair(var left: SnailfishNumber, var right: SnailfishNumber, parent: SnailfishPair?) :
SnailfishNumber(parent) {
override fun explode(currentLevel: Int): Boolean {
return if (currentLevel >= 4) {
val leftNeighbour = parent?.getLeftNeighbourOf(this)
val rightNeighbour = parent?.getRightNeighbourOf(this)
if (leftNeighbour != null) {
leftNeighbour.value += (left as SnailfishPrimitive).value
} else {
parent!!.left = SnailfishPrimitive(0, parent)
}
if (rightNeighbour != null) {
rightNeighbour.value += (right as SnailfishPrimitive).value
} else {
parent!!.right = SnailfishPrimitive(0, parent)
}
if (rightNeighbour != null && leftNeighbour != null) {
if (parent?.left == this) {
parent?.left = SnailfishPrimitive(0, parent)
} else if (parent?.right == this) {
parent?.right = SnailfishPrimitive(0, parent)
}
}
true
} else if ((left as? SnailfishPair)?.explode(currentLevel + 1) == true) {
true
} else {
(right as? SnailfishPair)?.explode(currentLevel + 1) == true
}
}
private fun getLeftNeighbourOf(child: SnailfishPair): SnailfishPrimitive? {
return if (child == right) {
if (left is SnailfishPair) {
left.getMostRightPrimitive()
} else {
left as SnailfishPrimitive
}
} else if (child == left) {
parent?.getLeftNeighbourOf(this)
} else {
throw IllegalArgumentException("Number $child is not a child of $this")
}
}
private fun getRightNeighbourOf(child: SnailfishPair): SnailfishPrimitive? {
return if (child == right) {
parent?.getRightNeighbourOf(this)
} else if (child == left) {
if (right is SnailfishPair) {
right.getMostLeftPrimitive()
} else {
right as SnailfishPrimitive
}
} else {
throw IllegalArgumentException("Number $child is not a child of $this")
}
}
override fun getMostRightPrimitive() = right.getMostRightPrimitive()
override fun getMostLeftPrimitive() = left.getMostLeftPrimitive()
override fun getMagnitude() = 3 * left.getMagnitude() + 2 * right.getMagnitude()
override fun split() = left.split() || right.split()
override fun toString() = "[$left,$right]"
}
private fun addAll(input: List<String>) = input.map { SnailfishNumber.parseString(it) }
.fold(null) { acc: SnailfishNumber?, other: SnailfishNumber -> acc?.plus(other) ?: other }
private fun part1(input: List<String>) = addAll(input)?.getMagnitude() ?: 0
private fun part2(input: List<String>): Int {
var max = 0
for (i in input.indices) {
for (j in input.indices) {
if (i != j) {
val n1 = SnailfishNumber.parseString(input[i])
val n2 = SnailfishNumber.parseString(input[j])
max = max(max, (n1 + n2).getMagnitude())
}
}
}
return max
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
check((SnailfishNumber.parseString("[1,2]") + SnailfishNumber.parseString("[[3,4],5]")).toString() == "[[1,2],[[3,4],5]]")
check(SnailfishNumber.parseString("[[[[[9,8],1],2],3],4]").reduce().toString() == "[[[[0,9],2],3],4]")
check(SnailfishNumber.parseString("[7,[6,[5,[4,[3,2]]]]]").reduce().toString() == "[7,[6,[5,[7,0]]]]")
check(SnailfishNumber.parseString("[[6,[5,[4,[3,2]]]],1]").reduce().toString() == "[[6,[5,[7,0]]],3]")
// slightly different expected result as our API only provide a "reduce" method (and even that should be private)
check(
SnailfishNumber.parseString("[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]").reduce()
.toString() == "[[3,[2,[8,0]]],[9,[5,[7,0]]]]"
)
check(
SnailfishNumber.parseString("[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]").reduce()
.toString() == "[[3,[2,[8,0]]],[9,[5,[7,0]]]]"
)
check((SnailfishNumber.parseString("[[[[4,3],4],4],[7,[[8,4],9]]]") + SnailfishNumber.parseString("[1,1]")).toString() == "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]")
check(addAll(listOf("[1,1]", "[2,2]", "[3,3]", "[4,4]")).toString() == "[[[[1,1],[2,2]],[3,3]],[4,4]]")
check(addAll(testInput).toString() == "[[[[6,6],[7,6]],[[7,7],[7,0]]],[[[7,7],[7,7]],[[7,8],[9,9]]]]")
check(SnailfishNumber.parseString("[[1,2],[[3,4],5]]").getMagnitude() == 143)
check(part1(testInput) == 4140)
check(part2(testInput) == 3993)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 8,378 | adventOfCode | Apache License 2.0 |
src/main/kotlin/P023_NonAbundantSums.kt | perihanmirkelam | 291,833,878 | false | null | /**
* P23-Non-Abundant Sums
*
* A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
* For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28,
* which means that 28 is a perfect number.
*
* A number n is called deficient if the sum of its proper divisors is less than n
* and it is called abundant if this sum exceeds n.
*
* As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16,
* the smallest number that can be written as the sum of two abundant numbers is 24.
* By mathematical analysis, it can be shown that all integers greater than 28123
* can be written as the sum of two abundant numbers.
* However, this upper limit cannot be reduced any further by analysis
* even though it is known that the greatest number that cannot be expressed as the sum of
* two abundant numbers is less than this limit.
*
* Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
*/
fun p23() {
val upperLimit = 28123; val minAbundant = 12; var sumOfDivisors = 1
val abundantList = mutableListOf<Int>()
val nonAbundantSum = (1 until upperLimit).toMutableList()
for (x in minAbundant until upperLimit) {
for (j in 2 until x) if (x % j == 0) sumOfDivisors += j
if (sumOfDivisors > x) abundantList.add(x)
sumOfDivisors = 1
}
for (x in 1 until upperLimit)
for (abundant in abundantList) {
if (x - abundant >= minAbundant)
if (abundantList.contains(x - abundant)) {
nonAbundantSum.remove(x)
break
} else break
}
println("A23: ${nonAbundantSum.sum()}")
} | 0 | Kotlin | 1 | 3 | a24ac440871220c87419bfd5938f80dc22a422b2 | 1,739 | ProjectEuler | MIT License |
16/src/main/kotlin/AuntGuesser.kt | kopernic-pl | 109,750,709 | false | null | import com.google.common.io.Resources
@Suppress("MagicNumber")
val facts = mapOf(
"children" to 3,
"cats" to 7,
"samoyeds" to 2,
"pomeranians" to 3,
"akitas" to 0,
"vizslas" to 0,
"goldfish" to 5,
"trees" to 3,
"cars" to 2,
"perfumes" to 1
)
fun isEqualTo(value: Int): (Int) -> Boolean = { i: Int -> i == value }
fun greater(value: Int): (Int) -> Boolean = { i: Int -> i > value }
fun lower(value: Int): (Int) -> Boolean = { i: Int -> i < value }
val auntFactsCheckers1: Map<String, (Int) -> Boolean> =
facts.mapValues { (_, fact) -> isEqualTo(fact) }
val auntFactsCheckers2: Map<String, (Int) -> Boolean> =
auntFactsCheckers1 +
listOf(
"cats" to greater(facts["cats"] ?: error("Null value")),
"pomeranians" to lower(facts["pomeranians"] ?: error("Null value")),
"goldfish" to lower(facts["goldfish"] ?: error("Null value")),
"trees" to greater(facts["trees"] ?: error("Null value"))
)
@Suppress("UnstableApiUsage")
fun main() {
val auntMemories = Resources.getResource("input.txt")
.readText().lines()
findAunt(auntMemories, auntFactsCheckers1, ::println)
findAunt(auntMemories, auntFactsCheckers2, ::println)
}
internal fun findAunt(
auntMemories: List<String>,
auntFactsCheckers: Map<String, (Int) -> Boolean>,
auntsConsumer: (List<AuntMemory>) -> Unit
) {
val matchingAunts = AuntMemoriesReader.readMemories(auntMemories)
.filter { (_, memory) -> memory.matches(auntFactsCheckers) }
auntsConsumer(matchingAunts)
}
private fun Map<String, Int>.matches(factCheckers: Map<String, (Int) -> Boolean>): Boolean {
return factCheckers.all { (checkName, check) ->
!this.containsKey(checkName) || check(this[checkName] ?: error("Checker error"))
}
}
data class AuntMemory(val name: String, val memory: Map<String, Int>)
object AuntMemoriesReader {
private const val sueKey = "sue"
private const val mem1Key = "mem1Key"
private const val mem1cntKey = "mem1cntKey"
private const val mem2Key = "mem2Key"
private const val mem2cntKey = "mem2cntKey"
private const val mem3Key = "mem3Key"
private const val mem3cntKey = "mem3cntKey"
private val regex =
(
"(?<$sueKey>Sue \\d+):" +
" (?<$mem1Key>\\w+): (?<$mem1cntKey>\\d+)," +
" (?<$mem2Key>\\w+): (?<$mem2cntKey>\\d+)," +
" (?<$mem3Key>\\w+): (?<$mem3cntKey>\\d+)"
).toRegex()
fun readMemories(s: List<String>): List<AuntMemory> {
return s.mapNotNull { l -> regex.matchEntire(l) }
.map { it.groups }
.map { g ->
AuntMemory(
g[sueKey]!!.value,
mapOf(
g[mem1Key]!!.value to g[mem1cntKey]!!.value.toInt(),
g[mem2Key]!!.value to g[mem2cntKey]!!.value.toInt(),
g[mem3Key]!!.value to g[mem3cntKey]!!.value.toInt()
)
)
}.toList()
}
}
| 0 | Kotlin | 0 | 0 | 06367f7e16c0db340c7bda8bc2ff991756e80e5b | 3,082 | aoc-2015-kotlin | The Unlicense |
NumberOfIslands.kt | ncschroeder | 604,822,497 | false | {"Kotlin": 19399} | /*
https://leetcode.com/problems/number-of-islands/
Given an m x n 2D binary grid `grid` which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
*/
// To solve this, iterate througn all the coordinates. When we find an island that hasn't been checked/visited
// yet, do a depth-first search on the surrounding coordinates to find the whole island.
fun numIslands(grid: Array<CharArray>): Int {
val checkedCoordinates = HashSet<Pair<Int, Int>>()
// checkCoordinate returns true if the coordinate provided is part of an island and hasn't been checked yet.
// Returns false otherwise.
fun checkCoordinate(coordinate: Pair<Int, Int>): Boolean {
val row = coordinate.first
val column = coordinate.second
if (grid.getOrNull(row)?.getOrNull(column) != '1' || coordinate in checkedCoordinates) {
return false
}
checkedCoordinates.add(coordinate)
arrayOf(
Pair(row - 1, column),
Pair(row, column + 1),
Pair(row + 1, column),
Pair(row, column - 1)
)
.forEach { checkCoordinate(it) }
return true
}
var islandCount = 0
for (row in grid.indices) {
for (col in grid.first().indices) {
if (checkCoordinate(Pair(row, col))) {
islandCount++
}
}
}
return islandCount
} | 0 | Kotlin | 0 | 0 | c77d0c8bb0595e61960193fc9b0c7a31952e8e48 | 1,733 | Coding-Challenges | MIT License |
AoC2021day15-Chiton/src/main/kotlin/Main.kt | mcrispim | 533,770,397 | false | {"Kotlin": 29888} | import java.io.File
lateinit var cave: List<List<Int>>
data class Position(val x: Int, val y: Int)
fun main() {
val originalCave = File("data.txt").readLines().map { str -> str.map { c-> c.digitToInt() } }
// For the first part, cave = originalCave.
// For the second part, cave = growCave(originalCave)
cave = growCave(originalCave)
val lastRow = cave.lastIndex
val lastCol = cave[0].lastIndex
val positionsToLook = mutableListOf<Position>()
val cameFrom = mutableMapOf<Position, Position?>()
val untilHere = mutableMapOf<Position, Int>()
val visited = mutableListOf<Position>()
val start = Position(0, 0)
val end = Position(lastRow, lastCol)
cameFrom[start] = null
untilHere[start] = 0
positionsToLook.add(start)
visited.add(start)
while (positionsToLook.isNotEmpty()) {
println(positionsToLook.size)
val current = positionsToLook.removeFirst()
for (nextPosition in neighbours(current, lastRow, lastCol, visited)) {
val untilNow = untilHere[current]?.plus(cave[nextPosition.x][nextPosition.y])
if (cameFrom[nextPosition] == null || untilHere[nextPosition]!! > untilNow!!) {
cameFrom[nextPosition] = current
untilHere[nextPosition] = untilNow!!
positionsToLook.add(nextPosition)
}
}
visited.add(current)
}
println("Risk: ${untilHere[end]}")
}
fun growCave(originalCave: List<List<Int>>): List<List<Int>> {
val bigCave = mutableListOf<MutableList<Int>>()
val nLines = originalCave.size
val nCols = originalCave[0].size
for (line in originalCave) {
bigCave.add(line.toMutableList())
}
repeat(4 * nCols) {
for (line in bigCave) {
val n = line[line.size - 10]
line.add(if (n < 9) n + 1 else 1)
}
}
repeat(4 * nLines) {
val line = mutableListOf<Int>()
for (n in bigCave[bigCave.size - 10]) {
line.add(if (n < 9) n + 1 else 1)
}
bigCave.add(line)
}
return bigCave
}
fun neighbours(
xy: Position,
maxLines: Int = Int.MAX_VALUE,
maxCols: Int = Int.MAX_VALUE,
visited: MutableList<Position>
): List<Position> {
val (line, col) = xy
val positions = mutableListOf<Position>(
Position(line - 1, col),
Position(line, col - 1),
Position(line, col + 1),
Position(line + 1, col)
)
return positions.filter { p -> p.x in 0..maxLines && p.y in 0..maxCols && p !in visited}
}
| 0 | Kotlin | 0 | 0 | ac4aa71c9b5955fa4077ae40fc7e3fc3d5242523 | 2,552 | AoC2021 | MIT License |
workshops/moscow_prefinals2020/day3/e.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package workshops.moscow_prefinals2020.day3
private typealias State = Int
private fun solve() {
val (hei, wid) = readInts()
val field = List(hei) { readLn().toCharArray() }
val state = IntArray(hei) { -1 }
fun arrayToInt(): Int {
var m = 0
for (i in 0 until hei) {
val bits = state[i] and 15
m = m or (bits shl (4 * i))
}
return m
}
fun intToArray(m: Int) {
for (i in 0 until hei) {
val bits = (m shr (4 * i)) and 15
state[i] = if (bits == 15) -1 else bits
}
}
while (true) {
var improved = false
for (y1 in 0 until hei) for (y2 in listOf(y1 - 1, y1 + 1)) if (y2 in 0 until hei) {
for (x1 in 0 until wid) for (x2 in listOf(x1 - 1, x1 + 1)) if (x2 in 0 until wid) {
for (spread in listOf("ce", "ec")) {
if ("" + field[y1][x1] + field[y1][x2] + field[y2][x1] == spread + spread[1]) {
if (field[y2][x2] == spread[0]) return println(-1)
if (field[y2][x2] == '.') improved = true
field[y2][x2] = spread[1]
}
}
}
}
if (!improved) break
}
val init: State = arrayToInt()
var a = mapOf(init to 0)
val inf = hei * wid * 5
var ans = inf
val future = List(hei) { BooleanArray(wid) }
var moreC = false
for (x in wid - 1 downTo 0) for (y in hei - 1 downTo 0) {
future[y][x] = moreC
moreC = moreC || field[y][x] == 'c'
}
for (x in 0 until wid) for (y in 0 until hei) {
val b = mutableMapOf<State, Int>()
val mayTake = (0..1).filter { field[y][x] != "ce"[it] }
for ((stateInt, perimeter) in a) for (take in mayTake) {
intToArray(stateInt)
val left = state[y]
val up = state.getOrElse(y - 1) { -1 }
val leftWall = if (left >= 0) 1 else 0
val upWall = if (up >= 0) 1 else 0
val newPerimeter = perimeter + if (take == 0) 0 else 4 - 2 * leftWall - 2 * upWall
var bad = false
if (take == 0) {
state[y] = -1
bad = (left >= 0) && !state.contains(left)
if (bad) {
if (state.maxOrNull() == -1 && !future[y][x]) ans = minOf(ans, newPerimeter)
}
} else {
when (listOf(left, up).count { it == -1 }) {
2 -> state[y] = hei
1 -> {
state[y] = maxOf(left, up)
if (left == -1 && y + 1 < hei && state[y + 1] == up) bad = true
}
0 -> {
state[y] = up
state.indices.forEach { if (state[it] == left) state[it] = up }
}
}
}
if (bad) continue
val repaint = mutableMapOf<Int, Int>()
for (i in state.indices) {
val c = state[i]
if (c == -1) continue
if (c !in repaint.keys) repaint[c] = repaint.size
state[i] = repaint[c]!!
}
val newStateInt = arrayToInt()
b[newStateInt] = minOf(b.getOrDefault(newStateInt, inf), newPerimeter)
}
a = b
}
ans = minOf(ans, a.filter { intToArray(it.key); state.maxOrNull()!! <= 0 }.values.minOrNull() ?: inf)
println(if (ans < inf) ans else -1)
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 3,019 | competitions | The Unlicense |
src/day01/Day01.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day01
import readInput
fun main() {
fun part1(input: List<String>): Int {
var cur = 0
var maxVal = -1
input.forEach {
if (it == "") {
if (cur > maxVal) {
maxVal = cur
}
cur = 0
} else {
cur += it.toInt()
}
}
if (cur > maxVal) {
maxVal = cur
}
return maxVal
}
fun part2(input: List<String>): Int {
val calories = mutableListOf<Int>()
var cur = 0
input.forEach {
if (it == "") {
calories.add(cur)
cur = 0
} else {
cur += it.toInt()
}
}
calories.add(cur)
calories.sort()
return calories.get(calories.lastIndex) + calories.get(calories.lastIndex - 1) + calories.get(calories.lastIndex - 2)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(1, true)
check(part1(testInput) == 24000)
val input = readInput(1)
println(part1(input))
check(part2(testInput) == 45000)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 1,220 | advent-of-code-2022 | Apache License 2.0 |
test/leetcode/DetermineColorOfAChessboardSquare.kt | andrej-dyck | 340,964,799 | false | null | package leetcode
import leetcode.SquareColor.*
import lib.isEven
import lib.require
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
/**
* https://leetcode.com/problems/determine-color-of-a-chessboard-square/description/
*
* 1812. Determine Color of a Chessboard Square
* [Easy]
*
* You are given coordinates, a string that represents the coordinates of a square of the chessboard.
* Below is a chessboard for your reference.
*
* 8 w b w b w b w b
* 7 b w b w b w b w
* 6 w b w b w b w b
* 5 b w b w b w b w
* 4 w b w b w b w b
* 3 b w b w b w b w
* 2 w b w b w b w b
* 1 b w b w b w b w
* A B C D E F G H
*
* Return true if the square is white, and false if the square is black.
*
* The coordinate will always represent a valid chessboard square.
* The coordinate will always have the letter first, and the number second.
*
* Constraints:
* - coordinates.length == 2
* - 'a' <= coordinates[0] <= 'h'
* - '1' <= coordinates[1] <= '8'
*/
fun squareIsWhite(coordinate: String) = squareColor(coordinate) == WHITE
fun squareIsBlack(coordinate: String) = squareColor(coordinate) == BLACK
enum class SquareColor { WHITE, BLACK }
fun squareColor(coordinate: String) =
if (coordinatePair(coordinate).isEven()) BLACK else WHITE
private fun coordinatePair(coordinate: String) =
coordinate
.require { it.length == 2 }
.let { coordinateValue(it.first()) to coordinateValue(it.last()) }
private fun coordinateValue(c: Char) = when (c) {
in 'a'..'h' -> c - 'a' + 1
in '1'..'8' -> c.digitToInt()
else -> throw IllegalArgumentException()
}
private fun Pair<Int, Int>.isEven() = (first + second).isEven()
/**
* Unit Tests
*/
class DetermineColorOfAChessboardSquareTest {
@ParameterizedTest
@ValueSource(
strings = [
"a1", "c1", "e1", "g1",
"b2", "d2", "f2", "h2",
"a3", "c3", "e3", "g3",
"b4", "d4", "f4", "h4",
"a5", "c5", "e5", "g5",
"b6", "d6", "f6", "h6",
"a7", "c7", "e7", "g7",
"b8", "d8", "f8", "h8"
]
)
fun `black squares are`(coordinate: String) {
assertThat(
squareIsBlack(coordinate)
).`as`("$coordinate must be black square").isTrue
}
@ParameterizedTest
@ValueSource(
strings = [
"b1", "d1", "f1", "h1",
"a2", "c2", "e2", "g2",
"b3", "d3", "f3", "h3",
"a4", "c4", "e4", "g4",
"b5", "d5", "f5", "h5",
"a6", "c6", "e6", "g6",
"b7", "d7", "f7", "h7",
"a8", "c8", "e8", "g8"
]
)
fun `white squares are`(coordinate: String) {
assertThat(
squareIsWhite(coordinate)
).`as`("$coordinate must be white square").isTrue
}
} | 0 | Kotlin | 0 | 0 | 3e3baf8454c34793d9771f05f330e2668fda7e9d | 2,909 | coding-challenges | MIT License |
Kotlin/MergeSort.kt | sukritishah15 | 299,329,204 | false | null | /**
* Algorithm: Merge Sorting
* Language: Kotlin
* Input:
* a) n: Size of Array
* b) arr: Integer Array of size n
* Output:
* a) Array before applying Merge Sorting
* b) Array after applying Merge Sorting
* Time Complexity: O(n * log n)
* Space Complexity: O(n)
*
* Sample Input:
* Enter the size of the integer array:
* 5
* Enter an integer array:
* 5 4 8 2 1
*
* Sample Output:
* Array before sorting is:
* 5 4 8 2 1
* Array after sorting is:
* 1 2 4 5 8
*/
import MergeSort.Companion.printIArray
import java.util.*
class MergeSort {
fun mergeSort(array: IntArray) {
val n = array.size
if (n < 2) return
val mid = n / 2
val left = IntArray(mid)
val right = IntArray(n - mid)
for (i in 0 until mid) left[i] = array[i]
for (i in mid until n) right[i - mid] = array[i]
mergeSort(left)
mergeSort(right)
merge(left, right, array)
}
private fun merge(left: IntArray, right: IntArray, array: IntArray) {
val nLeft = left.size
val nRight = right.size
var i = 0
var j = 0
var k = 0
while (i < nLeft && j < nRight) {
if (left[i] <= right[j]) {
array[k] = left[i]
k++
i++
} else {
array[k] = right[j]
k++
j++
}
}
while (i < nLeft) {
array[k] = left[i]
i++
k++
}
while (j < nRight) {
array[k] = right[j]
j++
k++
}
}
companion object {
fun printIArray(array: IntArray) {
println(array.joinToString(" "))
}
}
}
fun main() {
val scanner = Scanner(System.`in`)
println("Enter the size of the integer array: ")
val n = scanner.nextInt()
println("Enter an integer array: ")
val arr = IntArray(n)
arr.indices.forEach {
arr[it] = scanner.nextInt()
}
val merge = MergeSort()
println("Array before sorting is: ")
printIArray(arr)
merge.mergeSort(arr)
println("Array after sorting is: ")
printIArray(arr)
} | 164 | Java | 295 | 955 | 1b6040f7d9af5830882b53916e83d53a9c0d67d1 | 2,223 | DS-Algo-Point | MIT License |
solutions/src/solutions/y21/day 13.kt | Kroppeb | 225,582,260 | false | null | @file:Suppress("PackageDirectoryMismatch", "UnusedImport")
package solutions.y21.d13
/*
import grid.Clock
import helpers.*
import itertools.*
import kotlin.math.*
*/
import grid.Clock
import helpers.*
val xxxxx = Clock(6, 3);
/*
*/
private fun part1() {
var (paper, folds) = getLines(2021_13).splitOn { it.isEmpty() }
val parsed = folds.map {
(if (it.contains("x=")) 'x' else 'y') to it.getInt()!!
}
val papp = paper.ints()
val maxY = papp.maxBy { it[0] }[0] + 1
val maxX = papp.maxBy { it[1] }[1] + 1
var grid = List(maxX) { x ->
List(maxY) { y -> if (listOf(y, x) in papp) '#' else '.' }
}
var a = grid.take(parsed.first().second)
var b = grid.drop(parsed.first().second + 1).reversed()
if (a.size > b.size) {
b = b + List(a.size - b.size) { List(a.first().size) { '.' } }
} else if (a.size < b.size) {
a = List(b.size - a.size) { List(a.first().size) { '.' } } + a
}
// grid.map{it.log()}
grid = a.zip(b) { a, b ->
a.zip(b) { u, v ->
if (u == v) u else '#'
}
}
// "".log()
// grid.map { it.log() }
grid.flatten().count { it == '#' }.log()
}
private fun part2() {
var (paper, folds) = getLines(2021_13).splitOn { it.isEmpty() }
val parsed = folds.map {
(if (it.contains("x=")) 'x' else 'y') to it.getInt()!!
}
val papp = paper.ints()
val maxY = papp.maxBy { it[0] }[0] + 1
val maxX = papp.maxBy { it[1] }[1] + 1
var grid = List(maxX) { x ->
List(maxY) { y -> if (listOf(y, x) in papp) '#' else '.' }
}
for ((i, j) in parsed) {
if (i == 'x')
grid = grid.transpose()
var a = grid.take(j)
var b = grid.drop(j + 1).reversed()
if (a.size > b.size) {
b = b + List(a.size - b.size) { List(a.first().size) { '.' } }
} else if (a.size < b.size) {
a = List(b.size - a.size) { List(a.first().size) { '.' } } + a
}
// grid.map{it.log()}
grid = a.zip(b) { a, b ->
a.zip(b) { u, v ->
if (u == v) u else '#'
}
}
if (i == 'x')
grid = grid.transpose()
}
"".log()
grid.map { it.log() }
// grid.flatten().count { it == '#' }.log()
// added afterwards
"".log()
grid.map { it.map { if (it == '#') "##" else " " }.joinToString(separator = "").log() }
}
fun main() {
println("Day 13: ")
part1()
part2()
}
fun <T> T.log(): T = also { println(this) } | 0 | Kotlin | 0 | 1 | 744b02b4acd5c6799654be998a98c9baeaa25a79 | 2,567 | AdventOfCodeSolutions | MIT License |
src/main/kotlin/parts/wisdom/simplednn/Learning.kt | deansher | 267,331,452 | false | null | package parts.wisdom.simplednn
import koma.matrix.Matrix
private const val BATCH_SIZE = 20
private const val NUM_EPOCHS = 25
data class Coords(val row: Int, val col: Int) {
constructor(idx: IntArray) :
this(
idx.let {
require(it.size == 2) { "Can't construct Coords from an index of length ${it.size}" }
it[0]
},
idx[1]
)
}
/**
* A training example. The label is a combination of row and column because we use two dimensions for all outputs.
*/
data class Example(
val label: Coords,
val matrix: Matrix<Double>
) {
val shape = Shape(matrix.numRows(), matrix.numCols())
}
data class Shape(
val numRows: Int,
val numCols: Int
) {
fun requireSameShape(x: Example) {
require(x.matrix.numRows() == numRows) {
"example has ${x.matrix.numRows()}; should have $numRows"
}
require(x.matrix.numCols() == numCols) {
"example has ${x.matrix.numCols()}; should have $numCols"
}
}
}
fun requireAllSameShape(xs: List<Example>): Shape {
require(xs.isNotEmpty()) { "must have at least one example" }
val shape = xs[0].shape
for (x in xs) {
shape.requireSameShape(x)
}
return shape
}
data class ExampleSet(val examples: List<Example>) {
val shape = requireAllSameShape(examples)
}
fun pickBatches(examples: ExampleSet, batchSize: Int): List<List<Example>> =
examples.examples.shuffled().chunked(batchSize)
data class EvaluationMetrics(val accuracy: Float)
fun train(
classifier: Classifier,
trainingData: ExampleSet,
testData: ExampleSet
) {
for (epoch in 1..NUM_EPOCHS) {
for (batch in pickBatches(trainingData, BATCH_SIZE) /* debug with .take(1) */) {
val trainer = classifier.makeBatchTrainer()
for (x in batch) {
trainer.train(x.matrix, x.label)
}
trainer.updateParameters()
}
val metrics = evaluate(classifier, testData)
println("After epoch $epoch, $metrics")
}
}
fun evaluate(classifier: Classifier, testData: ExampleSet): EvaluationMetrics {
var numRight = 0
var numWrong = 0
for (x in testData.examples) {
if (classifier.inferClass(x) == x.label) {
numRight++
} else {
numWrong++
}
}
return EvaluationMetrics(numRight.toFloat() / (numRight + numWrong).toFloat())
}
| 0 | Kotlin | 0 | 0 | f4fc329b86f2ef231d5b9e1d982d6acafe275418 | 2,491 | simple-dnn-from-scratch-kotlin | The Unlicense |
pdg/src/main/kotlin/me/haydencheers/nscpdt/pdg/util/GraphEditDistanceEvaluator.kt | hjc851 | 247,242,039 | false | null | package me.haydencheers.nscpdt.pdg.util
import com.automation.graph.HungarianAlgorithm
import org.graphstream.graph.Edge
import org.graphstream.graph.Graph
import org.graphstream.graph.Node
import kotlin.math.max
object GraphEditDistanceEvaluator {
fun evaluate(g1: Graph, g2: Graph) = evaluate(g1, g2, 3.0, 1.0, 1.0)
fun evaluate(g1: Graph, g2: Graph, subCost: Double, insCost: Double, delCost: Double): Double {
val n = g1.nodeCount
val m = g2.nodeCount
val costMatrix = Array(n+m) { DoubleArray(n+m) }
val maxsize = max(n, m)
for (i in 0 until n) {
for (j in 0 until m) {
costMatrix[i][j] = getSubstituteCost(g1.getNode<Node>(i), g2.getNode<Node>(j), subCost, insCost, delCost)
}
}
for (i in 0 until m) {
for (j in 0 until m) {
costMatrix[i + n][j] = getInsertCost(i, j, insCost)
}
}
for (i in 0 until n) {
for (j in 0 until n) {
costMatrix[j][i + m] = getDeleteCost(i, j, delCost)
}
}
val greedyMinCosts = DoubleArray(n+m) { maxsize.toDouble() }
val usedIndicies = mutableSetOf<Int>()
for (i in 0 until (n+m)) {
var minIndex = Int.MAX_VALUE
var min = Double.MAX_VALUE
val row = costMatrix[i]
for (j in 0 until (n+m)) {
if (!usedIndicies.contains(j)) {
if (row[j] < min) {
minIndex = j
min = row[j]
}
}
}
if (minIndex != Int.MAX_VALUE) {
greedyMinCosts[i] = min
usedIndicies.add(minIndex)
}
}
val greedySum = greedyMinCosts.sum()
return greedySum
// val assignment = HungarianAlgorithm.hgAlgorithm(costMatrix, "min")
//
// val mins = costMatrix.map { it.min() ?: Double.MAX_VALUE }
// val costs = assignment.mapIndexed { index, ints -> costMatrix[ints[0]][ints[1]] }
//
// var sum = 0.0
// for (i in 0 until assignment.size) {
// sum += costMatrix[assignment[i][0]][assignment[i][1]]
// }
//
// return sum
}
private fun getSubstituteCost(node1: Node, node2: Node, subCost: Double, insCost: Double, delCost: Double): Double {
val diff = getRelabelCost(node1, node2, subCost) + getEdgeDiff(node1, node2, insCost, subCost, delCost)
return diff * subCost
}
private fun getRelabelCost(node1: Node, node2: Node, subCost: Double): Double {
return if (!equals(node1, node2)) subCost
else 0.0
}
private fun getEdgeDiff(node1: Node, node2: Node, insCost: Double, subCost: Double, delCost: Double): Double {
val edges1 = node1.getEdgeSet<Edge>().toTypedArray()
val edges2 = node2.getEdgeSet<Edge>().toTypedArray()
if (edges1.size == 0 || edges2.size == 0) {
return Math.max(edges1.size, edges2.size).toDouble()
}
val n = edges1.size
val m = edges2.size
val maxsize = max(n, m)
val edgeCostMatrix = Array(n + m) { DoubleArray(m + n) }
for (i in 0 until n) {
for (j in 0 until m) {
edgeCostMatrix[i][j] = getEdgeEditCost(edges1[i], edges2[j], subCost)
}
}
for (i in 0 until m) {
for (j in 0 until m) {
edgeCostMatrix[i + n][j] = getEdgeInsertCost(i, j, insCost)
}
}
for (i in 0 until n) {
for (j in 0 until n) {
edgeCostMatrix[j][i + m] = getEdgeDeleteCost(i, j, delCost)
}
}
val greedyMinCosts = DoubleArray(n+m) { maxsize.toDouble() }
val usedIndicies = mutableSetOf<Int>()
for (i in 0 until (n+m)) {
var minIndex = Int.MAX_VALUE
var min = Double.MAX_VALUE
val row = edgeCostMatrix[i]
for (j in 0 until (n+m)) {
if (!usedIndicies.contains(j)) {
if (row[j] < min) {
minIndex = j
min = row[j]
}
}
}
if (minIndex != Int.MAX_VALUE) {
greedyMinCosts[i] = min
usedIndicies.add(minIndex)
}
}
val greedySum = greedyMinCosts.sum()
return greedySum / (n+m)
// val assignment = HungarianAlgorithm.hgAlgorithm(edgeCostMatrix, "min")
// var sum = 0.0
// for (i in assignment.indices) {
// sum += edgeCostMatrix[assignment[i][0]][assignment[i][1]]
// }
//
// return sum / (n + m)
}
private fun getEdgeEditCost(edge1: Edge, edge2: Edge, subCost: Double): Double {
return (if (equals(edge1, edge2)) 0.0 else subCost)
}
private fun getEdgeInsertCost(i: Int, j: Int, insCost: Double): Double {
return if (i == j) {
insCost
} else java.lang.Double.MAX_VALUE
}
private fun getEdgeDeleteCost(i: Int, j: Int, delCost: Double): Double {
return if (i == j) {
delCost
} else java.lang.Double.MAX_VALUE
}
private fun getInsertCost(i: Int, j: Int, insCost: Double): Double {
return if (i == j) {
insCost
} else java.lang.Double.MAX_VALUE
}
private fun getDeleteCost(i: Int, j: Int, delCost: Double): Double {
return if (i == j) {
delCost
} else java.lang.Double.MAX_VALUE
}
//
// Element Equals
//
fun equals(lhs: Node, rhs: Node): Boolean {
val ltype = lhs.getAttribute<String>("type")
val lvarscope = lhs.getAttribute<String>("pdg.varscope")
val lnodetype = lhs.getAttribute<String>("pdg.nodetype")
val rtype = rhs.getAttribute<String>("type")
val rvarscope = rhs.getAttribute<String>("pdg.varscope")
val rnodetype = rhs.getAttribute<String>("pdg.nodetype")
return ltype == rtype &&
lvarscope == rvarscope &&
lnodetype == rnodetype
}
fun equals(lhs: Edge, rhs: Edge): Boolean {
val ltype = lhs.getAttribute<String>("type")
val lsnoderef = lhs.getAttribute<String>("pdg.snoderef")
val lfnoderef = lhs.getAttribute<String>("pdg.fnoderef")
val rtype = rhs.getAttribute<String>("type")
val rsnoderef = rhs.getAttribute<String>("pdg.snoderef")
val rfnoderef = rhs.getAttribute<String>("pdg.fnoderef")
return ltype == rtype &&
lsnoderef == rsnoderef &&
lfnoderef == rfnoderef
}
} | 0 | Kotlin | 0 | 0 | b697648f04710a58722dfc1b764a3e43e56b4c4a | 6,728 | NaiveSCPDTools | MIT License |
src/day19/Utils.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day19
fun <T> MutableMap<T, Int>.add (t: T, count: Int) {
val already = get (t)
if (already != null) {
put (t, already + count)
} else {
put (t, count)
}
}
fun permutations (pairs: List<Robots>): List<List<Robots>> {
return _permutations (pairs)
.map {
it.filter { it.count != 0 }
}
.filter { it.isNotEmpty () }
.sortedBy { it.size }
}
private fun _permutations (pairs: List<Robots>): List<List<Robots>> {
val res = mutableListOf<List<Robots>> ()
if (pairs.isNotEmpty ()) {
val pair = pairs[0]
if (pairs.size == 1) {
for (count in 0 .. pair.count) {
res.add (listOf (Robots (pair.material, count)))
}
} else {
val rest = _permutations (pairs.subList(1, pairs.size))
for (count in 0 .. pair.count) {
for (el in rest) {
val list = mutableListOf<Robots> (Robots (pair.material, count))
list.addAll (el)
res.add (list)
}
}
}
}
return res
}
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 1,150 | advent_of_code_2022 | Apache License 2.0 |
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12918.kt | boris920308 | 618,428,844 | false | {"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407} | package main.kotlin.programmers.lv01
/**
*
* https://school.programmers.co.kr/learn/courses/30/lessons/12918
*
* 문자열 다루기 기본
* 문제 설명
* 문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요.
* 예를 들어 s가 "a234"이면 False를 리턴하고 "1234"라면 True를 리턴하면 됩니다.
*
* 제한 사항
* s는 길이 1 이상, 길이 8 이하인 문자열입니다.
* s는 영문 알파벳 대소문자 또는 0부터 9까지 숫자로 이루어져 있습니다.
* 입출력 예
* s return
* "a234" false
* "1234" true
*
*/
fun main() {
println(solution("a234"))
println(solution("1234"))
}
private fun solution(s: String): Boolean {
return (s.length == 4 || s.length == 6) && isNumericString(s)
}
private fun isNumericString(s: String): Boolean {
val regex = Regex("""^\d+$""")
return regex.matches(s)
}
private fun solution_1(s: String) = (s.length == 4 || s.length == 6) && s.toIntOrNull() != null | 1 | Kotlin | 1 | 2 | 88814681f7ded76e8aa0fa7b85fe472769e760b4 | 1,043 | HoOne | Apache License 2.0 |
codeforces/polynomial2022/b_slow.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.polynomial2022
import java.util.TreeSet
private fun solve(): String {
val (n, _, k) = readInts()
val a = readInts()
val allow = LongArray(n) { -1 }
val allowed = TreeSet<Long>()
fun encode(count: Int, index: Int) = (count.toLong() shl 32) + index.toLong()
for (i in a.indices) {
allowed.add(encode(a[i], i))
}
for (i in 0 until n) {
if (allow[i] >= 0) allowed.add(allow[i])
val use = allowed.pollLast() ?: return "NO"
val count = (use shr 32).toInt()
val index = use.toInt()
if (count > 1 && i + k < n) allow[i + k] = encode(count - 1, index)
}
return "YES"
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 804 | competitions | The Unlicense |
src/main/kotlin/me/peckb/aoc/_2020/calendar/day07/Day07.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2020.calendar.day07
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
class Day07 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::bagData) { input ->
val bags = bags(input)
val containerBags = mutableSetOf<Bag>()
val bagsToInspect = mutableListOf<Bag>()
bags[SHINY_GOLD_BAG]?.also {
bagsToInspect.addAll(it.getParentContainers())
}
while(bagsToInspect.isNotEmpty()) {
bagsToInspect.removeFirst().also { bag ->
containerBags.add(bag)
bagsToInspect.addAll(bag.getParentContainers())
}
}
containerBags.size
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::bagData) { input ->
val bags = bags(input)
bags[SHINY_GOLD_BAG]?.let { bag ->
bag.getContents().entries.sumOf { (childBag, count) ->
count + (count * childBagCount(childBag))
}
}
}
private fun bags(input: Sequence<Pair<Bag, List<Pair<Bag, Int>>>>): MutableMap<Bag, Bag> {
val bags = mutableMapOf<Bag, Bag>()
input.forEach { (bag, contents) ->
bags.putIfAbsent(bag, bag)
contents.forEach { bags.putIfAbsent(it.first, it.first) }
bags[bag]?.also { parentBag ->
contents.forEach { (childBag, count) ->
bags[childBag]?.also {
it.containedIn(parentBag)
parentBag.addMandatoryContent(it, count)
}
}
}
}
return bags
}
private fun bagData(line: String): Pair<Bag, List<Pair<Bag, Int>>> {
val (outer, inner) = line.dropLast(1) // remove the final `.`
.split(" contain ")
val outerBag = outer.split(" ").take(2).let { (style, colour) -> Bag(style, colour) }
val innerBagData = if (inner.contains("no other bags")) {
emptyList()
} else {
inner.split(", ")
.map { it.split(" ").take(3) }
.map { (count, style, colour) -> Bag(style, colour) to count.toInt()}
}
return outerBag to innerBagData
}
private fun childBagCount(bag: Bag): Int {
return bag.getContents().entries.sumOf { (childBag, count) ->
count + (count * childBagCount(childBag))
}
}
data class Bag(val style: String, val colour: String) {
private val mandatoryContents: MutableMap<Bag, Int> = mutableMapOf()
private val parentContainers: MutableSet<Bag> = mutableSetOf()
fun addMandatoryContent(bag: Bag, count: Int) {
if (mandatoryContents.containsKey(bag)) {
throw IllegalStateException("Bag was already specified as a mandatory content.")
}
mandatoryContents[bag] = count
}
fun getContents(): Map<Bag, Int> {
return mandatoryContents.toMap()
}
fun containedIn(bag: Bag) {
parentContainers.add(bag)
}
fun getParentContainers(): Set<Bag> {
return parentContainers.toSet()
}
}
companion object {
private val SHINY_GOLD_BAG = Bag("shiny", "gold")
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 3,069 | advent-of-code | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.