kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
ummen-sherry__adventofcode2023__c91c1b6/src/main/kotlin/Day2.kt | import java.util.Locale
import java.util.Optional
import kotlin.jvm.optionals.getOrDefault
data class GameLimit(val redLimit: Int = 12, val greenLimit: Int = 13, val blueLimit: Int = 14)
fun GameLimit.isValid(color: String, count: Int): Boolean {
return when (color.lowercase(Locale.getDefault())) {
"red" -> this.redLimit >= count
"green" -> this.greenLimit >= count
"blue" -> this.blueLimit >= count
else -> false
}
}
private val gameLimit = GameLimit()
fun sumOfIDOfLegitGames(input: List<String>): Int {
return input.sumOf {
val limitExceededGameId = getLimitExceededGameId(it).getOrDefault(0)
limitExceededGameId
}
}
fun getLimitExceededGameId(gameInput: String): Optional<Int> {
val regex = Regex("Game (\\d+): (.*)")
val matchResult = regex.find(gameInput)
val groups = matchResult?.groupValues!!
val didLimitExceed = didLimitExceed(groups[1].toInt(), groups[2])
return if (!didLimitExceed) Optional.of(groups[1].toInt()) else Optional.empty<Int>()
}
fun didLimitExceed(gameId: Int, gameColorInput: String): Boolean {
val numberRegex = Regex("""(\d+) (\w+)""")
val numberMatches = numberRegex.findAll(gameColorInput)
numberMatches.forEach { matchResult ->
val groups = matchResult.groupValues
val count = groups[1].toInt()
val color = groups[2]
if (!gameLimit.isValid(color = color, count)) return true
}
return false
}
fun sumOfIDAndPowerOfLegitGames(input: List<String>): Int {
return input.sumOf {
val (gameId, power) = getMinPowerAndGameId(it)
if (gameId != 0) {
println("Game $gameId: Minimum Power = $power")
}
power
}
}
fun getMinPowerAndGameId(gameInput: String): Pair<Int, Int> {
val regex = Regex("Game (\\d+): (.*)")
val matchResult = regex.find(gameInput)
val groups = matchResult?.groupValues!!
val gameId = groups[1].toInt()
val minPower = calculateMinPower(groups[2])
return Pair(gameId, minPower)
}
fun calculateMinPower(gameColorInput: String): Int {
val numberRegex = Regex("""(\d+) (\w+)""")
val numberMatches = numberRegex.findAll(gameColorInput)
var maxRed = 1
var maxGreen = 1
var maxBlue = 1
for (matchResult in numberMatches) {
val groups = matchResult.groupValues
val count = groups[1].toInt()
val color = groups[2]
when (color) {
"red" -> maxRed = maxOf(maxRed, count)
"green" -> maxGreen = maxOf(maxGreen, count)
"blue" -> maxBlue = maxOf(maxBlue, count)
}
}
return maxRed * maxGreen * maxBlue
}
fun main(args: Array<String>) {
println("Advent 2023 - Day2")
val input = readFile("day-2-input1.txt")
// Part 1
// val sumOfIDOfLegitGames = sumOfIDOfLegitGames(input)
//
// println("Sum: $sumOfIDOfLegitGames")
// Part2
val sumOfIDAndPowerOfLegitGames = sumOfIDAndPowerOfLegitGames(input)
println("Sum: $sumOfIDAndPowerOfLegitGames")
} | [
{
"class_path": "ummen-sherry__adventofcode2023__c91c1b6/Day2Kt.class",
"javap": "Compiled from \"Day2.kt\"\npublic final class Day2Kt {\n private static final GameLimit gameLimit;\n\n public static final boolean isValid(GameLimit, java.lang.String, int);\n Code:\n 0: aload_0\n 1: ldc ... |
ShuffleZZZ__ITMO__29db54d/ParallelProgramming/possible-executions-analysis/src/PossibleExecutionsVerifier.kt | import java.io.*
import java.util.*
const val SOLUTION_FILE_NAME = "solution.txt"
val STATE_REGEX = Regex("\\[P([1-4]),Q([1-4]),([01]),([01])]")
fun main() {
val transitions = mutableSetOf<Transition>()
File(SOLUTION_FILE_NAME).readLines().forEachIndexed { index, line ->
val trim = line.substringBefore('#').trim()
try {
if (trim.isNotEmpty()) {
val t = parseTransition(trim)
require(transitions.add(t)) { "Duplicate transition $t" }
}
} catch (e: IllegalArgumentException) {
error("At $SOLUTION_FILE_NAME:${index + 1}: ${e.message}")
}
}
val states = transitions
.groupBy({ it.from }, { it.to })
.mapValues { it.value.toSet() }
.toMutableMap()
for (s in states.values.flatten()) {
if (s !in states) states[s] = emptySet()
}
val initial = State(1, 1, 0, 0)
// check initial state
require(initial in states) { "Must contain transition from initial state $initial" }
// check complete transitions out of each state
for ((from, tos) in states) {
val expected = mutableSetOf<State>()
from.moveP().let { expected += it }
from.moveQ()?.let { expected += it }
require(expected.size == tos.size) { "Unexpected number of transitions (${tos.size}) from state $from" }
for (e in expected) {
require(e in tos) { "Missing transition from state $from" }
}
}
// check reachability of all states
val queue = ArrayDeque<State>()
val reached = HashSet<State>()
fun mark(state: State) { if (reached.add(state)) queue += state }
mark(initial)
while (!queue.isEmpty()) {
val from = queue.removeFirst()
for (to in states[from]!!) mark(to)
}
for (state in states.keys) {
require(state in reached) { "State $state in never reached from the initial state" }
}
}
data class State(val p: Int, val q: Int, val a: Int, val b: Int) {
override fun toString(): String = "[P$p,Q$q,$a,$b]"
fun moveP(): State = when(p) { // while true:
1 -> copy(p = 2, a = 1) // 1: a = 1
2 -> if (b != 0) this else copy(p = 3) // 2: while b != 0: pass // do nothing
3 -> copy(p = 4) // 3: pass // critical section, do nothing
4 -> copy(p = 1, a = 0) // 4: a = 0
else -> error("Invalid state $this")
}
fun moveQ(): State? = when(q) { // while true:
1 -> copy(q = 2, b = 1) // 1: b = 1
2 -> if (a == 0) copy(q = 4) else copy(q = 3) // 2: if a == 0: break // to line 4
3 -> copy(q = 1, b = 0) // 3: b = 0
4 -> null // 4: stop // outside of loop
else -> error("Invalid state $this")
}
}
data class Transition(val from: State, val to: State) {
override fun toString(): String = "$from -> $to"
}
fun parseTransition(s: String): Transition {
val i = s.indexOf("->")
require(i > 0) { "Must contain transition with '->' separator" }
return Transition(parseState(s.substring(0, i)), parseState(s.substring(i + 2)))
}
fun parseState(s: String): State {
val match = STATE_REGEX.matchEntire(s.trim())
require(match != null) { "State does not match a specified format $STATE_REGEX" }
val g = match.groupValues.drop(1).map { it.toInt() }
return State(g[0], g[1], g[2], g[3])
}
| [
{
"class_path": "ShuffleZZZ__ITMO__29db54d/PossibleExecutionsVerifierKt.class",
"javap": "Compiled from \"PossibleExecutionsVerifier.kt\"\npublic final class PossibleExecutionsVerifierKt {\n public static final java.lang.String SOLUTION_FILE_NAME;\n\n private static final kotlin.text.Regex STATE_REGEX;\n\... |
andrewrlee__adventOfCode2020__a9c21a6/src/main/kotlin/File09.kt | import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
private class Challenge09 {
val numbers =
File("src/main/resources/09-input.txt").readLines(UTF_8).map { it.toLong() }
fun <A, B> cartesianProduct(listA: Iterable<A>, listB: Iterable<B>): Sequence<Pair<A, B>> =
sequence { listA.forEach { a -> listB.forEach { b -> yield(a to b) } } }
fun findAnswer1v1() = numbers.toList()
.windowed(26, 1)
.map { it.take(25).toSet() to it.last() }
.find { (previous, number) ->
cartesianProduct(previous, previous).filter { (i, j) -> i != j }.find { (i, j) -> i + j == number } == null
}?.second
fun List<Long>.findContiguousRangeThatSumsTo(resultToFind: Long): List<Long>? {
var sum = 0L
val trimmedList =
this.reversed().takeWhile { ((sum + it) <= resultToFind).also { _ -> sum += it } }.sorted()
return if (trimmedList.sum() == resultToFind) trimmedList else null
}
fun findContiguousRange(resultToFind: Long): List<Long> = (0..numbers.size).mapNotNull { i ->
(0..i).map(numbers::get).findContiguousRangeThatSumsTo(resultToFind)?.let { return it }
}
fun findAnswer2v1() = findContiguousRange(findAnswer1v1()!!).let { it.first() + it.last() }
fun solve() {
println(findAnswer1v1())
println(findAnswer2v1())
}
}
fun main() = Challenge09().solve() | [
{
"class_path": "andrewrlee__adventOfCode2020__a9c21a6/File09Kt.class",
"javap": "Compiled from \"File09.kt\"\npublic final class File09Kt {\n public static final void main();\n Code:\n 0: new #8 // class Challenge09\n 3: dup\n 4: invokespecial #11 ... |
andrewrlee__adventOfCode2020__a9c21a6/src/main/kotlin/File08.kt | import Challenge08.Operation.*
import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
private class Challenge08 {
enum class Operation { acc, jmp, nop }
enum class Mode { ALLOW_MODIFY, NO_MODIFY }
data class Instruction(val index: Int, val op: Operation, val value: Int) {
constructor(index: Int, line: String) : this(
index,
valueOf(line.substring(0, 3)),
line.substring(3).trim().toInt()
)
val accContr: Int get() = if (op == acc) value else 0
val nextIndex: Int get() = if (op == jmp) index + value else index + 1
}
val instructions =
File("src/main/resources/08-input.txt").readLines(UTF_8).withIndex().map { Instruction(it.index, it.value) }
fun findBeforeLoop(current: Instruction, seen: List<Instruction> = listOf(current)): List<Instruction> {
if (instructions.size < current.nextIndex) return seen
val next = instructions[current.nextIndex]
return if (seen.contains(next)) seen else findBeforeLoop(next, seen + next)
}
fun findAnswer1v1(): Int = findBeforeLoop(instructions[0]).map { it.accContr }.sum()
private fun findModifiedSolution(current: Instruction, seen: List<Instruction>, mode: Mode) =
if (mode == Mode.NO_MODIFY) null else when (current.op) {
acc -> null
jmp -> current.copy(op = nop).let { findWorking(it, Mode.NO_MODIFY, seen) }
nop -> current.copy(op = jmp).let { findWorking(it, Mode.NO_MODIFY, seen) }
}
fun findWorking(current: Instruction, mode: Mode, seen: List<Instruction> = listOf(current)): List<Instruction>? {
findModifiedSolution(current, seen, mode)?.let { return it }
if (instructions.size <= current.nextIndex) return seen
val next = instructions[current.nextIndex]
return if (seen.contains(next)) return null else findWorking(next, mode, seen + next)
}
fun findAnswer2v1(): Int = findWorking(instructions[0], Mode.ALLOW_MODIFY)?.map { it.accContr }?.sum() ?: 0
fun solve() {
println(findAnswer1v1())
println(findAnswer2v1())
}
}
fun main() = Challenge08().solve() | [
{
"class_path": "andrewrlee__adventOfCode2020__a9c21a6/File08Kt.class",
"javap": "Compiled from \"File08.kt\"\npublic final class File08Kt {\n public static final void main();\n Code:\n 0: new #8 // class Challenge08\n 3: dup\n 4: invokespecial #11 ... |
andrewrlee__adventOfCode2020__a9c21a6/src/main/kotlin/File02.kt | import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
private class Challenge02 {
data class Policy(val low: Int, val high: Int, val v: Char)
val pattern = "(\\d+)-(\\d+) (\\w): (\\w+)".toRegex()
fun readPoliciesAndPasswords() = File("src/main/resources/02-input.txt").readLines(UTF_8)
.map { pattern.find(it)!!.groupValues }
.map { Pair(Policy(it[1].toInt(), it[2].toInt(), it[3].toCharArray()[0]), it[4]) }
fun isValidV1(policy: Policy, password: String): Boolean {
val (low, high, v) = policy
val occurrences = password.groupingBy { it }.eachCount()[v] ?: 0
return occurrences in low..high
}
fun isValidV2(policy: Policy, password: String): Boolean {
val (low, high, v) = policy
val lowCharMatch = password.length < low || password[low - 1] == v
val highCharMatch = password.length < high || password[high - 1] == v
return (lowCharMatch || highCharMatch) && !(lowCharMatch && highCharMatch)
}
private fun findAnswer1v1() = readPoliciesAndPasswords().count { (policy, password) -> isValidV1(policy, password) }
private fun findAnswer2v1() = readPoliciesAndPasswords().count { (policy, password) -> isValidV2(policy, password) }
fun solve() {
println(findAnswer1v1())
println(findAnswer2v1())
}
}
fun main() = Challenge02().solve()
| [
{
"class_path": "andrewrlee__adventOfCode2020__a9c21a6/File02Kt.class",
"javap": "Compiled from \"File02.kt\"\npublic final class File02Kt {\n public static final void main();\n Code:\n 0: new #8 // class Challenge02\n 3: dup\n 4: invokespecial #11 ... |
andrewrlee__adventOfCode2020__a9c21a6/src/main/kotlin/File07.kt | import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
private class Challenge07 {
data class Bag(val description: String, val quantity: Int, val children: List<Bag> = emptyList()) {
constructor(args: List<String>) : this(args[2], args[1].toInt())
companion object {
val fullLineRegex = "^(.*?) bags contain (.*?).$".toRegex()
val contentRegex = "^(\\d)+ (.*) bag[s]*$".toRegex()
fun extract(regex: Regex, value: String) = regex.find(value)?.groupValues
fun extractContents(line: String) =
line.split(',').mapNotNull { extract(contentRegex, it.trim())?.let(::Bag) }
fun create(line: String) = extract(fullLineRegex, line)!!.let { Bag(it[1], 1, extractContents(it[2])) }
}
}
val bags = File("src/main/resources/07-input.txt").readLines(UTF_8).map(Bag::create)
val containingBags: Map<String, List<String>> = bags
.flatMap { bag -> bag.children.map { Pair(it.description, bag.description) } }
.groupBy { it.first }
.mapValues { it.value.map { it.second } }
fun findContainingBags(bagName: String, seen: Set<String> = emptySet()): Set<String> {
val containers = containingBags[bagName] ?: return seen
return containers.flatMap { findContainingBags(it, seen + containers) }.toSet()
}
fun findAnswer1v1() = findContainingBags("shiny gold").count()
val containedBags = bags.groupBy { it.description }.mapValues { it.value[0] }
fun countContainedBags(bagName: String): Int =
1 + containedBags[bagName]!!.children.map { it.quantity * countContainedBags(it.description) }.sum()
fun findAnswer2v1() = countContainedBags("shiny gold") - 1 // don't count the shiny gold bag!
fun solve() {
println(findAnswer1v1())
println(findAnswer2v1())
}
}
fun main() = Challenge07().solve() | [
{
"class_path": "andrewrlee__adventOfCode2020__a9c21a6/File07Kt.class",
"javap": "Compiled from \"File07.kt\"\npublic final class File07Kt {\n public static final void main();\n Code:\n 0: new #8 // class Challenge07\n 3: dup\n 4: invokespecial #11 ... |
ahampriyanshu__algo-ds-101__ea880b1/Data-Structures/Graph/GraphUsingList.kt | import kotlin.collections.ArrayList
class Node<T>(val value: T) {
val neighbors = ArrayList<Node<T>>()
fun addNeighbor(node: Node<T>) = neighbors.add(node)
override fun toString(): String = value.toString()
}
class Graph<T> {
private val nodes = HashSet<Node<T>>()
fun addNode(value: T) {
val newNode = Node(value)
nodes.add(newNode)
}
fun getNode(reference: T): Node<T>? {
return nodes.firstOrNull { it.value == reference }
}
fun addVertex(from: T, to: T) {
getNode(to)?.let { getNode(from)?.addNeighbor(it) }
}
}
fun <T> Graph<T>.bfs(reference: T): List<T> {
getNode(reference)?.let { referenceNode ->
val visited = ArrayList<Node<T>>()
val queue = ArrayList<Node<T>>()
queue.add(referenceNode)
while (queue.isNotEmpty()) {
val node = queue.removeAt(0)
if (!visited.contains(node)) {
visited.add(node)
node.neighbors
.filter { !visited.contains(it) }
.forEach { queue.add(it) }
}
}
return visited.map { it.value }
}
return emptyList()
}
fun <T> Graph<T>.dfs(reference: T): List<T> {
getNode(reference)?.let { referenceNode ->
val visited = ArrayList<Node<T>>()
val stack = ArrayList<Node<T>>()
stack.add(referenceNode)
while (stack.isNotEmpty()) {
val node = stack.removeAt(stack.lastIndex)
if (!visited.contains(node)) {
visited.add(node)
node.neighbors
.filter { !visited.contains(it) }
.forEach { stack.add(it) }
}
}
return visited.map { it.value }
}
return emptyList()
}
fun main() {
val namesGraph = Graph<String>()
namesGraph.addNode("Minato")
namesGraph.addNode("Obito")
namesGraph.addVertex("Minato", "Obito")
namesGraph.addNode("Kakashi")
namesGraph.addVertex("Minato", "Kakashi")
namesGraph.addNode("Rin")
namesGraph.addVertex("Minato", "Rin")
namesGraph.addNode("Naruto")
namesGraph.addVertex("Kakashi", "Naruto")
namesGraph.addNode("Sakura")
namesGraph.addVertex("Kakashi", "Sakura")
namesGraph.addNode("Sasuke")
namesGraph.addVertex("Kakashi", "Sasuke")
print(namesGraph.bfs("Minato"))
print(namesGraph.dfs("Minato"))
}
| [
{
"class_path": "ahampriyanshu__algo-ds-101__ea880b1/GraphUsingListKt.class",
"javap": "Compiled from \"GraphUsingList.kt\"\npublic final class GraphUsingListKt {\n public static final <T> java.util.List<T> bfs(Graph<T>, T);\n Code:\n 0: aload_0\n 1: ldc #10 // Stri... |
ahampriyanshu__algo-ds-101__ea880b1/Algorithms/Array/twoSum.kt | import java.util.*
/*Naive Approach: Check for all pairs if they adds up to the target or not
TC: O(n*n) SC: O(1)
*/
fun findTwoSumNaive(nums: List<Int>, target: Int): IntArray{
val n = nums.size
for(i in 0 until n){
for(j in (i+1) until n){
if(nums[i] + nums[j] == target)
return intArrayOf(nums[i], nums[j])
}
}
return intArrayOf(-1, -1)
}
/*Better Approach: Sort the given array
->create two pointers one of which points to the first element and another one to the last element.
->check if both the values pointed to by these pointers adds up to the target or not.
->if yes, return the result.
->otherwise, if the sum is lesser than the target increment left pointer
-> otherwise decrement the right pointer.
->The above intuition works because the array is sorted.
TC: O(nlogn) SC: O(n)
*/
fun findTwoSumBetter(nums: List<Int>, target: Int): IntArray{
Collections.sort(nums)
var (lo, hi) = Pair(0, nums.size - 1)
while(lo < hi){
val sum = nums[lo] + nums[hi]
if(sum == target){
return intArrayOf(nums[lo], nums[hi]);
}
if(sum < target) lo++ else hi--
}
return intArrayOf(-1, -1)
}
/*Optimal Approach:
->Use a hashmap to store the numbers as you traverse.
->At any point if you had added a value equal to the target - current_number in the hashmap.
->Then we have our ans as {current_number, target - current_number} which adds up to the target value.
->otherwise return {-1, -1} as the result.
TC: O(n) SC: O(n)
considering the hashmap works in O(1) on an average.
*/
fun findTwoSumOptimal(nums: List<Int>, target: Int): IntArray{
val map = mutableMapOf<Int, Boolean>()
for(num in nums){
if(map.containsKey(target - num))
return intArrayOf(target - num, num)
map[num] = true
}
return intArrayOf(-1, -1)
}
//main function
fun main(){
//get the input array
val nums = readLine()!!.split(' ').map{it.toInt()}
//get the target value
val target = readLine()!!.toInt()
//a pair of values to store the result
val values = findTwoSumOptimal(nums, target)
//if both the values of the result are -1
//it means no such pair exists that adds up to the target value
//otherwise, print a valid pair of values
if(values[0] == -1 && values[1] == -1)
println("No such pair exists")
else
println("${values[0]} and ${values[1]} adds up to $target")
} | [
{
"class_path": "ahampriyanshu__algo-ds-101__ea880b1/TwoSumKt.class",
"javap": "Compiled from \"twoSum.kt\"\npublic final class TwoSumKt {\n public static final int[] findTwoSumNaive(java.util.List<java.lang.Integer>, int);\n Code:\n 0: aload_0\n 1: ldc #10 // Strin... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle19.kt | object Puzzle19 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle19::class.java.getResource("puzzle19.txt").readText()
val calculatedMatchingStringCount = countMatchingStrings(input,Puzzle19::useSameRules)
println(calculatedMatchingStringCount)
val calculatedMatchingStringCountWithModifiedRules = countMatchingStrings(input,Puzzle19::useModifiedRules)
println(calculatedMatchingStringCountWithModifiedRules)
}
fun countMatchingStrings(input: String, modify: (Int, String) -> String): Int {
val rulesAndStrings = input.split("\n\n")
val rules = Rules(rulesAndStrings.first().split("\n"), modify)
val strings = rulesAndStrings.last().split("\n")
return strings.count { string -> rules.accept(string) }
}
fun useSameRules(index: Int, rules: String) = rules
fun useModifiedRules(index: Int, rules: String) =
when (index) {
8 -> "42 | 42 8"
11 -> "42 31 | 42 11 31"
else -> rules
}
class Rules(ruleStrings: List<String>, modify: (Int, String) -> String) {
private val regexp: Regex?
private val ruleCharMap: MutableMap<Int, String>
init {
val ruleMap = mutableMapOf<Int, List<List<Int>>>()
ruleCharMap = mutableMapOf()
ruleStrings.forEach{ ruleString -> //1: 2 3 | 3 2
val indexAndRules = ruleString.split(": ")
val index = indexAndRules.first().toInt() //1
val originalRules = indexAndRules.last() //2 3 | 3 2
val rules = modify(index, originalRules)
if (rules.startsWith("\"")){
ruleCharMap[index] = rules[1].toString()
}else {
val rulesArray = mutableListOf<List<Int>>()
rules.split(" | ").forEach { r ->
rulesArray.add(r.split(" ").map { it.toInt() })
}
ruleMap[index] = rulesArray
}
}
var couldResolveAnyRules = true
while (!ruleCharMap.containsKey(0) && couldResolveAnyRules) {
val resolvableRules = ruleMap.filter { rule ->
!ruleCharMap.containsKey(rule.key) && rule.value.all { r ->
r.all { r2 ->
ruleCharMap.containsKey(r2)
}
}
}
resolvableRules.forEach { resolvableRule ->
val key = resolvableRule.key
val value = resolvableRule.value
val resolvedValue = value.joinToString("|") { l ->
"(" + l.map { ruleNumber -> ruleCharMap[ruleNumber] }.joinToString("") + ")"
}
ruleCharMap[key] = "($resolvedValue)"
}
couldResolveAnyRules = resolvableRules.isNotEmpty()
}
if (ruleCharMap.containsKey(0)) {
regexp = ("^" + ruleCharMap[0] + "$").toRegex()
}else{
regexp = null
}
}
fun accept(string: String): Boolean {
if (regexp != null)
return regexp.matches(string)
else{
//0 = 8 11
//8 = (42)+
//11 = (42)(31) | 42 42 31 31
//0 = 42{k+}31{k}
val regexp42 = ruleCharMap[42]
val regexp31 = ruleCharMap[31]
var remainingString = string
val regexp4231 = "^$regexp42(.+)$regexp31$".toRegex()
var matchResult = regexp4231.find(remainingString)
val regexp42CapturingGroupCount = regexp42!!.count { it == '(' } + 1
while (
matchResult?.groups?.get(regexp42CapturingGroupCount) != null
&& remainingString != matchResult.groups[regexp42CapturingGroupCount]!!.value){
remainingString = matchResult.groups[regexp42CapturingGroupCount]!!.value
matchResult = regexp4231.find(remainingString)
}
val regexp42Plus = "^${ruleCharMap[42]}+$".toRegex()
return regexp42Plus.matches(remainingString) && remainingString != string
}
}
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle19$main$calculatedMatchingStringCount$1.class",
"javap": "Compiled from \"Puzzle19.kt\"\nfinal class Puzzle19$main$calculatedMatchingStringCount$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function2<java.lang.In... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle16.kt | import java.math.BigInteger
object Puzzle16 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle16::class.java.getResource("puzzle16.txt").readText()
val ticketInfo = TicketInfo(input)
println(ticketInfo.sumInvalidNumbers())
println(ticketInfo.getProdOfDepartmentFields())
}
class TicketInfo(input: String) {
private val rules: Rules
private val myTicket: List<Int>
private val otherTickets : List<List<Int>>
init {
val parts = input.split("\n\n")
rules = Rules(parts.first().split("\n"))
myTicket = parts[1].split("\n")[1].split(",").map(String::toInt)
val ticketLines = parts.last().split("\n").drop(1)
otherTickets = mutableListOf<List<Int>>()
ticketLines.forEach { line ->
otherTickets.add(line.split(",").map(String::toInt))
}
}
fun sumInvalidNumbers(): Int{
val invalidFields = rules.getInvalidData(otherTickets)
return invalidFields.sum()
}
fun getProdOfDepartmentFields(): BigInteger{
val validTickets = rules.getValidTickets(otherTickets)
rules.findRuleFields(validTickets)
return rules.getValuesForFields(myTicket, "departure").fold(BigInteger.ONE) { prod, element -> prod * element.toBigInteger() }
}
}
private class Rules(lines: List<String>) {
fun getValidTickets(ticketData: List<List<Int>>): List<List<Int>> {
return ticketData.filterNot { ticket -> ticket.any { i -> inValid(i) } }
}
fun findRuleFields(ticketData: List<List<Int>>){
val maxIndex = ticketData.first().lastIndex
for (rule in rules) {
for (fieldNumber in 0..maxIndex) {
if (ticketData.none { ticket -> rule.inValid(ticket[fieldNumber]) }){
rule.fieldNumbers.add(fieldNumber)
}
}
}
while (rules.any { rule -> rule.fieldNumbers.size > 1 }){
rules.filter { rule -> rule.fieldNumbers.size == 1 }.forEach { onlyRule ->
val fieldNumberToRemove = onlyRule.fieldNumbers.first()
rules.filter { rule -> rule.fieldNumbers.size > 1 && rule.fieldNumbers.contains(fieldNumberToRemove) }.forEach { removeSameFieldRule ->
removeSameFieldRule.fieldNumbers.remove(fieldNumberToRemove)
}
}
}
}
fun getInvalidData(ticketData: List<List<Int>>): List<Int> {
val invalidData = mutableListOf<Int>()
ticketData.forEach { ticket ->
ticket.forEach { value ->
if (inValid(value)){
invalidData.add(value)
}
}
}
return invalidData
}
private fun inValid(value: Int): Boolean {
return rules.all { rule -> rule.inValid(value) }
}
fun getValuesForFields(myTicket: List<Int>, fieldStartsWith: String): List<Int> {
return rules.filter { rule -> rule.name.startsWith(fieldStartsWith) }.map { rule -> myTicket[rule.fieldNumbers.first()] }
}
private data class Rule(val name: String, val ranges: List<Pair<Int, Int>>, var fieldNumbers: MutableList<Int>) {
fun inValid(value: Int): Boolean {
return ranges.all { range -> value < range.first || value > range.second }
}
}
private val rules: MutableList<Rule> = mutableListOf()
init {
lines.forEach { line ->
val nameAndRules = line.split(": ")
val name = nameAndRules.first()
val rulesString = nameAndRules.last().split(" or ")
val rulesArray = rulesString.map { it -> Pair(it.split("-").first().toInt(), it.split("-").last().toInt()) }
rules.add(Rule(name, rulesArray, mutableListOf()))
}
}
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle16$Rules$Rule.class",
"javap": "Compiled from \"Puzzle16.kt\"\nfinal class Puzzle16$Rules$Rule {\n private final java.lang.String name;\n\n private final java.util.List<kotlin.Pair<java.lang.Integer, java.lang.Integer>> ranges;\n\n private java.uti... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle22.kt | object Puzzle22 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle22::class.java.getResource("puzzle22.txt").readText()
val decksNormalPlay = Decks(input)
println(decksNormalPlay.calculateWinnerScoreNormalPlay())
val decksRecursivePlay = Decks(input)
println(decksRecursivePlay.calculateWinnerScoreRecursivePlay())
}
class Decks(input: String) {
private val deck1: MutableList<Int>
private val deck2: MutableList<Int>
init {
val decks = input.split("\n\n")
deck1 = decks.first().split("\n").drop(1).map { it.toInt() }.toMutableList()
deck2 = decks.last().split("\n").drop(1).map { it.toInt() }.toMutableList()
}
fun calculateWinnerScoreNormalPlay(): Int {
playDecksNormal()
val winnerDeck = if (deck1.isEmpty()) deck2 else deck1
return winnerDeck.reversed().mapIndexed { index, i -> i * (index+1) }.sum()
}
private fun playDecksNormal() {
while (noEmptyDeck()){
val card1 = deck1.first()
deck1.removeAt(0)
val card2 = deck2.first()
deck2.removeAt(0)
if (card1 > card2){
deck1.add(card1)
deck1.add(card2)
}else{
deck2.add(card2)
deck2.add(card1)
}
}
}
fun calculateWinnerScoreRecursivePlay(): Int {
val previousConfigs = mutableSetOf<String>()
while (noEmptyDeck()){
val key = deck1.joinToString(", ") + " | " + deck2.joinToString(", ")
if (previousConfigs.contains(key)){
deck2.clear()
} else {
previousConfigs.add(key)
playOneRound(deck1, deck2)
}
}
val winnerDeck = if (deck1.isEmpty()) deck2 else deck1
return winnerDeck.reversed().mapIndexed { index, i -> i * (index+1) }.sum()
}
private fun getWinnerRecursive(subDeck1: MutableList<Int>, subDeck2: MutableList<Int>): Int {
val previousConfigs = mutableSetOf<String>()
while (subDeck1.isNotEmpty() && subDeck2.isNotEmpty()) {
val key = subDeck1.joinToString(", ") + " | " + subDeck2.joinToString(", ")
if (previousConfigs.contains(key)) {
return 1
} else {
previousConfigs.add(key)
playOneRound(subDeck1, subDeck2)
}
}
return if (subDeck1.isEmpty()) 2 else 1
}
private fun playOneRound(subDeck1: MutableList<Int>,
subDeck2: MutableList<Int>
) {
val card1 = subDeck1.first()
subDeck1.removeAt(0)
val card2 = subDeck2.first()
subDeck2.removeAt(0)
val winner: Int = if (subDeck1.size >= card1 && subDeck2.size >= card2) {
getWinnerRecursive(subDeck1.take(card1).toMutableList(), subDeck2.take(card2).toMutableList())
} else {
if (card1 > card2) 1 else 2
}
if (winner == 1) {
subDeck1.add(card1)
subDeck1.add(card2)
} else {
subDeck2.add(card2)
subDeck2.add(card1)
}
}
private fun noEmptyDeck() = deck1.isNotEmpty() && deck2.isNotEmpty()
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle22.class",
"javap": "Compiled from \"Puzzle22.kt\"\npublic final class Puzzle22 {\n public static final Puzzle22 INSTANCE;\n\n private Puzzle22();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle12.kt | import kotlin.math.absoluteValue
object Puzzle12 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle12::class.java.getResource("puzzle12.txt").readText()
val calculatedDistance = calculateDistance(input)
println(calculatedDistance)
val calculateDistanceWithWaypoint = calculateDistanceWithWaypoint(input)
println(calculateDistanceWithWaypoint)
}
enum class Command {
N, S, E, W, L, R, F
}
enum class Direction {
N {
override fun toCommand() = Command.N
},
S {
override fun toCommand() = Command.S
},
E {
override fun toCommand() = Command.E
},
W {
override fun toCommand() = Command.W
};
abstract fun toCommand() : Command
}
class ShipData(
private var headTo: Direction,
private var posEast: Int,
private var posNorth: Int,
private var waypointPosEast: Int = 0,
private var waypointPosNorth: Int = 0){
fun getDistance() = posEast.absoluteValue + posNorth.absoluteValue
fun move(command: Command, i: Int){
when (command) {
Command.N -> { posNorth += i }
Command.S -> { posNorth -= i }
Command.E -> { posEast += i }
Command.W -> { posEast -= i }
Command.L -> {
val cnt = (i / 90)
val newHeadTo = (headTo.ordinal + cnt ) % 4
headTo = Direction.values()[newHeadTo]
}
Command.R -> {
val cnt = (i / 90)
val newHeadTo = (headTo.ordinal - cnt + 4 * cnt ) % 4
headTo = Direction.values()[newHeadTo]
}
Command.F -> {
move(headTo.toCommand(), i)
}
}
}
fun moveWithWaypoint(command: Command, i: Int){
when (command) {
Command.N -> { waypointPosNorth += i }
Command.S -> { waypointPosNorth -= i }
Command.E -> { waypointPosEast += i }
Command.W -> { waypointPosEast -= i }
Command.L -> {
moveWithWaypoint(Command.R, -i)
}
Command.R -> {
var num = i
if (i < 0) num = i + 360
when ((num / 90)){
1 -> {
val oldWaypointPosNorth = waypointPosNorth
val oldWaypointPosEast = waypointPosEast
waypointPosNorth = -oldWaypointPosEast
waypointPosEast = oldWaypointPosNorth
}
2 -> {
val oldWaypointPosNorth = waypointPosNorth
val oldWaypointPosEast = waypointPosEast
waypointPosNorth = -oldWaypointPosNorth
waypointPosEast = -oldWaypointPosEast
}
3 -> {
val oldWaypointPosNorth = waypointPosNorth
val oldWaypointPosEast = waypointPosEast
waypointPosNorth = oldWaypointPosEast
waypointPosEast = -oldWaypointPosNorth
}
}
}
Command.F -> {
posNorth += i * waypointPosNorth
posEast += i * waypointPosEast
}
}
}
}
fun calculateDistance(input: String): Int {
val commands = input.split("\n")
val shipData = ShipData(Direction.E, 0, 0)
commands.forEach { commandString ->
val command = commandString.first().toString()
val number = commandString.substring(1).toInt()
shipData.move(Command.valueOf(command), number)
}
return shipData.getDistance()
}
fun calculateDistanceWithWaypoint(input: String): Int {
val commands = input.split("\n")
val shipData = ShipData(Direction.E, 0, 0, 10, 1)
commands.forEach { commandString ->
val command = commandString.first().toString()
val number = commandString.substring(1).toInt()
shipData.moveWithWaypoint(Command.valueOf(command), number)
}
return shipData.getDistance()
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle12$ShipData.class",
"javap": "Compiled from \"Puzzle12.kt\"\npublic final class Puzzle12$ShipData {\n private Puzzle12$Direction headTo;\n\n private int posEast;\n\n private int posNorth;\n\n private int waypointPosEast;\n\n private int waypointP... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle7.kt | object Puzzle7 {
@JvmStatic
fun main(args: Array<String>) {
val rules = Rules(Puzzle7::class.java.getResource("puzzle7.txt").readText().split("\n"))
val sumOfAvailableOuterColors = rules.countContainingBags("shiny gold")
println(sumOfAvailableOuterColors)
val sumOfAvailableInnreColors = rules.countAllInnerBags("shiny gold")
println(sumOfAvailableInnreColors)
}
class Rules {
val bagRules = HashMap<String, HashMap<String, Int>?>()
constructor(input: List<String>){
input.forEach { line ->
val bagColorRegexp = "^([^ ]+ [^ ]+) bags contain (.+)\\.$".toRegex()
val bagListRegexp = "^(\\d+) ([^ ]+ [^ ]+) bags?$".toRegex()
val matchResult = bagColorRegexp.find(line)
val bagColor = matchResult?.groups?.get(1)?.value!!
val containingString = matchResult.groups[2]?.value!!
if (containingString == "no other bags"){
bagRules[bagColor] = null
}else{
val bagStringList = containingString.split(", ")
bagRules[bagColor] = HashMap()
bagStringList.forEach { bagCountString ->
val bagMatchResult = bagListRegexp.find(bagCountString)
val bagCount = bagMatchResult?.groups?.get(1)?.value?.toInt()!!
val innerBagColor = bagMatchResult.groups[2]?.value!!
bagRules[bagColor]!![innerBagColor] = bagCount
}
}
}
}
fun countContainingBags(color: String): Int {
val foundParents = HashSet<String>()
var count: Int
var addedCount: Int
var lookFor: HashSet<String> = hashSetOf(color)
do {
count = foundParents.count()
val parents = bagRules.filter { rule ->
if (rule.value != null)
lookFor.any { rule.value!!.containsKey(it) }
else
false
}
lookFor = parents.keys.toHashSet()
foundParents.addAll(lookFor)
addedCount = foundParents.count() - count
}while (addedCount > 0)
return foundParents.count()
}
fun countAllInnerBags(color: String) = countInnerBags(color) - 1
private fun countInnerBags(color: String): Int {
return if (bagRules[color] == null){
1
}else{
var retVal = 1
bagRules[color]!!.forEach { c, cnt ->
retVal += cnt * countInnerBags(c)
}
retVal
}
}
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle7.class",
"javap": "Compiled from \"Puzzle7.kt\"\npublic final class Puzzle7 {\n public static final Puzzle7 INSTANCE;\n\n private Puzzle7();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<in... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle14.kt | import java.math.BigInteger
import kotlin.math.pow
object Puzzle14 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle14::class.java.getResource("puzzle14.txt").readText()
val program1 = Program(input)
program1.run()
println(program1.sumOfUsedMemoryAddresses())
val program2 = Program(input)
program2.runV2()
println(program2.sumOfUsedMemoryAddresses())
}
class Program(input: String) {
private val subPrograms = mutableListOf<SubProgram>()
private val memory = HashMap<BigInteger, BigInteger>()
private val memorySetterRegex = "^mem\\[(\\d+)\\] = (\\d+)$".toRegex()
init {
input.split("\n").forEach { line ->
if (line.startsWith("mask = ")){
val mask = line.split(" = ")[1]
subPrograms.add(SubProgram(mask))
}else{
val matchResult = memorySetterRegex.find(line)
val memAddress = matchResult?.groups?.get(1)?.value!!.toInt()
val memValue = matchResult.groups[2]?.value!!.toInt()
subPrograms.last().addStatement(memAddress, memValue)
}
}
}
class SubProgram(private val mask: String) {
private val statements = mutableListOf<Pair<Int, Int>>()
private val memory = HashMap<BigInteger, BigInteger>()
fun addStatement(memAddress: Int, memValue: Int){
statements.add(Pair(memAddress, memValue))
}
fun run(): HashMap<BigInteger, BigInteger>{
statements.forEach { s ->
val address = s.first.toBigInteger()
val originalValue = s.second.toString(2).padStart(mask.length, '0')
val maskedValue = mutableListOf<Char>()
for (i in mask.length-1 downTo 0){
val maskValue = mask[i]
val value = originalValue[i]
maskedValue.add(0, if (maskValue == 'X') value else maskValue)
}
memory[address] = maskedValue.joinToString("").toBigInteger(2)
}
return memory
}
fun runV2(): HashMap<BigInteger, BigInteger>{
statements.forEach { s ->
val originalAddress = s.first.toString(2).padStart(mask.length, '0')
val value = s.second.toBigInteger()
val maskedAddress = mutableListOf<Char>()
for (i in mask.length-1 downTo 0){
val maskValue = mask[i]
val address = originalAddress[i]
maskedAddress.add(0,
when (maskValue) {
'0' -> address
'1' -> '1'
else -> 'F'
}
)
}
val floatingBitCount = maskedAddress.count { it == 'F' }
for (i in 0..(2.toDouble().pow(floatingBitCount.toDouble()).toInt())){
val number = i.toString(2).padStart(floatingBitCount, '0')
val floatedAddress = mutableListOf<Char>()
var numberIndex = 0
for (char in maskedAddress){
if (char == 'F'){
floatedAddress.add(number[numberIndex])
numberIndex++
}else{
floatedAddress.add(char)
}
}
memory[floatedAddress.joinToString("").toBigInteger(2)] = value
}
}
return memory
}
}
fun run(){
subPrograms.forEach { subProgram ->
val subProgramMemory = subProgram.run()
subProgramMemory.forEach { (address, value) ->
memory[address] = value
}
}
}
fun runV2(){
subPrograms.forEach { subProgram ->
val subProgramMemory = subProgram.runV2()
subProgramMemory.forEach { (address, value) ->
memory[address] = value
}
}
}
fun sumOfUsedMemoryAddresses() = memory.filter { it.value != BigInteger.ZERO }.values.sumOf { it }
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle14$Program$SubProgram.class",
"javap": "Compiled from \"Puzzle14.kt\"\npublic final class Puzzle14$Program$SubProgram {\n private final java.lang.String mask;\n\n private final java.util.List<kotlin.Pair<java.lang.Integer, java.lang.Integer>> statem... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle21.kt | object Puzzle21 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle21::class.java.getResource("puzzle21.txt").readText()
val allergicData = AllergicData(input)
println(allergicData.countNonAllergicIngredients())
println(allergicData.listIngredientsByAllergens())
}
class AllergicData(input: String){
private val allergenCanBeInFoods = mutableMapOf<String, Set<String>>()
private val allIngredients = mutableListOf<String>()
init {
input.split("\n").forEach { line ->
val ingredientsAndAllergens = line
.replace("(", "")
.replace(")", "")
.replace(",", "")
.split(" contains ")
val ingredients = ingredientsAndAllergens.first().split(" ")
allIngredients.addAll(ingredients)
val ingredientsSet = ingredients.toSet()
val allergens = ingredientsAndAllergens.last().split(" ")
allergens.forEach { allergen ->
if (allergenCanBeInFoods.containsKey(allergen)){
allergenCanBeInFoods[allergen] = allergenCanBeInFoods[allergen]!!.intersect(ingredientsSet)
}else{
allergenCanBeInFoods[allergen] = ingredientsSet
}
}
}
while (allergenCanBeInFoods.any { it.value.size > 1 }){
val knownAllergens = allergenCanBeInFoods.filter { it.value.size == 1 }
val unknownAllergenKeys = allergenCanBeInFoods.filter { allergenWithFoodList ->
allergenWithFoodList.value.size > 1
}.keys
unknownAllergenKeys.forEach { unknownAllergen ->
knownAllergens.forEach { knownAllergen->
allergenCanBeInFoods[unknownAllergen] = allergenCanBeInFoods[unknownAllergen]!!.minus(knownAllergen.value.first())
}
}
}
}
fun countNonAllergicIngredients() = allIngredients.count { ingredient -> allergenCanBeInFoods.none { allergen -> allergen.value.contains(ingredient) } }
fun listIngredientsByAllergens() = allergenCanBeInFoods.toList().sortedBy { (key, _) -> key }
.joinToString(",") { it.second.first() }
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle21.class",
"javap": "Compiled from \"Puzzle21.kt\"\npublic final class Puzzle21 {\n public static final Puzzle21 INSTANCE;\n\n private Puzzle21();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle13.kt | import java.math.BigInteger
object Puzzle13 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle13::class.java.getResource("puzzle13.txt").readText()
val earliestBusNumberMultipledByWaitTime = earliestBusNumberMultipledByWaitTime(input)
println(earliestBusNumberMultipledByWaitTime)
println(firstAfterOtherStarts(input))
}
fun earliestBusNumberMultipledByWaitTime(input: String): Int {
val lines = input.split("\n")
val timeOfArrive = lines.first().toInt()
val busNumbers = lines[1].split(",").filterNot { it == "x" }.map(String::toInt)
val waitTimes = busNumbers.map { it to it - (timeOfArrive % it) }.minByOrNull { it.second }!!
return waitTimes.first * waitTimes.second
}
fun firstAfterOtherStarts(input: String): BigInteger {
val lines = input.split("\n")
val busNumbers = lines[1].split(",").mapIndexed{ idx, value -> value to idx}.filterNot { it.first == "x" }.map { it.first.toBigInteger() to it.second.toBigInteger() }
val M = busNumbers.fold(BigInteger.ONE) { prod, element -> prod * element.first}
var x = BigInteger.ZERO
busNumbers.forEach { pair ->
val bNumer = pair.first
val index = pair.second
val m = M/bNumer
val firstComponent = Eucledian(m, bNumer).calculate().first
val d = (bNumer-index) % bNumer
x += (d * firstComponent * m)
}
while (x < M) x += M
return x%M
}
class Eucledian(a: BigInteger, b:BigInteger){
private var q = mutableListOf(BigInteger.ZERO,BigInteger.ZERO)
private var r = mutableListOf(a,b)
private var x = mutableListOf(BigInteger.ONE,BigInteger.ZERO)
private var y = mutableListOf(BigInteger.ZERO,BigInteger.ONE)
private var i = 2
private fun makeOneStep(): Boolean{
q.add(r[i-2] / r[i-1])
r.add(r[i-2] % r[i-1])
x.add(x[i-2] - q[i] * x[i-1])
y.add(y[i-2] - q[i] * y[i-1])
i++
return r.last() == BigInteger.ONE
}
fun calculate(): Pair<BigInteger, BigInteger>{
while (!makeOneStep()) {}
return Pair(x.last(), y.last())
}
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle13$Eucledian.class",
"javap": "Compiled from \"Puzzle13.kt\"\npublic final class Puzzle13$Eucledian {\n private java.util.List<java.math.BigInteger> q;\n\n private java.util.List<java.math.BigInteger> r;\n\n private java.util.List<java.math.BigInte... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle17.kt | object Puzzle17 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle17::class.java.getResource("puzzle17.txt").readText()
val calculatedActiveCountIn3D = calculateActiveCountIn3D(input)
println(calculatedActiveCountIn3D)
val calculatedActiveCountIn4D = calculateActiveCountIn4D(input)
println(calculatedActiveCountIn4D)
}
fun calculateActiveCountIn3D(input: String): Int {
var state = State3D(input)
for (i in 1..6){
state = state.getNextState()
}
return state.countActiveCells()
}
fun calculateActiveCountIn4D(input: String): Int {
var state = State4D(input)
for (i in 1..6){
state = state.getNextState()
}
return state.countActiveCells()
}
class State3D{
private val grid: List<List<CharArray>>
constructor(input: String){
val initialState = input.split("\n").map { line -> line.toCharArray() }
grid = listOf(initialState)
}
constructor(grid: List<List<CharArray>>){
this.grid = grid
}
private fun zDimension() = grid.size
private fun yDimension() = grid.first().size
private fun xDimension() = grid.first().first().size
private fun getGridAt(z: Int, y: Int, x: Int): Char{
return if (z in 0 until zDimension()
&& y in 0 until yDimension()
&& x in 0 until xDimension()){
grid[z][y][x]
}else '.'
}
fun getNextState(): State3D {
val nextState = mutableListOf<List<CharArray>>()
val nextXDimension = xDimension() + 2
val nextYDimension = yDimension() + 2
val nextZDimension = zDimension() + 2
for (z in 0 until nextZDimension) {
val rows = mutableListOf<CharArray>()
for (y in 0 until nextYDimension) {
val row = CharArray(nextXDimension)
for (x in 0 until nextXDimension) {
val currentStateZ = z - 1
val currentStateY = y - 1
val currentStateX = x - 1
val activeNeighbourCount = activeNeighbourCount(currentStateZ, currentStateY, currentStateX)
row[x] =
if (getGridAt(currentStateZ, currentStateY, currentStateX) == '#') {
if (activeNeighbourCount == 2 || activeNeighbourCount == 3) '#'
else '.'
} else if (activeNeighbourCount == 3) '#'
else '.'
}
rows.add(row)
}
nextState.add(rows)
}
return State3D(nextState)
}
private fun activeNeighbourCount(z: Int, y: Int, x: Int): Int {
var count = 0
for (i in -1..1)
for (j in -1..1)
for (k in -1..1){
if (
(i != 0 || j != 0 || k != 0)
&& getGridAt(z+k, y+j, x+i) == '#'
){
count++
}
}
return count
}
fun countActiveCells(): Int {
return grid.sumOf { z -> z.sumOf { y -> y.count { x -> x == '#' } }}
}
}
class State4D{
private val grid: List<List<List<CharArray>>>
constructor(input: String){
val initialState = input.split("\n").map { line -> line.toCharArray() }
grid = listOf(listOf(initialState))
}
constructor(grid: List<List<List<CharArray>>>){
this.grid = grid
}
private fun wDimension() = grid.size
private fun zDimension() = grid.first().size
private fun yDimension() = grid.first().first().size
private fun xDimension() = grid.first().first().first().size
private fun getGridAt(w: Int, z: Int, y: Int, x: Int): Char{
return if ( w in 0 until wDimension()
&& z in 0 until zDimension()
&& y in 0 until yDimension()
&& x in 0 until xDimension()){
grid[w][z][y][x]
}else '.'
}
fun getNextState(): State4D {
val nextState = mutableListOf<List<List<CharArray>>>()
val nextXDimension = xDimension() + 2
val nextYDimension = yDimension() + 2
val nextZDimension = zDimension() + 2
val nextWDimension = wDimension() + 2
for (w in 0 until nextWDimension) {
val layers = mutableListOf<List<CharArray>>()
for (z in 0 until nextZDimension) {
val rows = mutableListOf<CharArray>()
for (y in 0 until nextYDimension) {
val row = CharArray(nextXDimension)
for (x in 0 until nextXDimension) {
val currentStateW = w - 1
val currentStateZ = z - 1
val currentStateY = y - 1
val currentStateX = x - 1
val activeNeighbourCount = activeNeighbourCount(currentStateW, currentStateZ, currentStateY, currentStateX)
row[x] =
if (getGridAt(currentStateW, currentStateZ, currentStateY, currentStateX) == '#') {
if (activeNeighbourCount == 2 || activeNeighbourCount == 3) '#'
else '.'
} else if (activeNeighbourCount == 3) '#'
else '.'
}
rows.add(row)
}
layers.add(rows)
}
nextState.add(layers)
}
return State4D(nextState)
}
private fun activeNeighbourCount(w: Int, z: Int, y: Int, x: Int): Int {
var count = 0
for (i in -1..1)
for (j in -1..1)
for (k in -1..1)
for (l in -1..1){
if (
(i != 0 || j != 0 || k != 0 || l != 0)
&& getGridAt(w+l,z+k, y+j, x+i) == '#'
){
count++
}
}
return count
}
fun countActiveCells(): Int {
return grid.sumOf { w -> w.sumOf { z -> z.sumOf { y -> y.count { x -> x == '#' } }}}
}
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle17$State3D.class",
"javap": "Compiled from \"Puzzle17.kt\"\npublic final class Puzzle17$State3D {\n private final java.util.List<java.util.List<char[]>> grid;\n\n public Puzzle17$State3D(java.lang.String);\n Code:\n 0: aload_1\n 1: ld... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle11.kt | object Puzzle11 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle11::class.java.getResource("puzzle11.txt").readText()
val calculateOccupiedSeats = calculateOccupiedSeats(input, Puzzle11::countImmediatelyAdjacentSeats, 4)
println(calculateOccupiedSeats)
val calculateOccupiedSeatsVisible = calculateOccupiedSeats(input, Puzzle11::countVisibleAdjacentSeats, 5)
println(calculateOccupiedSeatsVisible)
}
fun calculateOccupiedSeats(input: String,
counter: (i: Int, rows: Int, j: Int, cols: Int, input: List<CharArray>) -> Int,
minOccupiedToLeave: Int): Int {
var arrayWithResult = Pair(inputToArrayLists(input), true)
while (arrayWithResult.second){
arrayWithResult = applyRules(arrayWithResult.first, counter, minOccupiedToLeave)
}
return arrayWithResult.first.sumOf { line -> line.count { it == '#' } }
}
private fun applyRules(
input: List<CharArray>,
counter: (i: Int, rows: Int, j: Int, cols: Int, input: List<CharArray>) -> Int,
minOccupiedToLeave: Int
): Pair<List<CharArray>, Boolean> {
val rows = input.size
val cols = input.first().size
val output = List(rows) {CharArray(cols)}
var changed = false
for (row in 0 until rows){
for (col in 0 until cols){
val countOccupied = counter(row, rows, col, cols, input)
if (input[row][col] == 'L'){
if (countOccupied == 0){
output[row][col] = '#'
changed = true
}else{
output[row][col] = 'L'
}
}else if (input[row][col] == '#'){
if (countOccupied >= minOccupiedToLeave){
output[row][col] = 'L'
changed = true
}else{
output[row][col] = '#'
}
}else{
output[row][col] = '.'
}
}
}
return Pair(output, changed)
}
fun countImmediatelyAdjacentSeats(i: Int, rows: Int, j: Int, cols: Int, input: List<CharArray>): Int {
var countOccupied = 0
for (x in -1..1)
for (y in -1..1) {
if ( (x != 0 || y != 0)
&& i + x >= 0 && i + x <= rows - 1
&& j + y >= 0 && j + y <= cols - 1
&& input[i + x][j + y] == '#'
) {
countOccupied++
}
}
return countOccupied
}
fun countVisibleAdjacentSeats(row: Int, rows: Int, col: Int, cols: Int, input: List<CharArray>): Int {
var countOccupied = 0
for (dCol in -1..1) {
var currentCol = col + dCol
if (currentCol in 0 until cols) {
for (dRow in -1..1) {
if (dCol != 0 || dRow != 0) {
var currentRow = row + dRow
currentCol = col + dCol
while (currentCol in 0 until cols && currentRow in 0 until rows && input[currentRow][currentCol] == '.') {
currentCol += dCol
currentRow += dRow
}
if (currentCol in 0 until cols && currentRow in 0 until rows && input[currentRow][currentCol] == '#') {
countOccupied++
}
}
}
}
}
return countOccupied
}
private fun inputToArrayLists(input: String): List<CharArray> {
return input.split("\n").map { it.toCharArray() }
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle11$main$calculateOccupiedSeats$1.class",
"javap": "Compiled from \"Puzzle11.kt\"\nfinal class Puzzle11$main$calculateOccupiedSeats$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function5<java.lang.Integer, java.la... |
namyxc__adventOfCode2020__60fa699/src/main/kotlin/Puzzle10.kt | import java.math.BigInteger
object Puzzle10 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle10::class.java.getResource("puzzle10.txt").readText()
val count1and3diffInInput = count1and3diffInInput(input)
println(count1and3diffInInput.first * count1and3diffInInput.second)
val countAvailableConfigurations = countAvailableConfigurations(input)
println(countAvailableConfigurations)
}
fun count1and3diffInInput(input: String): Pair<Int, Int> {
val orderedNumbers = inputToSortedList(input)
var diff1 = 0
var diff3 = 0
for ( i in 1 until orderedNumbers.count()){
val diff = orderedNumbers[i] - orderedNumbers[i-1]
if (diff == 1) diff1 ++
if (diff == 3) diff3 ++
}
return Pair(diff1, diff3)
}
private fun inputToSortedList(input: String): List<Int> {
val numbers = input.split("\n").map(String::toInt)
val numbersWithStartAndEnd = numbers + 0 + (numbers.maxOrNull()!! + 3)
return numbersWithStartAndEnd.sorted()
}
fun countAvailableConfigurations(input: String): BigInteger {
val orderedNumbers = inputToSortedList(input)
val parentsMap = HashMap<Int, MutableList<Int>>()
for ( i in orderedNumbers) {
for (j in 1..3) {
val parent = i - j
if (orderedNumbers.contains(parent)) {
if (!parentsMap.containsKey(i)) {
parentsMap[i] = ArrayList()
}
parentsMap[i]!!.add(parent)
}
}
}
val parentCount = HashMap<Int, BigInteger>()
for (num in orderedNumbers){
val parents = parentsMap[num]
if (parents == null){
parentCount[num] = BigInteger.ONE
}else{
parentCount[num] = parents.map{ parentCount[it]!!}.sumOf { it }
}
}
val maxValue = orderedNumbers.maxOrNull()!!
return parentCount[maxValue]!!
}
} | [
{
"class_path": "namyxc__adventOfCode2020__60fa699/Puzzle10.class",
"javap": "Compiled from \"Puzzle10.kt\"\npublic final class Puzzle10 {\n public static final Puzzle10 INSTANCE;\n\n private Puzzle10();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.... |
xieweiking__leetcode-cn__a7a1fc3/problems/0005_longest-palindromic-substring/manacher/Solution.kt | class Solution {
fun longestPalindrome(s: String): String {
if (s.length <= 1)
return s
val size = 2 * s.length + 1;
val t = CharArray(size)
for (i in 0..(s.length - 1))
t[2 * i + 1] = s[i]
val pLens = IntArray(size)
var c = 0
var r = 0
var maxPLen = 0
var idx = 0
for (i in 0..(size - 1)) {
val j = 2 * c - i;
var pLen = if (r > i) Math.min(r - i, pLens[j])
else 0
var posLeft = i - (pLen + 1)
var posRight = i + (pLen + 1)
while (0 <= posLeft && posRight < size &&
t[posLeft] == t[posRight]) {
++pLen
--posLeft
++posRight
}
pLens[i] = pLen
val newR = i + pLen
if (newR > r) {
c = i
r = newR
}
if (pLen > maxPLen) {
maxPLen = pLen
idx = i
}
}
val start = (idx - maxPLen) / 2
return s.substring(start, start + maxPLen)
}
}
| [
{
"class_path": "xieweiking__leetcode-cn__a7a1fc3/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class Solution {\n public Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public f... |
ggsant__algorithms_analysis_and_data_structure__8ebed6d/algorithms_and_data_structure/with_kotlin/algoritms/LinearSearchAlgorithms.kt | /**
* Idea: Go through the vector, analyzing each position i. If A[i].key equals K, then it found the
* position and returns i. If you went through the entire vector and no element equal to K exists,
* then return -1.
*
* Linear search is an algorithm which finds the position of a target value within an array (Usually
* unsorted)
*
* Worst-case performance O(n) Best-case performance O(1) Average performance O(n) Worst-case space
* complexity O(1)
*/
fun main() {
val array = intArrayOf(-6, -1, 3, 7, 10, 27, 35, 37, 52)
val k1 = 27
val k2 = 2
println("Result for k1 ${linearSearch(array, k1)}")
println("Result for k2 ${linearSearch(array, k2)}")
}
/**
* @param array is an array where the element should be found
* @param k is an element which should be found
* @return index of the element
*/
fun linearSearch(array: IntArray, k: Int): Int {
for (i in array.indices) {
if (array[i].compareTo(k) == 0) {
return i
}
}
return -1
}
| [
{
"class_path": "ggsant__algorithms_analysis_and_data_structure__8ebed6d/LinearSearchAlgorithmsKt.class",
"javap": "Compiled from \"LinearSearchAlgorithms.kt\"\npublic final class LinearSearchAlgorithmsKt {\n public static final void main();\n Code:\n 0: bipush 9\n 2: newarray i... |
ggsant__algorithms_analysis_and_data_structure__8ebed6d/algorithms_and_data_structure/with_kotlin/algoritms/BinarySearch.kt | class BinarySearchSolution
fun main() {
print(binarySearch(arrayOf(12, 3, 24, 5, 10, 23, 9), 23))
}
/**
* @param array is an array where the element should be found
* @param key is an element which should be found
* @return index of the element
*/
fun <T : Comparable<T>> binarySearch(array: Array<T>, key: T): Int {
return binarySearchHelper(array, key, 0, array.size - 1)
}
/**
* @param array The array to search
* @param key The element you are looking for
* @param left is the index of the first element at array.
* @param is the index of the last element at array.
* @return the location of the key or -1 if the element is not found
*/
fun <T : Comparable<T>> binarySearchHelper(array: Array<T>, key: T, start: Int, end: Int): Int {
if (start > end) {
return -1
}
val mid = start + (end - start) / 2
return when {
array[mid].compareTo(key) == 0 -> mid
array[mid].compareTo(key) > 0 -> binarySearchHelper(array, key, start, mid - 1)
else -> binarySearchHelper(array, key, mid + 1, end)
}
}
| [
{
"class_path": "ggsant__algorithms_analysis_and_data_structure__8ebed6d/BinarySearchKt.class",
"javap": "Compiled from \"BinarySearch.kt\"\npublic final class BinarySearchKt {\n public static final void main();\n Code:\n 0: bipush 7\n 2: anewarray #8 // class jav... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/SortCharactersByFrequency.kt | /**
* Given a string s, sort it in decreasing order based on the frequency of the characters.
* The frequency of a character is the number of times it appears in the string.
*
* Return the sorted string. If there are multiple answers, return any of them.
*
*
*
* Example 1:
*
* Input: s = "tree"
* Output: "eert"
* Explanation: 'e' appears twice while 'r' and 't' both appear once.
* So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
* Example 2:
*
* Input: s = "cccaaa"
* Output: "aaaccc"
* Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
* Note that "cacaca" is incorrect, as the same characters must be together.
* Example 3:
*
* Input: s = "Aabb"
* Output: "bbAa"
* Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
* Note that 'A' and 'a' are treated as two different characters.
*
*
* Constraints:
*
* 1 <= s.length <= 5 * 10^5
* s consists of uppercase and lowercase English letters and digits.
* @see <a href="https://leetcode.com/problems/sort-characters-by-frequency/">LeetCode</a>
*/
fun frequencySort(s: String): String {
val frequencyMap = mutableMapOf<Char, Int>()
s.forEach { char ->
frequencyMap[char] = 1 + frequencyMap.getOrDefault(char, 0)
}
val charsByFrequencyMap = mutableMapOf<Int, MutableList<Char>>()
frequencyMap.forEach { char, frequency ->
if (!charsByFrequencyMap.contains(frequency)) {
charsByFrequencyMap[frequency] = mutableListOf(char)
} else {
charsByFrequencyMap[frequency]?.add(char)
}
}
val result = StringBuilder()
for (frequency in s.length downTo 1) {
charsByFrequencyMap[frequency]?.forEach { char ->
repeat(frequency) {
result.append(char)
}
}
}
return result.toString()
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/SortCharactersByFrequencyKt.class",
"javap": "Compiled from \"SortCharactersByFrequency.kt\"\npublic final class SortCharactersByFrequencyKt {\n public static final java.lang.String frequencySort(java.lang.String);\n Code:\n 0: aload_0\n 1: ld... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/PartitionArrayForMaximumSum.kt | /**
* Given an integer array arr, partition the array into (contiguous) subarrays of length at most k.
* After partitioning, each subarray has their values changed to become the maximum value of that subarray.
*
* Return the largest sum of the given array after partitioning.
* Test cases are generated so that the answer fits in a 32-bit integer.
*
*
*
* Example 1:
*
* Input: arr = [1,15,7,9,2,5,10], k = 3
* Output: 84
* Explanation: arr becomes [15,15,15,9,10,10,10]
* Example 2:
*
* Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
* Output: 83
* Example 3:
*
* Input: arr = [1], k = 1
* Output: 1
*
*
* Constraints:
*
* 1 <= arr.length <= 500
* 0 <= arr[i] <= 10^9
* 1 <= k <= arr.length
* @see <a https://leetcode.com/problems/partition-array-for-maximum-sum/">LeetCode</a>
*/
fun maxSumAfterPartitioning(arr: IntArray, k: Int): Int {
val arraySize = arr.size
// memoryArray[i] will hold the maximum sum we can get for the first i elements of arr, with memoryArray[0] = 0
val memoryArray = IntArray(arraySize + 1)
for (index in 1..arraySize) {
var subarrayMaxElement = 0
for (subarraySize in 1..minOf(k, index)) {
subarrayMaxElement = subarrayMaxElement.coerceAtLeast(arr[index - subarraySize])
val sum = memoryArray[index - subarraySize] + subarraySize * subarrayMaxElement
memoryArray[index] = memoryArray[index].coerceAtLeast(sum)
}
}
return memoryArray[arraySize]
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/PartitionArrayForMaximumSumKt.class",
"javap": "Compiled from \"PartitionArrayForMaximumSum.kt\"\npublic final class PartitionArrayForMaximumSumKt {\n public static final int maxSumAfterPartitioning(int[], int);\n Code:\n 0: aload_0\n 1: ldc ... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/SequentialDigits.kt | /**
* An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
*
* Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
*
*
*
* Example 1:
*
* Input: low = 100, high = 300
* Output: [123,234]
* Example 2:
*
* Input: low = 1000, high = 13000
* Output: [1234,2345,3456,4567,5678,6789,12345]
*
*
* Constraints:
*
* 10 <= low <= high <= 10^9
* @see <a href="https://leetcode.com/problems/sequential-digits/">LeetCode</a>
*/
fun sequentialDigits(low: Int, high: Int): List<Int> {
val result = mutableListOf<Int>()
val lengthOfLow = low.toString().length
val maxStartDigit = 10 - lengthOfLow
val numbersQueue = ArrayDeque<Int>()
for (startDigit in 1..maxStartDigit) {
var number = startDigit
for (index in 1 until lengthOfLow) {
number = number * 10 + startDigit + index
}
numbersQueue.add(number)
}
while (numbersQueue.isNotEmpty()) {
val currentNumber = numbersQueue.removeFirst()
if (currentNumber > high) {
return result
}
if (currentNumber >= low) {
result.add(currentNumber)
}
currentNumber.rem(10).let { lastDigit ->
if (lastDigit != 9) {
numbersQueue.add(currentNumber * 10 + lastDigit + 1)
}
}
}
return result
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/SequentialDigitsKt.class",
"javap": "Compiled from \"SequentialDigits.kt\"\npublic final class SequentialDigitsKt {\n public static final java.util.List<java.lang.Integer> sequentialDigits(int, int);\n Code:\n 0: new #10 //... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/DailyTemperatures.kt | /**
* Given an array of integers temperatures represents the daily temperatures,
* return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature.
* If there is no future day for which this is possible, keep answer[i] == 0 instead.
*
*
*
* Example 1:
*
* Input: temperatures = [73,74,75,71,69,72,76,73]
* Output: [1,1,4,2,1,1,0,0]
* Example 2:
*
* Input: temperatures = [30,40,50,60]
* Output: [1,1,1,0]
* Example 3:
*
* Input: temperatures = [30,60,90]
* Output: [1,1,0]
*
*
* Constraints:
*
* 1 <= temperatures.length <= 10^5
* 30 <= temperatures[i] <= 100
* @see <a href="https://leetcode.com/problems/daily-temperatures/">LeetCode</a>
*/
fun dailyTemperatures(temperatures: IntArray): IntArray {
val stack = ArrayDeque<Pair<Int, Int>>()
val answer = IntArray(temperatures.size)
for (index in (0 until temperatures.size).reversed()) {
while (stack.isNotEmpty() && temperatures[index] >= stack.last().first) {
stack.removeLast()
}
answer[index] = if (stack.isEmpty()) 0 else stack.last().second - index
stack.add(Pair(temperatures[index], index))
}
return answer
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/DailyTemperaturesKt.class",
"javap": "Compiled from \"DailyTemperatures.kt\"\npublic final class DailyTemperaturesKt {\n public static final int[] dailyTemperatures(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String ... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/QuicksortDualPivot.kt | /**
* Swap two elements in an array.
*/
private fun swap(arr: Array<Int>, i: Int, j: Int) {
val temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
/**
* Partition the array around two pivots.
* Return the indices of the pivots.
*/
private fun partition(arr: Array<Int>, left: Int, right: Int): Pair<Int, Int> {
if (arr[left] > arr[right]) swap(arr, left, right)
val leftPivot = arr[left]
val rightPivot = arr[right]
var leftPivotIndex = left
var rightPivotIndex = right
for (index in leftPivotIndex+1 until rightPivotIndex) {
if (arr[index] < leftPivot) {
leftPivotIndex++
swap(arr, leftPivotIndex, index)
} else if (arr[index] >= rightPivot) {
while (arr[rightPivotIndex-1] > rightPivot && index < rightPivotIndex-1) rightPivotIndex--
rightPivotIndex--
swap(arr, rightPivotIndex, index)
if (arr[index] < leftPivot) {
leftPivotIndex++
swap(arr, leftPivotIndex, index)
}
}
}
swap(arr, left, leftPivotIndex)
swap(arr, right, rightPivotIndex)
return Pair(leftPivotIndex, rightPivotIndex)
}
/**
* Quick sort the array using two pivots.
*/
private fun quickSortDualPivot(arr: Array<Int>, left: Int, right: Int) {
if (left < right) {
val pivotIndices = partition(arr, left, right)
quickSortDualPivot(arr, left, pivotIndices.first - 1)
quickSortDualPivot(arr, pivotIndices.first + 1, pivotIndices.second - 1)
quickSortDualPivot(arr, pivotIndices.second + 1, right)
}
}
fun main() {
val arrayOfIntegers = readLine()?.trimEnd()?.split(" ")?.map { it.toInt() }?.toTypedArray() ?: return
quickSortDualPivot(arrayOfIntegers, 0, arrayOfIntegers.size-1)
arrayOfIntegers.forEach { print("$it ") }
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/QuicksortDualPivotKt.class",
"javap": "Compiled from \"QuicksortDualPivot.kt\"\npublic final class QuicksortDualPivotKt {\n private static final void swap(java.lang.Integer[], int, int);\n Code:\n 0: aload_0\n 1: iload_1\n 2: aaload\n ... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/LargestDivisibleSubset.kt | /**
* Given a set of distinct positive integers nums,
* return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:
*
* answer[i] % answer[j] == 0, or
* answer[j] % answer[i] == 0
* If there are multiple solutions, return any of them.
*
*
*
* Example 1:
*
* Input: nums = [1,2,3]
* Output: [1,2]
* Explanation: [1,3] is also accepted.
* Example 2:
*
* Input: nums = [1,2,4,8]
* Output: [1,2,4,8]
*
*
* Constraints:
*
* 1 <= nums.length <= 1000
* 1 <= nums[i] <= 2 * 10^9
* All the integers in nums are unique.
* @see <a href="https://leetcode.com/problems/largest-divisible-subset/">LeetCode</a>
*/
fun largestDivisibleSubset(nums: IntArray): List<Int> {
val sortedNums = nums.sorted()
val subsets = MutableList(sortedNums.size) { listOf<Int>() }
var largestSubsetIndex = 0
for ((index, num) in sortedNums.withIndex()) {
var currentSubset = listOf(num)
for (previousIndex in 0 until index) {
val previousSubset = subsets[previousIndex]
if (num % previousSubset.last() == 0 && previousSubset.size >= currentSubset.size) {
currentSubset = previousSubset + num
}
}
subsets[index] = currentSubset
if (subsets[index].size > subsets[largestSubsetIndex].size) {
largestSubsetIndex = index
}
}
return subsets[largestSubsetIndex]
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/LargestDivisibleSubsetKt.class",
"javap": "Compiled from \"LargestDivisibleSubset.kt\"\npublic final class LargestDivisibleSubsetKt {\n public static final java.util.List<java.lang.Integer> largestDivisibleSubset(int[]);\n Code:\n 0: aload_0\n ... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/EvaluateReversePolishNotation.kt | /**
* You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
*
* Evaluate the expression. Return an integer that represents the value of the expression.
*
* Note that:
*
* The valid operators are '+', '-', '*', and '/'.
* Each operand may be an integer or another expression.
* The division between two integers always truncates toward zero.
* There will not be any division by zero.
* The input represents a valid arithmetic expression in a reverse polish notation.
* The answer and all the intermediate calculations can be represented in a 32-bit integer.
*
*
* Example 1:
*
* Input: tokens = ["2","1","+","3","*"]
* Output: 9
* Explanation: ((2 + 1) * 3) = 9
* Example 2:
*
* Input: tokens = ["4","13","5","/","+"]
* Output: 6
* Explanation: (4 + (13 / 5)) = 6
* Example 3:
*
* Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
* Output: 22
* Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
* = ((10 * (6 / (12 * -11))) + 17) + 5
* = ((10 * (6 / -132)) + 17) + 5
* = ((10 * 0) + 17) + 5
* = (0 + 17) + 5
* = 17 + 5
* = 22
*
*
* Constraints:
*
* 1 <= tokens.length <= 104
* tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
* @see <a href="https://leetcode.com/problems/evaluate-reverse-polish-notation/">LeetCode</a>
*/
fun evalRPN(tokens: Array<String>): Int {
val listOfOperators = listOf("+", "-", "*", "/")
val stack = ArrayDeque<Int>()
tokens.forEach { token ->
if (token in listOfOperators) {
val operand2 = stack.removeLast()
val operand1 = stack.removeLast()
val result = operate(operand1, operand2, token)
stack.addLast(result)
} else {
stack.addLast(token.toInt())
}
}
return stack.last()
}
private fun operate(operand1: Int, operand2: Int, operator: String) = when (operator) {
"+" -> operand1 + operand2
"-" -> operand1 - operand2
"*" -> operand1 * operand2
"/" -> operand1 / operand2
else -> 0
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/EvaluateReversePolishNotationKt.class",
"javap": "Compiled from \"EvaluateReversePolishNotation.kt\"\npublic final class EvaluateReversePolishNotationKt {\n public static final int evalRPN(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc ... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/KInversePairsArray.kt | /**
* For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].
*
* Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs.
* Since the answer can be huge, return it modulo 10^9 + 7.
*
*
*
* Example 1:
*
* Input: n = 3, k = 0
* Output: 1
* Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.
* Example 2:
*
* Input: n = 3, k = 1
* Output: 2
* Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.
*
*
* Constraints:
*
* 1 <= n <= 1000
* 0 <= k <= 1000
* @see <a href="https://leetcode.com/problems/k-inverse-pairs-array/">LeetCode</a>
*/
fun kInversePairs(n: Int, k: Int): Int {
val memoryArray = Array<IntArray>(n + 1) { IntArray(k + 1) { -1 } }
return numberOfArrays(n, k, memoryArray)
}
fun numberOfArrays(numberOfElements: Int, numberOfInversePairsRequired: Int, memoryArray: Array<IntArray>): Int {
// since 1 <= numberOfElements, numberOfInversePairsRequired = 0 can only be achieved in one way,
// by arranging the elements of the array in increasing order
if (numberOfInversePairsRequired == 0) {
return 1
}
// if numberOfInversePairsRequired is non zero, it cannot be achieved with just one element
if (numberOfElements == 1 || numberOfInversePairsRequired < 0) {
return 0
}
if (memoryArray[numberOfElements][numberOfInversePairsRequired] != -1) {
return memoryArray[numberOfElements][numberOfInversePairsRequired]
}
var totalNumberOfArrays = 0
for (numberOfInversePairsEncountered in 0 until numberOfElements) {
totalNumberOfArrays = (
totalNumberOfArrays +
numberOfArrays(
numberOfElements - 1,
numberOfInversePairsRequired - numberOfInversePairsEncountered,
memoryArray
)
).mod(1_00_00_00_007)
}
memoryArray[numberOfElements][numberOfInversePairsRequired] = totalNumberOfArrays
return totalNumberOfArrays
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/KInversePairsArrayKt.class",
"javap": "Compiled from \"KInversePairsArray.kt\"\npublic final class KInversePairsArrayKt {\n public static final int kInversePairs(int, int);\n Code:\n 0: iconst_0\n 1: istore_3\n 2: iload_0\n 3: icon... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/MinimumWindowSubstring.kt | /**
* Given two strings s and t of lengths m and n respectively, return the minimum window
* substring
* of s such that every character in t (including duplicates) is included in the window.
* If there is no such substring, return the empty string "".
*
* The testcases will be generated such that the answer is unique.
*
*
*
* Example 1:
*
* Input: s = "ADOBECODEBANC", t = "ABC"
* Output: "BANC"
* Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
* Example 2:
*
* Input: s = "a", t = "a"
* Output: "a"
* Explanation: The entire string s is the minimum window.
* Example 3:
*
* Input: s = "a", t = "aa"
* Output: ""
* Explanation: Both 'a's from t must be included in the window.
* Since the largest window of s only has one 'a', return empty string.
*
*
* Constraints:
*
* m == s.length
* n == t.length
* 1 <= m, n <= 10^5
* s and t consist of uppercase and lowercase English letters.
*
*
* Follow up: Could you find an algorithm that runs in O(m + n) time?
* @see <a https://leetcode.com/problems/minimum-window-substring/">LeetCode</a>
*/
fun minWindow(s: String, t: String): String {
val sFrequencyMap = mutableMapOf<Char, Int>()
val tFrequencyMap = mutableMapOf<Char, Int>()
t.forEach { char ->
tFrequencyMap[char] = 1 + tFrequencyMap.getOrDefault(char, 0)
}
var start = 0
var end = 0
var minWindowStart = 0
var minWindowLength = Int.MAX_VALUE
var requiredChars = tFrequencyMap.size
while (start < s.length && end < s.length) {
while (end < s.length && requiredChars > 0) {
val endChar = s[end]
sFrequencyMap[endChar] = 1 + sFrequencyMap.getOrDefault(endChar, 0)
if (sFrequencyMap[endChar] == tFrequencyMap[endChar]) {
requiredChars--
}
end++
}
if (requiredChars > 0) {
break
}
var startChar = s[start]
while (!tFrequencyMap.containsKey(startChar) || sFrequencyMap[startChar]!! > tFrequencyMap[startChar]!!) {
sFrequencyMap[startChar] = sFrequencyMap[startChar]!! - 1
start++
startChar = s[start]
}
if (end - start < minWindowLength) {
minWindowLength = end - start
minWindowStart = start
}
sFrequencyMap[startChar] = sFrequencyMap[startChar]!! - 1
requiredChars++
start++
}
return if (minWindowLength == Int.MAX_VALUE) {
""
} else {
s.substring(minWindowStart until minWindowStart + minWindowLength)
}
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/MinimumWindowSubstringKt.class",
"javap": "Compiled from \"MinimumWindowSubstring.kt\"\npublic final class MinimumWindowSubstringKt {\n public static final java.lang.String minWindow(java.lang.String, java.lang.String);\n Code:\n 0: aload_0\n ... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/DivideArrayIntoArraysWithMaxDifference.kt | /**
* You are given an integer array nums of size n and a positive integer k.
*
* Divide the array into one or more arrays of size 3 satisfying the following conditions:
*
* Each element of nums should be in exactly one array.
* The difference between any two elements in one array is less than or equal to k.
* Return a 2D array containing all the arrays. If it is impossible to satisfy the conditions, return an empty array.
* And if there are multiple answers, return any of them.
*
*
*
* Example 1:
*
* Input: nums = [1,3,4,8,7,9,3,5,1], k = 2
* Output: [[1,1,3],[3,4,5],[7,8,9]]
* Explanation: We can divide the array into the following arrays: [1,1,3], [3,4,5] and [7,8,9].
* The difference between any two elements in each array is less than or equal to 2.
* Note that the order of elements is not important.
* Example 2:
*
* Input: nums = [1,3,3,2,7,3], k = 3
* Output: []
* Explanation: It is not possible to divide the array satisfying all the conditions.
*
*
* Constraints:
*
* n == nums.length
* 1 <= n <= 10^5
* n is a multiple of 3.
* 1 <= nums[i] <= 10^5
* 1 <= k <= 10^5
* @see <a href="https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/">LeetCode</a>
*/
fun divideArray(nums: IntArray, k: Int): Array<IntArray> {
val numsSize = nums.size
val dividedArraysColumns = 3
val dividedArraysRows = numsSize / dividedArraysColumns
val sortedNums = nums.sorted()
val dividedArrays = Array<IntArray>(dividedArraysRows) { IntArray(dividedArraysColumns) }
for (index in 0 until numsSize) {
val row = index / dividedArraysColumns
val column = index.rem(dividedArraysColumns)
if (column == 0) {
dividedArrays[row][column] = sortedNums[index]
} else if (column == 1 && sortedNums[index] - sortedNums[index - 1] <= k) {
dividedArrays[row][column] = sortedNums[index]
} else if (column == 2 && sortedNums[index] - sortedNums[index - 2] <= k) {
dividedArrays[row][column] = sortedNums[index]
} else {
return arrayOf<IntArray>()
}
}
return dividedArrays
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/DivideArrayIntoArraysWithMaxDifferenceKt.class",
"javap": "Compiled from \"DivideArrayIntoArraysWithMaxDifference.kt\"\npublic final class DivideArrayIntoArraysWithMaxDifferenceKt {\n public static final int[][] divideArray(int[], int);\n Code:\n 0:... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/GroupAnagrams.kt | /**
* Given an array of strings strs, group the anagrams together. You can return the answer in any order.
*
* An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
* typically using all the original letters exactly once.
*
*
*
* Example 1:
*
* Input: strs = ["eat","tea","tan","ate","nat","bat"]
* Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
* Example 2:
*
* Input: strs = [""]
* Output: [[""]]
* Example 3:
*
* Input: strs = ["a"]
* Output: [["a"]]
*
*
* Constraints:
*
* 1 <= strs.length <= 10^4
* 0 <= strs[i].length <= 100
* strs[i] consists of lowercase English letters.
* @see <a href="https://leetcode.com/problems/group-anagrams/">LeetCode</a>
*/
fun groupAnagrams(strs: Array<String>): List<List<String>> {
val resultMap = mutableMapOf<List<Int>, MutableList<String>>()
strs.forEach { string ->
val countArray = IntArray(26)
string.forEach { char ->
countArray[char - 'a'] += 1
}
val key = countArray.toList()
val currentList = resultMap.getOrDefault(key, mutableListOf())
currentList.add(string)
resultMap[key] = currentList
}
val resultList = mutableListOf<List<String>>()
resultMap.values.forEach { listOfString ->
resultList.add(listOfString)
}
return resultList
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/GroupAnagramsKt.class",
"javap": "Compiled from \"GroupAnagrams.kt\"\npublic final class GroupAnagramsKt {\n public static final java.util.List<java.util.List<java.lang.String>> groupAnagrams(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc ... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/SubarraySumEqualsK.kt | /**
* Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
*
* A subarray is a contiguous non-empty sequence of elements within an array.
*
*
*
* Example 1:
*
* Input: nums = [1,1,1], k = 2
* Output: 2
* Example 2:
*
* Input: nums = [1,2,3], k = 3
* Output: 2
*
*
* Constraints:
*
* 1 <= nums.length <= 2 * 10^4
* -1000 <= nums[i] <= 1000
* -10^7 <= k <= 10^7
*/
fun subarraySum(nums: IntArray, k: Int): Int {
val prefixSumCount = mutableMapOf<Int, Int>()
prefixSumCount[0] = 1
var currentPrefixSum = 0
var subarraysWithSumK = 0
for (number in nums) {
currentPrefixSum += number
val complement = currentPrefixSum - k
subarraysWithSumK += prefixSumCount.getOrDefault(complement, 0)
prefixSumCount[currentPrefixSum] = prefixSumCount.getOrDefault(currentPrefixSum, 0) + 1
}
return subarraysWithSumK
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/SubarraySumEqualsKKt.class",
"javap": "Compiled from \"SubarraySumEqualsK.kt\"\npublic final class SubarraySumEqualsKKt {\n public static final int subarraySum(int[], int);\n Code:\n 0: aload_0\n 1: ldc #9 // String ... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/PerfectSquares.kt | /**
* Given an integer n, return the least number of perfect square numbers that sum to n.
*
* A perfect square is an integer that is the square of an integer;
* in other words, it is the product of some integer with itself.
* For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.
*
*
*
* Example 1:
*
* Input: n = 12
* Output: 3
* Explanation: 12 = 4 + 4 + 4.
* Example 2:
*
* Input: n = 13
* Output: 2
* Explanation: 13 = 4 + 9.
*
*
* Constraints:
*
* 1 <= n <= 10^4
* @see <a href="https://leetcode.com/problems/perfect-squares/">LeetCode</a>
*/
fun numSquares(n: Int): Int {
val resultList = IntArray(n + 1) { Int.MAX_VALUE }
resultList[0] = 0
for (index in 1..n) {
var squareNum = 1
while (index >= squareNum * squareNum) {
resultList[index] = minOf(resultList[index], 1 + resultList[index - squareNum * squareNum])
squareNum++
}
}
return resultList[n]
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/PerfectSquaresKt.class",
"javap": "Compiled from \"PerfectSquares.kt\"\npublic final class PerfectSquaresKt {\n public static final int numSquares(int);\n Code:\n 0: iconst_0\n 1: istore_2\n 2: iload_0\n 3: iconst_1\n 4: iadd... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/LongestCommonSubsequence.kt | /**
* Given two strings text1 and text2, return the length of their longest common subsequence.
* If there is no common subsequence, return 0.
*
* A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
*
* For example, "ace" is a subsequence of "abcde".
* A common subsequence of two strings is a subsequence that is common to both strings.
*
*
*
* Example 1:
*
* Input: text1 = "abcde", text2 = "ace"
* Output: 3
* Explanation: The longest common subsequence is "ace" and its length is 3.
* Example 2:
*
* Input: text1 = "abc", text2 = "abc"
* Output: 3
* Explanation: The longest common subsequence is "abc" and its length is 3.
* Example 3:
*
* Input: text1 = "abc", text2 = "def"
* Output: 0
* Explanation: There is no such common subsequence, so the result is 0.
*
*
* Constraints:
*
* 1 <= text1.length, text2.length <= 1000
* text1 and text2 consist of only lowercase English characters.
* @see <a https://leetcode.com/problems/longest-common-subsequence/">LeetCode</a>
*/
fun longestCommonSubsequence(text1: String, text2: String): Int {
if (text1.isEmpty() || text2.isEmpty()) {
return 0
}
val memoryArray = Array<IntArray>(text1.length + 1) { IntArray(text2.length + 1) }
for (index1 in (0 until text1.length).reversed()) {
for (index2 in (0 until text2.length).reversed()) {
val length = if (text1[index1] == text2[index2]) {
1 + memoryArray[index1 + 1][index2 + 1]
} else {
maxOf(memoryArray[index1 + 1][index2], memoryArray[index1][index2 + 1])
}
memoryArray[index1][index2] = length
}
}
return memoryArray[0][0]
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/LongestCommonSubsequenceKt.class",
"javap": "Compiled from \"LongestCommonSubsequence.kt\"\npublic final class LongestCommonSubsequenceKt {\n public static final int longestCommonSubsequence(java.lang.String, java.lang.String);\n Code:\n 0: aload_0\... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/PalindromicSubstrings.kt | /**
* Given a string s, return the number of palindromic substrings in it.
*
* A string is a palindrome when it reads the same backward as forward.
*
* A substring is a contiguous sequence of characters within the string.
*
*
*
* Example 1:
*
* Input: s = "abc"
* Output: 3
* Explanation: Three palindromic strings: "a", "b", "c".
* Example 2:
*
* Input: s = "aaa"
* Output: 6
* Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
*
*
* Constraints:
*
* 1 <= s.length <= 1000
* s consists of lowercase English letters.
* @see <a href="https://leetcode.com/problems/palindromic-substrings/">LeetCode</a>
*/
fun countSubstrings(s: String): Int {
var substringCount = 0
for (index in s.indices) {
substringCount += countSubstringsWithCenter(s, index, index)
substringCount += countSubstringsWithCenter(s, index, index + 1)
}
return substringCount
}
private fun countSubstringsWithCenter(s: String, start: Int, end: Int): Int {
var count = 0
var startIndex = start
var endIndex = end
while (startIndex >= 0 && endIndex < s.length && s[startIndex] == s[endIndex]) {
count++
startIndex--
endIndex++
}
return count
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/PalindromicSubstringsKt.class",
"javap": "Compiled from \"PalindromicSubstrings.kt\"\npublic final class PalindromicSubstringsKt {\n public static final int countSubstrings(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
Codextor__kotlin-codes__68b75a7/src/main/kotlin/QuickSort.kt | /**
* Swap two elements in an array.
*/
private fun swap(arr: Array<Int>, i: Int, j: Int) {
val temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
/**
* Partition the array around a randomly selected pivot.
* Return the index of the pivot.
*/
private fun partition(arr: Array<Int>, left: Int, right: Int): Int {
val randomIndex = (left..right).random()
swap(arr, randomIndex, right)
val pivot = arr[right]
var pivotIndex = left - 1
for (index in left..right) {
if (arr[index] <= pivot) {
pivotIndex++
swap(arr, pivotIndex, index)
}
}
return pivotIndex
}
/**
* Quick sort the array.
*/
private fun quickSort(arr: Array<Int>, left: Int, right: Int) {
if (left < right) {
val pivotIndex = partition(arr, left, right)
quickSort(arr, left, pivotIndex - 1)
quickSort(arr, pivotIndex + 1, right)
}
}
fun main() {
val arrayOfIntegers = readLine()?.trimEnd()?.split(" ")?.map { it.toInt() }?.toTypedArray() ?: return
quickSort(arrayOfIntegers, 0, arrayOfIntegers.size-1)
arrayOfIntegers.forEach { print("$it ") }
}
| [
{
"class_path": "Codextor__kotlin-codes__68b75a7/QuickSortKt.class",
"javap": "Compiled from \"QuickSort.kt\"\npublic final class QuickSortKt {\n private static final void swap(java.lang.Integer[], int, int);\n Code:\n 0: aload_0\n 1: iload_1\n 2: aaload\n 3: invokevirtual #12 ... |
Uberts94__kotlin__ce54675/exercises/practice/minesweeper/src/main/kotlin/Minesweeper.kt | data class MinesweeperBoard(val inputBoard: List<String>) {
fun withNumbers(): List<String> =
inputBoard.mapIndexed { row, str ->
str.mapIndexed { col, cell -> when (cell) {
'.' -> adjacentMines(row, col)
else -> cell
}
}.joinToString("")
}
private fun adjacentMines(row: Int, col: Int): Char {
val count =
(Math.max(0, row - 1)..Math.min(inputBoard.size - 1, row + 1))
.flatMap { i ->
(Math.max(0, col - 1)..Math.min(inputBoard[i].length - 1, col + 1))
.map { j ->
if (inputBoard[i][j] == '*') 1 else 0
}
}
.sum()
return if (count > 0) (count + 48).toChar() else '.'
}
}
fun main(args: Array<String>) {
val a = MinesweeperBoard(
listOf<String>(".", "*", ".", "*", ".", ".", ".", "*", ".", ".",
".", ".", "*", ".", ".", ".", ".", ".", ".", "."))
println("Minesweeper board:")
println(a.withNumbers())
}
| [
{
"class_path": "Uberts94__kotlin__ce54675/MinesweeperKt.class",
"javap": "Compiled from \"Minesweeper.kt\"\npublic final class MinesweeperKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokesta... |
bertptrs__adventofcode__1f41f4b/2017/day-10/solution.kt | fun valArray(): IntArray
{
val arr = IntArray(256)
for (i in arr.indices) {
arr[i] = i
}
return arr
}
fun hash(input: IntArray, values: IntArray, index: Int, skip: Int): Pair<Int, Int> {
var curIndex = index
var curSkip = skip
for (range in input) {
val halfRange = range / 2
for (i in 0..(halfRange - 1)) {
val i1 = (curIndex + i) % values.size
val i2 = (curIndex + range - i - 1) % values.size
values[i1] = values[i2].also { values[i2] = values[i1] }
}
curIndex = (curIndex + range + curSkip) % values.size
curSkip++
}
return Pair(curIndex, curSkip)
}
fun solve(input: String)
{
// Part 1
val part1input = input.split(",").map { it.toInt() }.toIntArray()
val values = valArray()
hash(part1input, values, 0, 0)
println(values[0] * values[1])
// Part 2
val part2input = ArrayList(List(input.length) { input[it].toInt()})
part2input.addAll(arrayOf(17, 31, 73, 47, 23))
val values2 = valArray()
var skip = 0
var index = 0
// Repeat hash 64 times
for (i in 1..64) {
val (newIndex, newSkip) = hash(part2input.toIntArray(), values2, index, skip)
index = newIndex
skip = newSkip
}
for (i in 0..15) {
val startIndex = 16 * i
val endIndex = startIndex + 15
val currentNum = values2.slice(startIndex..endIndex).reduce{a, b -> a.xor(b)}
print("%02x".format(currentNum))
}
println()
}
fun main(args: Array<String>)
{
solve(readLine()!!)
} | [
{
"class_path": "bertptrs__adventofcode__1f41f4b/SolutionKt.class",
"javap": "Compiled from \"solution.kt\"\npublic final class SolutionKt {\n public static final int[] valArray();\n Code:\n 0: sipush 256\n 3: newarray int\n 5: astore_0\n 6: iconst_0\n 7: istor... |
nmicra__kotlin_practice__4bf80f0/src/main/kotlin/LangDecoder.kt | /**
* Given map is how to encode any character in alphabet.
* Write a decode function, that will return all possible variant that can be encoded for a given string
* Example: for a given string "12", possible values [ab,l]
* for "1213" --> [abac, abm, auc, lac, lm]
*/
val map = mapOf(
"a" to "1", "b" to "2", "c" to "3", "d" to "4", "e" to "5",
"f" to "6", "g" to "7", "h" to "8", "i" to "9", "j" to "10",
"k" to "11", "l" to "12", "m" to "13", "n" to "14", "o" to "15",
"p" to "16", "q" to "17", "r" to "18", "s" to "19", "t" to "20",
"u" to "21", "v" to "22", "w" to "23", "x" to "24", "y" to "25", "z" to "26"
)
fun main() {
println(decode("1213"))
}
val reversedMap = map.entries.associateBy({ it.value }) { it.key }
val abcMaxLength = map["z"]?.length ?: error("Assumption that z is the last character of the alphabet")
fun splitString(str : String,n : Int) : Pair<String,String> = Pair(str.toCharArray().dropLast(str.length-n).joinToString(""),
str.toCharArray().drop(n).joinToString(""))
tailrec fun decode(str: String) : Set<String> {
fun aggregate(splitedPair : Pair<String,String>) : Set<String> {
val set = (1..splitedPair.first.length)
.map { splitString(splitedPair.first,it) }
.map { reversedMap[it.first].orEmpty() + reversedMap[it.second].orEmpty() }
.toSet()
val set2 = decode(splitedPair.second)
return set.map {el1 -> set2.map { el1 +it }.toSet() }.flatten().toSet()
}
return when {
str.length <= abcMaxLength -> (1..str.length)
.map { splitString(str,it) }
.map { reversedMap[it.first].orEmpty() + reversedMap[it.second].orEmpty() }
.toSet()
else -> (1..abcMaxLength).asSequence()
.map { splitString(str, it) }
.map { aggregate(it) }
.toSet().flatten().toSet()
}
} | [
{
"class_path": "nmicra__kotlin_practice__4bf80f0/LangDecoderKt.class",
"javap": "Compiled from \"LangDecoder.kt\"\npublic final class LangDecoderKt {\n private static final java.util.Map<java.lang.String, java.lang.String> map;\n\n private static final java.util.Map<java.lang.String, java.lang.String> re... |
nmicra__kotlin_practice__4bf80f0/src/main/kotlin/AvailableMeetingSlotsInCalendar.kt | import java.time.LocalTime
val person1_meetings = listOf("09:00-09:30", "13:00-14:00", "17:20-18:00") // Scheduled meetings for Person1
val person2_meetings = listOf( "13:30-14:30", "17:00-17:30") // Scheduled meetings for Person2
val restrictions_person1 = "08:00,19:00" // Person1 cannot accept meetings before 8:00 & after 19:00
val restrictions_person2 = "08:30,18:30" // Person2 cannot accept meetings before 8:00 & after 19:00
val findMeetingSlot : Long = 40 // minutes
val step : Long = 10 // minutes
/**
* Find all possibilities for a meeting with the duration of $findMeetingSlot minutes between Person1 & Person2
* This meeting should not overlap with already existing meetings or specified restrictions.
*/
fun main() {
val lstResults = mutableListOf<String>()
val allMeetings = parseStringListsToLocalTime(person1_meetings).plus(parseStringListsToLocalTime(person2_meetings))
var (begin, end) = determineLowerUpperRestrictions(restrictions_person1,restrictions_person2)
while (begin.plusMinutes(findMeetingSlot).isBefore(end)){
if (allMeetings.none { isOverLap(it.first,it.second,begin, begin.plusMinutes(findMeetingSlot))}){
lstResults.add("$begin - ${begin.plusMinutes(findMeetingSlot)}")
}
begin = begin.plusMinutes(step)
}
println(lstResults)
}
/**
* returns true when startTime1-endTime1 is overlaps with startTime2-endTime2
*/
fun isOverLap(start1 : LocalTime, end1 : LocalTime, start2 : LocalTime, end2 : LocalTime) : Boolean{
if((start1.isAfter(start2) && start1.isBefore(end2)) || (end1.isAfter(start2) && end1.isBefore(end2)) ||
start1.isBefore(start2) && end1.isAfter(end2) || start2.isBefore(start1) && end2.isAfter(end1)){
return true
}
return false
}
fun parseStringListsToLocalTime(list : List<String>) : List<Pair<LocalTime,LocalTime>> {
return list.map { val (left,right) = it.split("-")
Pair(LocalTime.parse(left), LocalTime.parse(right))}.toList()
}
fun determineLowerUpperRestrictions(restrictions_person1 : String, restrictions_person2 : String) : Pair<LocalTime,LocalTime>{
val (left1,right1) = restrictions_person1.split(",")
val (left2,right2) = restrictions_person2.split(",")
val lowerBound = when{
LocalTime.parse(left1).isBefore(LocalTime.parse(left2)) -> LocalTime.parse(left2)
else -> LocalTime.parse(left1)
}
val upperBound = when {
LocalTime.parse(right1).isBefore(LocalTime.parse(right2)) -> LocalTime.parse(right1)
else -> LocalTime.parse(right2)
}
return Pair(lowerBound,upperBound)
} | [
{
"class_path": "nmicra__kotlin_practice__4bf80f0/AvailableMeetingSlotsInCalendarKt.class",
"javap": "Compiled from \"AvailableMeetingSlotsInCalendar.kt\"\npublic final class AvailableMeetingSlotsInCalendarKt {\n private static final java.util.List<java.lang.String> person1_meetings;\n\n private static fi... |
carolhmj__aoc2019__a101068/day12/day12.kt | import kotlin.math.*
import java.io.File
data class Moon(val position : IntArray, val velocity : IntArray = intArrayOf(0,0,0))
data class IndexAndValue<T>(val index : Int, val value : T)
fun <T, U> cartesianProductIndexed(c1: Collection<T>, c2: Collection<U>): List<Pair<IndexAndValue<T>, IndexAndValue<U>>> {
return c1.mapIndexed { lhsIdx, lhsElem -> c2.mapIndexed { rhsIdx, rhsElem -> IndexAndValue(lhsIdx, lhsElem) to IndexAndValue(rhsIdx, rhsElem) } }.flatten()
}
fun sumArrays(a : IntArray, b : IntArray) : IntArray {
return a.zip(b).map {(x, y) -> x + y}.toIntArray()
}
fun sumAbs(a : IntArray) : Int {
return a.map { abs(it) }.sum()
}
fun calculateEnergy(moons : List<Moon>) : Int {
return moons.map { sumAbs(it.position) * sumAbs(it.velocity) }.sum()
}
fun step(moons : List<Moon>) : List<Moon> {
val accelerations = cartesianProductIndexed(moons, moons).map { (moonA, moonB) ->
moonA.index to moonA.value.position.zip(moonB.value.position).map { (posA : Int, posB : Int) ->
(posB - posA).sign
}.toIntArray()
}.groupBy({ it.first }, { it.second }).map { (k, v) -> k to v.reduce({ acc : IntArray, curr : IntArray -> sumArrays(acc, curr) }) }
val updatedMoons = accelerations.map { (idx, acceleration) ->
val newVelocity = sumArrays(moons[idx].velocity, acceleration)
val newPosition = sumArrays(moons[idx].position, newVelocity)
Moon(newPosition, newVelocity)
}
return updatedMoons
}
fun readInput(filename : String) : List<Moon> {
return File(filename).readLines().map {
val (x, y, z) = """<x=(-?\d+), y=(-?\d+), z=(-?\d+)>""".toRegex().find(it)!!.destructured
Moon(intArrayOf(x.toInt(), y.toInt(), z.toInt()))
}
}
fun main() {
// var moons = listOf(Moon(intArrayOf(-1,0,2)), Moon(intArrayOf(2,-10,-7)), Moon(intArrayOf(4,-8,8)), Moon(intArrayOf(3,5,-1)))
// var moons = listOf(Moon(intArrayOf(-8,-10,0)), Moon(intArrayOf(5,5,10)), Moon(intArrayOf(2,-7,3)), Moon(intArrayOf(9,-8,-3)))
var moons = readInput("input.txt")
println("Input moons ${moons}")
var steps = 1000
for (i in 1..steps) {
moons = step(moons)
}
println("moons after loop ${moons}")
val energy = calculateEnergy(moons)
println("Calculated energy ${energy}")
} | [
{
"class_path": "carolhmj__aoc2019__a101068/Day12Kt.class",
"javap": "Compiled from \"day12.kt\"\npublic final class Day12Kt {\n public static final <T, U> java.util.List<kotlin.Pair<IndexAndValue<T>, IndexAndValue<U>>> cartesianProductIndexed(java.util.Collection<? extends T>, java.util.Collection<? exten... |
JiangKlijna__leetcode-learning__65a1348/kt/001 Two Sum/TwoSum.kt |
/**
* Given an array of integers, return indices of the two numbers such that they add up to a specific target.
* You may assume that each input would have exactly one solution.
* 给出一个int数组和目标值,从数组中找到两个值使得其和为目标值.返回两个下标位置.
*
*/
class TwoSum {
fun twoSum(numbers: IntArray, target: Int): IntArray {
val re = IntArray(2)
val map = hashMapOf<Int, Int>()
for (i in numbers.indices) {
val idx = map[numbers[i]]
if (idx == null) {// 如果map中不存在就保存数据
map.put(target - numbers[i], i)
} else {// 若存在 即找到了所需要的元素
if (idx < i) {
re[0] = idx
re[1] = i
return re
}
}
}
return re
}
}
| [
{
"class_path": "JiangKlijna__leetcode-learning__65a1348/TwoSum.class",
"javap": "Compiled from \"TwoSum.kt\"\npublic final class TwoSum {\n public TwoSum();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public fi... |
bsautner__Advent-of-Code-2022__5f53cb1/AOC2022/src/main/kotlin/AOC7.kt | import java.io.File
class AOC7 {
private val input = File("/home/ben/aoc/input-7.txt")
private val list = mutableListOf<String>()
private var PWD = Node("root", null) //Present Working Directory
var spaceNeeded = 0L
var winner = 70000000L
fun process() {
input.forEachLine { list.add(it) }
PWD.nodes["/"] = Node("/", PWD)
buildNodeTreeFromCommandList(list, PWD)
val answer = getSmallNodesSum(PWD)
println("Part 1 $answer")
val rootSize = getNodeSize(PWD)
spaceNeeded = MAX_HD - rootSize
spaceNeeded = UPDATE_SIZE - spaceNeeded
smallestDeletableDir(PWD)
println("Part 2 $winner")
}
private fun smallestDeletableDir(node: Node) {
if (getNodeSize(node) in (spaceNeeded + 1) until winner) {
winner = getNodeSize(node)
}
node.nodes.values.forEach {
smallestDeletableDir(it)
}
}
private fun getSmallNodesSum(node: Node) : Long {
var sum = 0L
node.nodes.values.forEach {
if (getNodeSize(it) <= 100000) {
sum += getNodeSize(it)
}
sum += getSmallNodesSum(it)
}
return sum
}
private fun getNodeSize(node: Node) : Long {
var size = 0L
node.items.forEach {
size += it.size
}
node.nodes.values.forEach {
size += getNodeSize(it)
}
return size
}
private tailrec fun buildNodeTreeFromCommandList(list: List<String>, pwd: Node?) {
if (list.isEmpty()) {
return
}
val line = list.first()
val rest = list.drop(1)
val parts = line.split(" ")
if (isNumeric(parts[0])) {
val item = Item(parts[1], parts[0].toLong())
pwd?.items?.add(item)
buildNodeTreeFromCommandList(rest, pwd)
}
else {
when (parts[0]) {
"dir" -> {
pwd?.nodes?.set(parts[1], Node(parts[1], pwd))
buildNodeTreeFromCommandList(rest, pwd)
}
"$" -> {
if (parts[1] == "cd") {
if (parts[2] == "..") {
buildNodeTreeFromCommandList(rest, pwd?.parent)
} else {
val node = pwd?.nodes?.get(parts[2])
buildNodeTreeFromCommandList(rest, node)
}
// pwd = pwd.nodes[parts[2]]!!
} else if (parts[1] == "ls") {
buildNodeTreeFromCommandList(rest, pwd)
}
}
}
}
}
companion object {
private const val MAX_HD = 70000000
private const val UPDATE_SIZE = 30000000
@JvmStatic
fun main(args: Array<String>) {
AOC7().process()
}
fun isNumeric(toCheck: String): Boolean {
return toCheck.toDoubleOrNull() != null
}
}
}
data class Node(private val name: String, val parent: Node?) {
val nodes = mutableMapOf<String, Node>()
val items = mutableListOf<Item>()
}
data class Item(private val name: String, val size: Long)
| [
{
"class_path": "bsautner__Advent-of-Code-2022__5f53cb1/AOC7.class",
"javap": "Compiled from \"AOC7.kt\"\npublic final class AOC7 {\n public static final AOC7$Companion Companion;\n\n private final java.io.File input;\n\n private final java.util.List<java.lang.String> list;\n\n private Node PWD;\n\n pr... |
bsautner__Advent-of-Code-2022__5f53cb1/AOC2022/src/main/kotlin/AOC8.kt | import java.io.File
class AOC8 {
var maxScore = 0
fun process() {
val input = File("/home/ben/aoc/input-8.txt")
val sample = input.useLines { it.toList() }
val matrix = sample.map { it.toCharArray() }.toTypedArray()
var count = 0
matrix.mapIndexed { y, row ->
row.mapIndexed { x, _ ->
if (isVisible(x, y, matrix)) {
count++
}
scoreTree(x, y, matrix)
}
}
println("Part 1 Answer: $count")
println("Part 2 Answer: $maxScore")
}
private fun scoreTree(x: Int, y: Int, matrix: Array<CharArray>) : Int {
if (x == 0 || x == matrix.size -1 || y == 0 || y == matrix.size -1) {
return 0
}
val a = matrix[y][x].digitToInt()
val right = matrix[y].takeWhile { it.digitToInt() < a }.count()
val left = matrix[y].reversed().takeWhile { it.digitToInt() < a }.count()
val down = matrix.takeWhile { it[x].digitToInt() < a }.count()
val up = matrix.reversed().takeWhile { it[x].digitToInt() < a }.count()
val score = up * down * left * right
if (score > maxScore) {
maxScore = score
}
return score
}
private fun isVisible(x: Int, y: Int, matrix: Array<CharArray>) : Boolean {
if (x == 0 || x == matrix.size -1 || y == 0 || y == matrix.size -1) {
return true
}
val a = matrix[y][x].digitToInt()
val right = matrix[y].takeWhile { it.digitToInt() < a }.count()
val left = matrix[y].reversed().takeWhile { it.digitToInt() < a }.count()
val down = matrix.takeWhile { it[x].digitToInt() < a }.count()
val up = matrix.reversed().takeWhile { it[x].digitToInt() < a }.count()
return right == 0 || left == 0 || down == 0 || up == 0
}
} | [
{
"class_path": "bsautner__Advent-of-Code-2022__5f53cb1/AOC8.class",
"javap": "Compiled from \"AOC8.kt\"\npublic final class AOC8 {\n private int maxScore;\n\n public AOC8();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ret... |
XinyueZ__lambda-world__3ec03f2/foreach/src/main0.kt | import java.util.stream.Collectors
import java.util.stream.IntStream
import java.util.stream.Stream
fun main(args: Array<String>) {
println("Examples foreach, list, array, collection ....")
println()
val list1 = listOf("one", "two", "three")
foreachList(list1)
val list2 = list1 + listOf("four", "five", "six")
streamForeachList(list2)
translateNumbers(list2)
sum(list2)
sumParallel(list2)
sumAdvanced(list2)
evenOdd(list2)
simulateForeach(list2) {
println(it)
}
}
fun foreachList(vals: List<String>) {
println("[foreach] on list")
vals.forEach { println(it) }
}
fun streamForeachList(vals: List<String>) {
println("[stream.foreach] on list")
vals.stream().forEach { println(it) }
}
fun simulateForeach(vals: List<String>, body: (String) -> Unit) {
println("Foreach simulated by inline fun")
for (s in vals) {
body(s)
}
}
fun translateNumbers(vals: List<String>) {
println("[stream.mapToInt.foreach] on list")
vals.stream().mapToInt {
when (it) {
"one" -> 1
"two" -> 2
"three" -> 3
"four" -> 4
"five" -> 5
"six" -> 6
else -> -1
}
}.forEach { println(it) }
}
fun sum(vals: List<String>) {
println("[stream.mapToInt.sum] on list")
vals.stream().filter({
if (vals.indexOf(it) == vals.size - 1) print(it + " = ") else print(it + " + ")
true
}).mapToInt {
when (it) {
"one" -> 1
"two" -> 2
"three" -> 3
"four" -> 4
"five" -> 5
"six" -> 6
else -> -1
}
}.sum().let { println(it) }
}
fun sumParallel(vals: List<String>) {
println("[stream.mapToInt.parallel.sum] on list")
vals.stream().parallel().filter({
if (vals.indexOf(it) == vals.size - 1) print(it + " = ") else print(it + " + ")
true
}).mapToInt {
when (it) {
"one" -> 1
"two" -> 2
"three" -> 3
"four" -> 4
"five" -> 5
"six" -> 6
else -> -1
}
}.sum().let { println(it) }
}
fun sumAdvanced(vals: List<String>) {
println("[stream + stream] on list")
vals.stream().flatMapToInt {
Stream.of(
when (it) {
"one" -> Pair(1, 1)//index or position, value
"two" -> Pair(2, 2)
"three" -> Pair(3, 3)
"four" -> Pair(4, 4)
"five" -> Pair(5, 5)
"six" -> Pair(6, 7)
else -> null
}
).filter {
if (it!!.first == vals.size) print(it.first.toString() + " = ") else print(it.first.toString() + " + ")
true
}.flatMapToInt { IntStream.of(it!!.second) }
}.sum().let { println(it) }
}
fun evenOdd(vals: List<String>) {
println("[stream + collect + partitioningBy] on list")
val collect = vals.stream().collect(Collectors.partitioningBy({
val num = when (it) {
"one" -> 1
"two" -> 2
"three" -> 3
"four" -> 4
"five" -> 5
"six" -> 6
else -> -1
}
num.rem(2) == 0
}))
println("even:")
println(collect[true])
println("odd:")
println(collect[false])
} | [
{
"class_path": "XinyueZ__lambda-world__3ec03f2/Main0Kt.class",
"javap": "Compiled from \"main0.kt\"\npublic final class Main0Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic #15 ... |
SebastianAigner__aoc-2022-kotlin__2b50330/src/Day01.kt | import java.io.File
import java.util.PriorityQueue
fun main() {
fun parseInput(input: String) = input.split("\n\n").map { elf ->
elf.lines().map { it.toInt() }
}
// O(size * log size) -> O(size * log n) -> O(size)
fun List<List<Int>>.topNElves(n: Int): Int {
fun findTopN(n: Int, element: List<Int>): List<Int> {
if (element.size == n) return element
val x = element.random()
val small = element.filter { it < x }
val equal = element.filter { it == x }
val big = element.filter { it > x }
if (big.size >= n) return findTopN(n, big)
if (equal.size + big.size >= n) return (equal + big).takeLast(n)
return findTopN(n - equal.size - big.size, small) + equal + big
}
return findTopN(n, this.map { it.sum() }).sum()
}
fun part1(input: String): Int {
val data = parseInput(input)
return data.topNElves(1)
}
fun part2(input: String) : Int {
val data = parseInput(input)
return data.topNElves(3)
}
// test if implementation meets criteria from the description, like:
val testInput = File("src/Day01_test.txt").readText()
check(part1(testInput) == 24000)
val input = File("src/Day01.txt").readText()
println(part1(input))
println(part2(input))
// val input = readInput("Day01")
// println(part1(input))
// println(part2(input))
}
| [
{
"class_path": "SebastianAigner__aoc-2022-kotlin__2b50330/Day01Kt.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
hannotify__advent-of-code__ccde130/src/main/kotlin/codes/hanno/adventofcode/day3/Day3Runner.kt | import java.io.File
import java.nio.file.Path
fun main(args: Array<String>) {
Day3Runner().run(Path.of("src/main/resources/day3/input.txt"))
}
class Day3Runner {
fun run(input: Path) {
File(input.toString()).useLines { lines ->
val groups = mutableListOf<Group>()
val rucksacks = mutableListOf<Rucksack>()
lines.forEachIndexed { index, line ->
rucksacks.add(Rucksack(line))
if ((index + 1) % 3 == 0) {
groups.add(Group(rucksacks.toList()))
rucksacks.clear()
}
}
val sumOfProrities = groups.map {
it.determineBadgeItem().priority()
}.toList().sum()
println(sumOfProrities)
}
}
data class Group(val rucksacks: List<Rucksack>) {
fun determineBadgeItem(): Item {
val itemsRucksack1 = rucksacks.get(0).getAllItems()
val itemsRucksack2 = rucksacks.get(1).getAllItems()
val itemsRucksack3 = rucksacks.get(2).getAllItems()
return itemsRucksack1.intersect(itemsRucksack2).intersect(itemsRucksack3).first()
}
}
class Rucksack(input: String) {
val firstCompartment: MutableList<Item> = mutableListOf()
val secondCompartment: MutableList<Item> = mutableListOf()
init {
val indexHalf = (input.length / 2 - 1)
for (firstHalfChar in input.substring(IntRange(0, indexHalf)).toList())
firstCompartment.add(Item(firstHalfChar))
for (secondHalfChar in input.substring(IntRange(indexHalf + 1, input.length - 1)).toList())
secondCompartment.add(Item(secondHalfChar))
assert(firstCompartment.size == secondCompartment.size)
}
fun determineDuplicateItem(): Item {
return firstCompartment.intersect(secondCompartment).first()
}
fun getAllItems(): Set<Item> {
return firstCompartment.union(secondCompartment)
}
}
data class Item(val value: Char) {
fun priority(): Int = if (value.isUpperCase()) value.code - 38 else value.code - 96
}
}
| [
{
"class_path": "hannotify__advent-of-code__ccde130/Day3Runner$Group.class",
"javap": "Compiled from \"Day3Runner.kt\"\npublic final class Day3Runner$Group {\n private final java.util.List<Day3Runner$Rucksack> rucksacks;\n\n public Day3Runner$Group(java.util.List<Day3Runner$Rucksack>);\n Code:\n ... |
hannotify__advent-of-code__ccde130/src/main/kotlin/codes/hanno/adventofcode/day2/Day2.kt | import Day2.Choice.ChoiceCategory.*
import Day2.Outcome.WDL.*
import java.nio.file.Files
import java.nio.file.Path
fun main(args: Array<String>) {
Day2().run(Path.of("src/main/resources/day2/input.txt"))
}
class Day2 {
fun run(input: Path) {
val scores = Files.lines(input).map {
val split = it.split(" ")
return@map Turn(Choice.valueOf(split[0]), Outcome.valueOf(split[1])).ourScore()
}.toList();
println(scores.sum())
}
data class Turn(val theirChoice: Choice, val outcome: Outcome) {
fun ourScore(): Int = outcome.score() + theirChoice.determineOurChoice(outcome).choiceCategory.score()
}
enum class Choice(val choiceCategory: ChoiceCategory) {
A(ROCK),
B(PAPER),
C(SCISSORS);
fun determineOurChoice(outcome: Outcome): Choice = when (outcome.wdl) {
WIN -> when (this.choiceCategory) {
ROCK -> B
PAPER -> C
SCISSORS -> A
}
DRAW -> this
LOSE -> when (this.choiceCategory) {
ROCK -> C
PAPER -> A
SCISSORS -> B
}
}
enum class ChoiceCategory {
ROCK, PAPER, SCISSORS;
fun score(): Int = when (this) {
ROCK -> 1
PAPER -> 2
SCISSORS -> 3
}
}
}
enum class Outcome(val wdl: WDL) {
X(LOSE),
Y(DRAW),
Z(WIN);
fun score(): Int = when(this.wdl) {
LOSE -> 0
DRAW -> 3
WIN -> 6
}
enum class WDL {
WIN, DRAW, LOSE
}
}
}
| [
{
"class_path": "hannotify__advent-of-code__ccde130/Day2$Choice$WhenMappings.class",
"javap": "Compiled from \"Day2.kt\"\npublic final class Day2$Choice$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n public static final int[] $EnumSwitchMapping$1;\n\n static {};\n Code:\n 0... |
gouthamhusky__leetcode-journey__a0e158c/neetcode/src/main/java/org/twopointers/TwoPointers.kt | import kotlin.math.max
import kotlin.math.min
fun main() {
trap(intArrayOf(0,1,0,2,1,0,1,3,2,1,2,1))
}
fun isPalindrome(s: String): Boolean {
val stringBuilder = StringBuilder()
for (c in s){
if (!c.isLetterOrDigit())
continue
else if (c.isUpperCase())
stringBuilder.append(c.lowercaseChar())
else
stringBuilder.append(c)
}
var start = 0
var end = stringBuilder.length - 1
while (start < end){
if (stringBuilder[start] != stringBuilder[end])
return false
start++
end--
}
return true
}
fun twoSum(numbers: IntArray, target: Int): IntArray {
var start = 0
var end = numbers.size - 1
while ( start < end){
val currentElement = numbers[start] + numbers[end]
if (currentElement == target)
return intArrayOf(start + 1 , end + 1)
else if (currentElement > target)
end--
else start++
}
return intArrayOf()
}
fun threeSum(nums: IntArray): List<List<Int>> {
nums.sort()
val ans = mutableListOf<List<Int>>()
for (i in nums.indices){
val current = nums[i]
if (i > 0 && current == nums[i-1])
continue
var l = i +1
var r = nums.size - 1
while (l < r){
when{
nums[i] + nums[l] + nums[r] == 0 -> {
ans.add(mutableListOf(i, l, r))
l++
while (nums[l] == nums[l+1] && l < r)
l++
}
nums[i] + nums[l] + nums[r] < 0 -> {
l++
}
else -> r--
}
}
}
return ans
}
fun maxArea(height: IntArray): Int {
var max = Int.MIN_VALUE
var l = 0
var r = height.size - 1
while (l < r){
val area = minOf(height[l], height[r]) * (r - l)
max = maxOf(max, area)
if (height[l] < height[r]) l++ else r--
}
return max
}
fun trap(height: IntArray): Int {
val maxLeft = IntArray(height.size)
val maxRight = IntArray(height.size)
val ans = IntArray(height.size)
for (i in height.indices){
if (i == 0)
maxLeft[i] = 0
else maxLeft[i] = maxOf(maxLeft[i-1], height[i-1])
}
for (i in height.size -1 downTo 0){
if (i == height.size-1)
maxRight[i] = 0
else maxRight[i] = maxOf(maxRight[i+1], height[i+1])
}
for (i in height.indices){
val storage = minOf(maxRight[i], maxLeft[i]) - height[i]
if (storage > 0)
ans[i] = storage
}
return ans.sum()
}
fun maxProfit(prices: IntArray): Int {
var left = 0
var right = 1
var max = Int.MIN_VALUE
while (left < prices.size - 1){
if (prices[right] - prices[right] <= 0){
left = right
right++
}
else {
val sp = prices[right] - prices[left]
max = maxOf(max, sp)
right++
}
}
return max
} | [
{
"class_path": "gouthamhusky__leetcode-journey__a0e158c/TwoPointersKt.class",
"javap": "Compiled from \"TwoPointers.kt\"\npublic final class TwoPointersKt {\n public static final void main();\n Code:\n 0: bipush 12\n 2: newarray int\n 4: astore_0\n 5: aload_0\n ... |
codermrhasan__ctci-problems-and-solutions__3f40e94/chapter_1_arrays_and_strings/1_is_unique/solution.kt | /* PROBLEM
Implement an algorithm to determine if a string has all unique characters.
What if you can not use additional data structures? */
/* ALGORITHM 1 - areCharsUnique
Keep and array of 256 elements, corresponding to each ASCII character, initially set to
false. For each letter in the original string I set the corresponding element of the
array to true. If the string contains only unique characters, I must never find an element
in the control array already set tu true (this would mean that the letter has already been
found before).
Performance: O(n)
ALGORITHM 2 - areCharsUniqueSort
Not optimal.
First I sort the characters of the string in ascending order, then I scan the
sorted string and check that there must not be 2 equal consecutive characters.
Performance: O(n*logn)
ALGORITHM 3 - areCharsUniqueDoubleLoop
Not optimal.
Compare each character of the string with all subsequent characters.
Performance: O(n^2) */
val letters = Array(256) {false}
fun main() {
val myString = "claudiosn"
println("Characters are unique? -> ${areCharsUnique(myString)}")
println("Characters are unique? -> ${areCharsUniqueSort(myString)}")
println("Characters are unique? -> ${areCharsUniqueDoubleLoop(myString)}")
}
fun areCharsUnique(myString: String): Boolean {
for(character in myString) {
if(!letters[character.toInt()]) {
letters[character.toInt()] = true
} else {
return false
}
}
return true
}
fun areCharsUniqueSort(myString: String): Boolean {
if(myString.length < 2) return true
val arr = myString.toCharArray()
val myStringSorted = arr.sorted().joinToString("")
for(i in 0..myStringSorted.length - 2) {
if(myStringSorted[i] == myStringSorted[i+1]) return false
}
return true
}
fun areCharsUniqueDoubleLoop(myString: String): Boolean {
if(myString.length < 2) return true
for(i in 0..myString.length-2) {
for(j in i+1..myString.length-1) {
if(myString[i] == myString[j]) return false
}
}
return true
} | [
{
"class_path": "codermrhasan__ctci-problems-and-solutions__3f40e94/SolutionKt.class",
"javap": "Compiled from \"solution.kt\"\npublic final class SolutionKt {\n private static final java.lang.Boolean[] letters;\n\n public static final java.lang.Boolean[] getLetters();\n Code:\n 0: getstatic ... |
magrathealabs__university__c6f2844/dojos/music-theory/kotlin/Main.kt | data class Note(val name: String)
{
fun flatten() = Note(name[0].toString() + 'b')
}
val Notes by lazy {
listOf("C", "C#", "D", "D#", "E", "F",
"F#", "G", "G#", "A", "A#", "B")
.map { Note(it) }
}
enum class Interval(val value: Int) {
Half(1),
Whole(2),
WholeAndHalf(3);
operator fun times(multiplier: Int) =
Array(multiplier) { this }
}
infix fun Note.hasSameLetterOf(note: Note) =
this.name.startsWith(note.name[0])
/**
* Changes note names to avoid repeated letters (e.g. "F" followed by "F#").
*/
fun uniqueNotes(notes: List<Note>): List<Note>
{
val newNotes = notes.toMutableList()
return notes.foldIndexed(newNotes) { i, acc, note ->
val cycle = CyclicIterator(acc).apply { next(i) }
val chromaticCycle = CyclicIterator(Notes)
if (cycle.prev() hasSameLetterOf note)
acc.apply {
set(i, chromaticCycle.next(Notes.indexOf(note) + 1).flatten())
}
else
acc
}
}
open class Scale(val root: Note, vararg val intervals: Interval)
{
fun notes(): List<Note> {
val iterator = CyclicIterator(Notes)
iterator.next(Notes.indexOf(root))
val notes = intervals.dropLast(1).fold(mutableListOf(root)) {
acc, interval -> acc.apply { add(iterator.next(interval.value)) }
}
return uniqueNotes(notes)
}
}
object Scales
{
class Major(root: Note)
: Scale(root, Interval.Whole,
Interval.Whole,
Interval.Half,
Interval.Whole,
Interval.Whole,
Interval.Whole,
Interval.Half)
class Minor(root: Note)
: Scale(root, Interval.Whole,
Interval.Half,
Interval.Whole,
Interval.Whole,
Interval.Half,
Interval.Whole,
Interval.Whole)
}
open class Chord(val root: Note, val intervals: List<Array<Interval>>)
{
fun notes(): List<Note> {
val cyclicIterator = CyclicIterator(Notes).apply { next(Notes.indexOf(root)) }
return intervals.fold(mutableListOf<Note>()) {
acc, intervals -> acc.apply {
add(cyclicIterator.next(intervals.halfStepsCount))
}
}.apply { add(0, root) }
}
private val Array<Interval>.halfStepsCount get() =
fold(0) { sum, interval -> sum + interval.value }
}
object Chords
{
class MajorTriad(root: Note)
: Chord(root, listOf(Interval.Whole * 2,
Interval.Half * 3))
}
class CyclicIterator<T>(val list: List<T>)
{
private var position = 0
val current get() = list[position]
fun next(n: Int = 1) =
if (list.size == 0) {
list[0]
} else if (list.size > position + n) {
position += n
list[position]
} else {
position = position + n - list.size
list[position]
}
fun prev(n: Int = 1) =
if (position - n < 0) {
position = list.size - n
list[position]
} else {
position = position - n
list[position]
}
}
fun <T> assertEquals(a: T, b: T) {
try {
assert(a == b)
} catch (e: AssertionError) {
println("Expected: $a")
println("Received: $b")
throw e
}
}
fun main() {
assertEquals(
listOf("Db", "Eb", "F", "Gb", "Ab", "Bb", "C"),
Scales.Major(root = Note("C#")).notes().map { it.name }
)
assertEquals(
listOf("B", "C#", "D#", "E", "F#", "G#", "A#"),
Scales.Major(root = Note("B")).notes().map { it.name }
)
assertEquals(
listOf("Bb", "C", "D", "Eb", "F", "G", "A"),
Scales.Major(root = Note("A#")).notes().map { it.name }
)
assertEquals(
listOf("Gb", "Ab", "Bb", "Cb", "Db", "Eb", "F"),
Scales.Major(root = Note("F#")).notes().map { it.name }
)
assertEquals(
listOf("C", "D", "Eb", "F", "G", "Ab", "Bb"),
Scales.Minor(root = Note("C")).notes().map { it.name }
)
assertEquals(
listOf("C", "E", "G"),
Chords.MajorTriad(root = Note("C")).notes().map { it.name }
)
assertEquals(
listOf("D", "F#", "A"),
Chords.MajorTriad(root = Note("D")).notes().map { it.name }
)
println("All tests passed!")
}
| [
{
"class_path": "magrathealabs__university__c6f2844/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n private static final kotlin.Lazy Notes$delegate;\n\n public static final java.util.List<Note> getNotes();\n Code:\n 0: getstatic #12 // Field N... |
Edsonctm__LeetCodeKotlin__5e9ae01/_14_Longest_Common_Prefix/src/main/kotlin/LongestCommonPrefix.kt | fun main() {
val strs = arrayOf("flower","flow","flight")
val strs2 = arrayOf("dog","racecar","car")
val strs3 = arrayOf("a")
val strs4 = arrayOf("reflower","flow","flight")
val strs5 = arrayOf("aaa","aa","aaa")
longestCommonPrefix(strs)
longestCommonPrefix(strs2)
longestCommonPrefix(strs3)
longestCommonPrefix(strs4)
longestCommonPrefix(strs5)
}
fun longestCommonPrefix(strs: Array<String>): String {
var menorPalavra = strs[0]
var resposta = ""
var index = 0
var contador = menorPalavra.length
if(strs.isEmpty()) return ""
if(strs.size == 1) return strs[0]
strs.forEach {
if(it == "") return ""
if(it.length < menorPalavra.length){
menorPalavra = it
}
}
val strsFiltrado = strs.filter { it != menorPalavra }
strsFiltrado.forEach{
var i = 0
while (i < it.length && contador > 0)
if (index < menorPalavra.length && it[index] == menorPalavra[index]){
index++
i++
} else if (index < contador) {
contador = index
i = it.length
index = 0
} else {
i = it.length
index = 0
}
}
resposta = menorPalavra.substring(0, contador)
return resposta
} | [
{
"class_path": "Edsonctm__LeetCodeKotlin__5e9ae01/LongestCommonPrefixKt.class",
"javap": "Compiled from \"LongestCommonPrefix.kt\"\npublic final class LongestCommonPrefixKt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: anewarray #8 // class java/lang/S... |
kevinrobayna__adventofcode_2020__8b1a84d/src/main/kotlin/day1.kt | import java.util.stream.Collectors
// https://adventofcode.com/2020/day/1
class Day1(
private val values: List<Int>
) {
fun solve(): Pair<Int, Int> {
val pairs: MutableList<Pair<Int, Int>> = mutableListOf()
for (outLoop in values.indices) {
for (innerLoop in values.indices) {
if (!outLoop.equals(innerLoop)) {
val first = Math.max(values[outLoop], values[innerLoop])
val second = Math.min(values[outLoop], values[innerLoop])
pairs.add(Pair(first, second))
}
}
}
return pairs
.filter { it.first + it.second == 2020 }
.distinct()
.get(0)
}
}
// https://adventofcode.com/2020/day/1
class Day1Part2(
private val values: List<Int>
) {
fun solve(): Triple<Int, Int, Int> {
val tuples: MutableList<Triple<Int, Int, Int>> = mutableListOf()
for (outLoop in values) {
for (innerLoop in values) {
for (innerInnerLoop in values) {
val points = listOf(outLoop, innerLoop, innerInnerLoop).sorted()
tuples.add(Triple(points[0], points[1], points[2]))
}
}
}
return tuples
.filter { it.first.plus(it.second).plus(it.third) == 2020 }
.distinct()
.get(0)
}
}
fun main() {
val problem = Day1::class.java.getResource("day1.txt")
.readText()
.split('\n')
.stream()
.map { it.toInt() }
.collect(Collectors.toList())
val pair = Day1(problem).solve()
println("solution = $pair, x*y = ${pair.first * pair.second}")
val triple = Day1Part2(problem).solve()
println("solution = $triple, x*y*z = ${triple.first * triple.second * triple.third}")
} | [
{
"class_path": "kevinrobayna__adventofcode_2020__8b1a84d/Day1.class",
"javap": "Compiled from \"day1.kt\"\npublic final class Day1 {\n private final java.util.List<java.lang.Integer> values;\n\n public Day1(java.util.List<java.lang.Integer>);\n Code:\n 0: aload_1\n 1: ldc #10 ... |
Walop__AdventOfCode2022__7a13f65/src/main/kotlin/Day15.kt | import java.io.InputStream
import kotlin.math.absoluteValue
data class Sensor(val pos: Vec2, val range: Int)
class Day15 {
companion object {
private fun readSensors(input: InputStream?): Pair<List<Sensor>, Set<Vec2>> {
if (input == null) {
throw Exception("Input missing")
}
val numRegex = "[\\d\\-]+".toRegex()
val coords = input.bufferedReader().useLines { lines ->
lines.flatMap {
numRegex.findAll(it).map { res -> res.value.toInt() }
}.toList()
}
val filled = coords.chunked(2).map { Vec2(it[0], it[1]) }.toSet()
val sensors = coords.chunked(4)
.map { Sensor(Vec2(it[0], it[1]), (it[0] - it[2]).absoluteValue + (it[1] - it[3]).absoluteValue) }
return Pair(sensors, filled)
}
fun process(input: InputStream?, rowNum: Int): Long {
val (sensors, filled) = readSensors(input)
//sensors.forEach { println(it) }
//filled.forEach { println(it) }
val leftSensor = sensors.minBy { it.pos.x - it.range }
val rightSensor = sensors.maxBy { it.pos.x + it.range }
val minX = leftSensor.pos.x - leftSensor.range
val maxX = rightSensor.pos.x + rightSensor.range
println("$minX-$maxX: ${(minX - maxX).absoluteValue}")
// val map = mutableListOf<Char>()
val sum = (minX..maxX)
.toList()
.parallelStream()
.map { x ->
val inRange = sensors.any { sensor ->
(sensor.pos.x - x).absoluteValue + (sensor.pos.y - rowNum).absoluteValue <= sensor.range
}
if (!inRange) {
// map.add('.')
0
} else {
if (filled.contains(Vec2(x, rowNum))) {
// map.add('.')
0
} else {
// map.add('#')
1
}
}
}.filter { it != 0 }.count()
// map.add('.')
//println(map.joinToString("").trim('.').count { it == '.' })
//File("C:\\Temp\\map_15.txt").writeText(map.joinToString(""))
return sum
}
fun process2(input: InputStream?): Long {
val (sensors, filled) = readSensors(input)
var maxX = sensors.maxOf { it.pos.x }
var current = Vec2(0, 0)
var covering: Sensor? = null
while (true) {
covering = sensors.firstOrNull { sensor ->
sensor != covering &&
(sensor.pos.x - current.x).absoluteValue + (sensor.pos.y - current.y).absoluteValue <= sensor.range
}
if (covering == null) {
break
}
val newPos = ((covering.pos.x + covering.range) - (covering.pos.y - current.y).absoluteValue) + 1
if (newPos < maxX) {
current.x = newPos
} else {
current.x = 0
current.y++
}
}
// println(current)
return 4_000_000L * current.x.toLong() + current.y.toLong()
}
}
}
| [
{
"class_path": "Walop__AdventOfCode2022__7a13f65/Day15.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15 {\n public static final Day15$Companion Companion;\n\n public Day15();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<ini... |
Walop__AdventOfCode2022__7a13f65/src/main/kotlin/Day12.kt | import java.io.InputStream
data class HeightMap(val start: List<Int>, val end: Int, val width: Int, val graph: List<List<Boolean>>)
class Day12 {
companion object {
private fun readMap(input: InputStream?, startTile: Char, endTile: Char): HeightMap {
if (input == null) {
throw Exception("Input missing")
}
var start = mutableListOf<Int>()
var end = 0
var width = 0
val map = input.bufferedReader().readLines().flatMapIndexed { i, row ->
width = row.length
row.mapIndexed { j, tile ->
if (tile == startTile) {
start.add(i * width + j)
}
if (tile == endTile) {
end = i * width + j
}
when (tile) {
'S' -> {
'a'
}
'E' -> {
'z'
}
else -> {
tile
}
}
}
}
val graph = MutableList(map.size) { MutableList(map.size) { false } }
map.forEachIndexed { i, tile ->
if (i % width + 1 < width) {
if (tile.code >= map[i + 1].code - 1) {
graph[i][i + 1] = true
}
if (tile.code <= map[i + 1].code + 1) {
graph[i + 1][i] = true
}
}
if (i + width < map.size) {
if (tile.code >= map[i + width].code - 1) {
graph[i][i + width] = true
}
if (tile.code <= map[i + width].code + 1) {
graph[i + width][i] = true
}
}
}
return HeightMap(start, end, width, graph)
}
private fun findPath(graph: List<List<Boolean>>, width: Int, start: Int, end: Int): Int {
val numOfVertices = graph.size
val visitedAndDistance = List(numOfVertices) { mutableListOf(0, Int.MAX_VALUE) }
visitedAndDistance[start][1] = 0
fun nextToVisit(): Int {
var v = -1
for (i in 0 until numOfVertices) {
if (visitedAndDistance[i][0] == 0 && (v < 0 || visitedAndDistance[i][1] <= visitedAndDistance[v][1])) {
v = i
}
}
return v
}
repeat(numOfVertices) {
val toVisit = nextToVisit()
for (i in listOf(toVisit - 1, toVisit + 1, toVisit + width, toVisit - width)) {
if (i in 0 until numOfVertices && graph[toVisit][i] && visitedAndDistance[i][0] == 0) {
val newDistance = visitedAndDistance[toVisit][1] + 1
if (visitedAndDistance[i][1] > newDistance) {
visitedAndDistance[i][1] = newDistance
if (i == end) {
return newDistance
}
}
}
visitedAndDistance[toVisit][0] = 1
}
}
return -1
}
fun process(input: InputStream?): Int {
val heightMap = readMap(input, 'S', 'E')
//heightMap.graph.forEach { println(it) }
return findPath(heightMap.graph, heightMap.width, heightMap.start[0], heightMap.end)
}
fun process2(input: InputStream?): Int {
val heightMap = readMap(input, 'a', 'E')
var i = 0
val lengths = heightMap.start.parallelStream().map {
findPath(heightMap.graph, heightMap.width, it, heightMap.end)
}.map {
i++
println("$i of ${heightMap.start.size} Done: $it")
it
}
.filter { it > 0 }
return lengths.min(Integer::compare).get()
}
}
}
| [
{
"class_path": "Walop__AdventOfCode2022__7a13f65/Day12$Companion.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class Day12$Companion {\n private Day12$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: r... |
Walop__AdventOfCode2022__7a13f65/src/main/kotlin/Day11.kt | import java.io.InputStream
data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: Long,
val trueReceiver: Int,
val falseReceiver: Int,
var inspectionCount: Long = 0
)
class Day11 {
companion object {
private fun createOperation(operator: String, other: Long?): (Long) -> Long {
return when (operator) {
"+" -> { old: Long -> old + (other ?: old) }
else -> { old: Long -> old * (other ?: old) }
}
}
private fun privateProcess(input: InputStream?, rounds: Int, worryDivider: Long): Long {
if (input == null) {
throw Exception("Input missing")
}
val numRegex = "\\d+".toRegex()
val operatorRegex = "[+*]".toRegex()
val monkeys = input.bufferedReader().useLines { lines ->
lines.chunked(7)
.map { monkeyDesc ->
val items = numRegex.findAll(monkeyDesc[1]).map { it.value.toLong() }.toMutableList()
//println(monkeyDesc)
Monkey(
items,
createOperation(
operatorRegex.find(monkeyDesc[2])!!.value,
numRegex.find(monkeyDesc[2])?.value?.toLong()
),
numRegex.find(monkeyDesc[3])!!.value.toLong(),
numRegex.find(monkeyDesc[4])!!.value.toInt(),
numRegex.find(monkeyDesc[5])!!.value.toInt(),
)
}.toList()
}
val mod = monkeys.map { it.test }.fold(1L) { acc, it -> acc * it }
for (i in 1..rounds) {
for (monkey in monkeys) {
monkey.items.map {
monkey.operation(it) / worryDivider
}.forEach {
monkey.inspectionCount++
val reveiver =
if ((it) % monkey.test == 0L) monkey.trueReceiver else monkey.falseReceiver
val converted = it % mod
monkeys[reveiver].items.add(converted)
}
monkey.items.clear()
}
// if (i == 1 || i % 1000 == 0) {
// monkeys.forEachIndexed { index, it -> println("$index: ${it.items}, ${it.inspectionCount}") }
// println()
// }
}
return monkeys.sortedByDescending { it.inspectionCount }.take(2).map { it.inspectionCount }
.fold(1L) { acc, count -> acc * count }
}
fun process(input: InputStream?): Long {
return privateProcess(input, 20, 3L)
}
fun process2(input: InputStream?): Long {
return privateProcess(input, 10_000, 1L)
}
}
}
| [
{
"class_path": "Walop__AdventOfCode2022__7a13f65/Day11$Companion$privateProcess$$inlined$sortedByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class Day11$Companion$privateProcess$$inlined$sortedByDescending$1<T> implements java.util.Comparator {\n public Day11$Companion$pr... |
Walop__AdventOfCode2022__7a13f65/src/main/kotlin/Day9.kt | import java.io.InputStream
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt
data class Vec2(
var x: Int,
var y: Int
) {
operator fun plus(other: Vec2): Vec2 {
return Vec2(x + other.x, y + other.y)
}
operator fun minus(other: Vec2): Vec2 {
return Vec2(x - other.x, y - other.y)
}
fun toUnits(): Vec2 {
val uX = if (abs(x) > 1) x / 2 else x
val uY = if (abs(y) > 1) y / 2 else y
return Vec2(uX, uY)
}
fun length(): Float {
return sqrt(x.toFloat().pow(2) + y.toFloat().pow(2))
}
}
class Day9 {
companion object {
fun process(input: InputStream?): Int {
if (input == null) {
throw Exception("Input missing")
}
var head = Vec2(0, 0)
var prevHead = Vec2(0, 0)
var tail = Vec2(0, 0)
val visited = mutableSetOf(tail)
input.bufferedReader()
.useLines { lines ->
lines.map { it.split(" ") }
.map { Pair(it[0], it[1].toInt()) }
.forEach { c ->
//println("${head.x},${head.y}")
val dir = when (c.first) {
"U" -> Vec2(0, 1)
"D" -> Vec2(0, -1)
"L" -> Vec2(-1, 0)
else -> Vec2(1, 0)
}
repeat(c.second) {
head += dir
if ((head - tail).length() > 1.5) {
tail = prevHead
visited.add(tail)
}
prevHead = head
}
}
}
return visited.size
}
fun process2(input: InputStream?): Int {
if (input == null) {
throw Exception("Input missing")
}
val rope = Array(10) { Vec2(0, 0) }
val visited = mutableSetOf(rope[9])
input.bufferedReader()
.useLines { lines ->
lines.map { it.split(" ") }
.map { Pair(it[0], it[1].toInt()) }
.forEach { c ->
val dir = when (c.first) {
"U" -> Vec2(0, 1)
"D" -> Vec2(0, -1)
"L" -> Vec2(-1, 0)
else -> Vec2(1, 0)
}
repeat(c.second) {
rope[0] += dir
for (i in 1..9) {
val sectionVec = rope[i - 1] - rope[i]
if (sectionVec.length() > 1.5) {
rope[i] += sectionVec.toUnits()
}
}
visited.add(rope[9])
}
}
}
return visited.size
}
}
}
| [
{
"class_path": "Walop__AdventOfCode2022__7a13f65/Day9$Companion.class",
"javap": "Compiled from \"Day9.kt\"\npublic final class Day9$Companion {\n private Day9$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retur... |
Walop__AdventOfCode2022__7a13f65/src/main/kotlin/Day7.kt | import java.io.InputStream
interface IFile {
val name: String
val size: Int
}
data class File(override val name: String, override val size: Int) : IFile
data class Directory(
override val name: String,
override var size: Int,
val children: MutableList<IFile>,
val parent: Directory?,
) : IFile
class Day7 {
companion object {
private fun sumLessThan100k(dir: Directory): Int {
val returnSize = if (dir.size <= 100_000) dir.size else 0
val subDirs = dir.children.filterIsInstance<Directory>()
if (subDirs.isNotEmpty()) {
return returnSize + subDirs.sumOf { sumLessThan100k(it) }
}
return returnSize
}
private fun dirsMoreThan(dir: Directory, min: Int): List<Int> {
val returnList = if (dir.size >= min) listOf(dir.size) else listOf()
val subDirs = dir.children.filterIsInstance<Directory>()
if (subDirs.isNotEmpty()) {
return returnList + subDirs.flatMap { dirsMoreThan(it, min) }
}
return returnList
}
fun process(input: InputStream?): Int {
if (input == null) {
throw Exception("Input missing")
}
return input
.bufferedReader()
.useLines { lines ->
val root = Directory("/", 0, mutableListOf(), null)
var current = root
for (line in lines.drop(1)) {
when (line.take(4)) {
"$ cd" -> {
val dir = line.drop(5)
if (dir == "..") {
current.size = current.children.sumOf { it.size }
current = current.parent!!
} else {
current = current.children.find { it.name == line.drop(5) } as Directory
}
}
"$ ls" -> continue
"dir " -> current.children.add(Directory(line.drop(4), 0, mutableListOf(), current))
else -> {
val split = line.split(" ")
current.children.add(File(split[1], split[0].toInt()))
}
}
}
current.size = current.children.sumOf { it.size }
root.size = root.children.sumOf { it.size }
sumLessThan100k(root)
}
}
fun process2(input: InputStream?): Int {
if (input == null) {
throw Exception("Input missing")
}
return input
.bufferedReader()
.useLines { lines ->
val root = Directory("/", 0, mutableListOf(), null)
var current = root
for (line in lines.drop(1)) {
when (line.take(4)) {
"$ cd" -> {
val dir = line.drop(5)
if (dir == "..") {
current.size = current.children.sumOf { it.size }
current = current.parent!!
} else {
current = current.children.find { it.name == line.drop(5) } as Directory
}
}
"$ ls" -> continue
"dir " -> current.children.add(Directory(line.drop(4), 0, mutableListOf(), current))
else -> {
val split = line.split(" ")
current.children.add(File(split[1], split[0].toInt()))
}
}
}
while (current.parent != null) {
current.size = current.children.sumOf { it.size }
current = current.parent!!
}
root.size = root.children.sumOf { it.size }
val toFree = 70_000_000 - 30_000_000 - root.size
dirsMoreThan(root, -toFree).min()
}
}
}
}
| [
{
"class_path": "Walop__AdventOfCode2022__7a13f65/Day7.class",
"javap": "Compiled from \"Day7.kt\"\npublic final class Day7 {\n public static final Day7$Companion Companion;\n\n public Day7();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":... |
Walop__AdventOfCode2022__7a13f65/src/main/kotlin/Day8.kt | import java.io.InputStream
import kotlin.math.sqrt
class Day8 {
companion object {
private fun readTreeMap(input: InputStream?): String {
if (input == null) {
throw Exception("Input missing")
}
return input.reader().readLines().joinToString("")
}
fun process(input: InputStream?): Int {
val treeMap = readTreeMap(input)
val side = sqrt(treeMap.length.toDouble()).toInt()
return treeMap.mapIndexed { index, c ->
val x = index % side
val y = index / side
if (x == 0 || x + 1 == side || y == 0 || y + 1 == side) {
print(1)
1
} else {
if ((y * side until index).any { treeMap[it] >= c } &&
(index + 1 until (y + 1) * side).any { treeMap[it] >= c } &&
(x until index step side).any { treeMap[it] >= c } &&
((index + side)..treeMap.length step side).any { treeMap[it] >= c }) {
print(0)
0
} else {
print(1)
1
}
}
}
.sum()
}
private fun countVisibility(treeMap: String, start: Int, end: Int, step: Int, height: Char): Int {
var index = start + step
var sum = 0
if (step > 0) {
while (index < treeMap.length && index < end) {
sum++
if (treeMap[index] >= height) break
index += step
}
} else {
while (index >= 0 && index > end) {
sum++
if (treeMap[index] >= height) break
index += step
}
}
return sum
}
fun process2(input: InputStream?): Int {
val treeMap = readTreeMap(input)
val side = sqrt(treeMap.length.toDouble()).toInt()
return treeMap.mapIndexed { index, c -> Pair(index, c) }.filter { pair ->
val x = pair.first % side
val y = pair.first / side
if (x == 0 || x + 1 == side || y == 0 || y + 1 == side) {
true
} else {
!((y * side until pair.first).any { treeMap[it] >= pair.second } &&
(pair.first + 1 until (y + 1) * side).any { treeMap[it] >= pair.second } &&
(x until pair.first step side).any { treeMap[it] >= pair.second } &&
((pair.first + side)..treeMap.length step side).any { treeMap[it] >= pair.second })
}
}.maxOf { pair ->
val x = pair.first % side
val y = pair.first / side
if (x == 0 || x + 1 == side || y == 0 || y + 1 == side) {
0
} else {
val left = countVisibility(treeMap, pair.first, y * side - 1, -1, pair.second)
val right = countVisibility(treeMap, pair.first, (y + 1) * side, 1, pair.second)
val up = countVisibility(treeMap, pair.first, x - 1, -side, pair.second)
val down = countVisibility(treeMap, pair.first, treeMap.length, side, pair.second)
// val left = (pair.first - 1..y * side).takeWhile { treeMap[it] < pair.second }.count() + 1
// val right = (pair.first + 1 until (y + 1) * side).takeWhile { treeMap[it] < pair.second }
// .count() + 1
// val up = (pair.first - side..x step side).takeWhile { treeMap[it] < pair.second }.count() + 1
// val down = (pair.first + side..treeMap.length step side).takeWhile { treeMap[it] < pair.second }
// .count() + 1
println("${x},${y}: ${left * right * up * down}")
left * right * up * down
}
}
}
}
}
| [
{
"class_path": "Walop__AdventOfCode2022__7a13f65/Day8$Companion.class",
"javap": "Compiled from \"Day8.kt\"\npublic final class Day8$Companion {\n private Day8$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retur... |
nikitabobko__stalin-sort__6098af3/kotlin/StalinSort.kt | fun main(args: Array<String>) {
val intComrades = listOf(0, 2, 1, 4, 3, 6, 5).sortComrades()
val charComrades = listOf('A', 'C', 'B', 'E', 'D').sortComrades()
val redArmyRanks = listOf(
RedArmyRank.SOLDIER,
RedArmyRank.ASSISTANT_PLATOON_LEADER,
RedArmyRank.SQUAD_LEADER).sortComrades()
val dickwads = listOf(
RedArmyDickwad("Stalin", RedArmyRank.SUPREME_COMMANDER),
RedArmyDickwad("Pablo", RedArmyRank.NOT_EVEN_RUSSIAN),
RedArmyDickwad("Putin", RedArmyRank.BEAR_RIDER)).sortComrades()
println("$intComrades\n$charComrades\n$redArmyRanks\n$dickwads")
}
fun <T: Comparable<T>> Iterable<T>.sortComrades(): List<T> {
var max = firstOrNull() ?: return emptyList()
return mapIndexedNotNull { index, comrade ->
if (index == 0 || comrade >= max) {
max = comrade
comrade
} else {
null
}
}
}
enum class RedArmyRank {
NOT_EVEN_RUSSIAN,
SOLDIER,
SQUAD_LEADER,
ASSISTANT_PLATOON_LEADER,
COMPANY_SERGEANT,
BEAR_RIDER,
SUPREME_COMMANDER
}
data class RedArmyDickwad(
val name: String,
val rank: RedArmyRank
) : Comparable<RedArmyDickwad> {
override operator fun compareTo(other: RedArmyDickwad) = rank.compareTo(other.rank)
}
| [
{
"class_path": "nikitabobko__stalin-sort__6098af3/StalinSortKt.class",
"javap": "Compiled from \"StalinSort.kt\"\npublic final class StalinSortKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invo... |
somei-san__atcoder-kotline__43ea45f/src/main/Main.kt | import java.util.*
fun main(args: Array<String>) {
abc000X()
}
fun abc000X() {
System.err.println("!!!!!!!!!!!テスト!!!!!!!!!")
val N = readLine()!!
val As = readLine()!!.split(" ").map { it.toInt() }.sorted()
System.err.println(As)
val sets = mutableListOf<kakeru>()
for (k in 0 until As.count() - 2)
for (j in k + 1 until As.count() - 1)
for (i in j + 1 until As.count())
if (As[i] == As[j] * As[k])
sets.add(kakeru(As[i], As[j], As[k]))
sets.forEach { System.err.println(it) }
// System.err.println(Ws)
println(sets.count() * 2)
}
data class kakeru(val i: Int, val j: Int, val k: Int)
data class waru(val i: Int, val j: Int, val k: Int)
fun ng() {
println("No")
}
fun ok() {
println("Yes")
}
// 約数のList
fun divisor(value: Long): List<Long> {
val max = Math.sqrt(value.toDouble()).toLong()
return (1..max)
.filter { value % it == 0L }
.map { listOf(it, value / it) }
.flatten()
.sorted()
}
// 範囲内の素数を取得
// fromだけ指定すると戻り値の個数で素数判定ができる
fun prime(from: Long, to: Long = from): List<Long> {
return (from..to).filter { i ->
val max = Math.sqrt(i.toDouble()).toLong()
(2..max).all { j -> i % j != 0L }
}
}
// 渡された値が素数か判定
fun isPrime(source: Int): Boolean {
return prime(source.toLong()).any()
}
// 素因数分解
fun decom(value: Long): List<Long> {
if (value == 1L) return listOf(1)
val max = Math.sqrt(value.toDouble()).toLong()
return prime(2, max).filter { value % it == 0L }
}
// 最大公約数
fun gcd(a: Long, b: Long): Long {
return if (a % b == 0L) b else gcd(b, a % b)
}
// 文字列を入れ替え
fun swap(base: String, a: String, b: String): String {
return base.map {
when (it) {
a.toCharArray()[0] -> b
b.toCharArray()[0] -> a
else -> it.toString()
}
}.joinToString()
}
/**
* リストをスタックに変換する
* @param list リスト
* @return スタック
*/
fun listToStack(list: List<Int>): Stack<Int> {
// スタック
val stack = Stack<Int>()
for (e in list) {
stack.push(e)
}
return stack
}
/**
* ユークリッドの互除法を用いて、最大公約数を導出する
* @param list 最大公約数を求める対象となる数が格納されたリスト
* @return 最大公約数
*/
fun gcd(list: List<Int>): Int {
// 最大公約数を求める対象となる数が格納されたスタック
val stack = listToStack(list)
// ユークリッドの互除法を用いて、最大公約数を導出する
// (最終的にスタック内に1つだけ数が残り、それが最大公約数となる)
while (1 < stack.size) {
// スタックから2つの数をpop
val pops = (0 until 2).map {
stack.pop()
}
// スタックからpopした2つの数のうち、小さい方の数のインデックス
val minIndex = if (pops[1] < pops[0]) {
1
} else {
0
}
// スタックからpopした2つの数のうち、小さい方の数をpush
stack.push(pops[minIndex])
// スタックからpopした2つの数の剰余
val r = pops[(minIndex + 1) % 2] % pops[minIndex]
// スタックからpopした2つの数に剰余があるならば、それをpush
if (0 < r) {
stack.push(r)
}
}
// 最大公約数を返す
return stack.pop()
}
/**
* 最小公倍数を導出する
* @param list 最小公倍数を求める対象となる数が格納されたリスト
* @return 最小公倍数
*/
fun lcm(list: List<Int>): Int {
// 最大公約数を求める対象となる数が格納されたスタック
val stack = listToStack(list)
// 最小公倍数を導出する
// (最終的にスタック内に1つだけ数が残り、それが最小公倍数となる)
while (1 < stack.size) {
// スタックから2つの数をpop
val pops = (0 until 2).map {
stack.pop()
}
// スタックからpopした2つの数の最小公倍数をpush
stack.push(pops[0] * pops[1] / gcd(pops))
}
// 最小公倍数を返す
return stack.pop()
} | [
{
"class_path": "somei-san__atcoder-kotline__43ea45f/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic #15 ... |
piazentin__programming-challenges__db490b1/hacker-rank/sorting/MergeSortCountingInversions.kt | import java.lang.StringBuilder
private fun IntArray.toNiceString(): String {
val sb = StringBuilder().append("[")
this.forEach { sb.append(it).append(",") }
if (sb.length > 1) sb.deleteCharAt(sb.lastIndex).append("]")
return sb.toString()
}
private val IntRange.size: Int
get() = this.last - this.first
private val IntRange.half: Int
get() = this.first + (this.size / 2)
fun main() {
val queries = readLine().orEmpty().trim().toInt()
val arrays = Array(queries) {
readLine() // ignore first line
readLine().orEmpty().trim().split(" ").map { l -> l.toInt() }.toIntArray()
}
arrays.forEach {
println(countSwaps(it))
}
}
fun countSwaps(array: IntArray): Long {
return sort(array, 0 .. array.size, IntArray(array.size))
}
fun sort(array: IntArray, range: IntRange, temp: IntArray): Long {
if (range.size <= 1) return 0
val leftHalf = range.first .. range.half
val rightHalf = range.half .. range.last
return sort(array, leftHalf, temp) + sort(array, rightHalf, temp) + merge(array, leftHalf, rightHalf, temp)
}
fun merge(array: IntArray, leftHalf: IntRange, rightHalf: IntRange, temp: IntArray): Long {
var left = leftHalf.first
var right = rightHalf.first
var index = left
var swaps = 0L
while (left < leftHalf.last && right < rightHalf.last) {
if (array[left] <= array[right]) temp[index] = array[left++]
else {
swaps += right - index
temp[index] = array[right++]
}
index++
}
while (left < leftHalf.last) temp[index++] = array[left++]
while (right < rightHalf.last) temp[index++] = array[right++]
for (i in leftHalf.first until rightHalf.last) array[i] = temp[i]
return swaps
}
| [
{
"class_path": "piazentin__programming-challenges__db490b1/MergeSortCountingInversionsKt.class",
"javap": "Compiled from \"MergeSortCountingInversions.kt\"\npublic final class MergeSortCountingInversionsKt {\n private static final java.lang.String toNiceString(int[]);\n Code:\n 0: new #... |
piazentin__programming-challenges__db490b1/hacker-rank/strings/SpecialPalindromeAgain.kt |
fun main() {
readLine() // ignore first input
val str = readLine().orEmpty()
var count = 0L
val freqTable = buildFreqTable(str)
// all singles
for (freq in freqTable) count += triangleNumber(freq.second)
// all "middle" cases
for (i in 0 until freqTable.size - 2) {
if (freqTable[i + 1].second == 1 && freqTable[i].first == freqTable[i + 2].first) {
count += Math.min(freqTable[i].second, freqTable[i + 2].second)
}
}
println(count)
}
private fun buildFreqTable(str: String): List<Pair<Char, Int>> {
if (str.length == 1) return listOf(Pair(str[0], 1))
val table = mutableListOf<Pair<Char, Int>>()
var lastChar = str[0]
var count = 1
for (i in 1 until str.length) {
if (str[i] == lastChar) count++
else {
table.add(Pair(lastChar, count))
lastChar = str[i]
count = 1
}
}
table.add(Pair(lastChar, count))
return table
}
private fun triangleNumber(n: Int) = (n * (n + 1L)) / 2L
| [
{
"class_path": "piazentin__programming-challenges__db490b1/SpecialPalindromeAgainKt.class",
"javap": "Compiled from \"SpecialPalindromeAgain.kt\"\npublic final class SpecialPalindromeAgainKt {\n public static final void main();\n Code:\n 0: invokestatic #12 // Method kotlin/io/Co... |
piazentin__programming-challenges__db490b1/hacker-rank/sorting/FraudulentActivityNotifications.kt | // https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem
fun main() {
val (_, days) = readLine().orEmpty().trim().split(" ").map(String::toInt)
val expenditures = readLine().orEmpty().trim().split(" ").map(String::toInt).toTypedArray()
fraudulentActivityNotifications(days, expenditures)
}
fun fraudulentActivityNotifications(days: Int, expenditures: Array<Int>) {
val countArray = IntArray(200)
var qty = 0
// initialize
for (i in 0 until days) {
countArray[expenditures[i]]++
}
for (i in days until expenditures.size) {
if (expenditures[i] >= median(days, countArray)) qty++
countArray[expenditures[i - days]]--
countArray[expenditures[i]]++
}
println(qty)
}
fun median(days: Int, countArray: IntArray): Int {
var count = 0
val even = days % 2 == 0
val medianIdx = days / 2
var foundFirst = false
var median = 0
for (countIdx in 0 until countArray.size) {
count += countArray[countIdx]
if (!even) {
if (count > medianIdx) {
median = countIdx * 2
break
}
} else {
if (countArray[countIdx] > 0 && count == medianIdx) {
median = countIdx
foundFirst = true
} else if (countArray[countIdx] > 0 && count > medianIdx) {
if (foundFirst) median += countIdx
else median = countIdx * 2
break
}
}
}
return median
}
| [
{
"class_path": "piazentin__programming-challenges__db490b1/FraudulentActivityNotificationsKt.class",
"javap": "Compiled from \"FraudulentActivityNotifications.kt\"\npublic final class FraudulentActivityNotificationsKt {\n public static final void main();\n Code:\n 0: nop\n 1: invokestatic ... |
piazentin__programming-challenges__db490b1/hacker-rank/strings/SherlockAndTheValidString.kt | // https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem
fun main() {
val string = readLine().orEmpty()
println(if (isValid(string)) "YES" else "NO")
}
fun isValid(string: String): Boolean {
if (string.length <= 3) return true
val charFreq = IntArray('z' - 'a' + 1)
for (char in string) charFreq[char - 'a']++
val metaFreq = mutableMapOf<Int, Int>()
for (frequency in charFreq) {
if (frequency != 0) metaFreq[frequency] = metaFreq.getOrDefault(frequency, 0) + 1
}
return when (metaFreq.keys.size) {
1 -> true
2 -> {
val (first, second) = metaFreq.keys.toList()
if ((first == 1 && metaFreq[first] == 1) || (second == 1 && metaFreq[second] == 1)) true
else Math.abs(first - second) == 1 && (metaFreq[first] == 1 || metaFreq[second] == 1)
}
else -> false
}
}
| [
{
"class_path": "piazentin__programming-challenges__db490b1/SherlockAndTheValidStringKt.class",
"javap": "Compiled from \"SherlockAndTheValidString.kt\"\npublic final class SherlockAndTheValidStringKt {\n public static final void main();\n Code:\n 0: invokestatic #12 // Method kot... |
linisme__LeetCodeInKotlin__4382afc/LongestPalindrome.kt | class LongestPalindromeSolution {
fun longestPalindrome(s: String): String {
var chars = s.toCharArray()
val sourceLength = s.length
var maxLength = 0
var maxLeft = 0
var maxRight = 0
for (l in 0 until sourceLength) {
if (maxLength > sourceLength - l) {
break
}
test@ for (r in sourceLength - 1 downTo l) {
val targetLength = r - l + 1
for (i in 0 until targetLength / 2) {
if (chars[l + i] != chars[r - i]) {
continue@test
}
}
if (maxLength < targetLength) {
maxLength = targetLength
maxLeft = l
maxRight = r
break
}
}
}
return s.substring(maxLeft, maxRight + 1)
}
fun isPalindrome(chars: CharArray, l : Int, r: Int): Boolean {
val length = r - l + 1
for (i in 0 until length / 2) {
if (chars[l + i] != chars[r - i]) {
return false
}
}
return true
}
}
fun main(args: Array<String>) {
println(LongestPalindromeSolution().longestPalindrome("abbccbbdl"))
}
| [
{
"class_path": "linisme__LeetCodeInKotlin__4382afc/LongestPalindromeKt.class",
"javap": "Compiled from \"LongestPalindrome.kt\"\npublic final class LongestPalindromeKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // Strin... |
linisme__LeetCodeInKotlin__4382afc/LengthOfLongestSubstring.kt | class LengthOfLongestSubstringSolution {
fun lengthOfLongestSubstring(s: String): Int {
var set = hashSetOf<Char>()
var maxLength = 0
val size = s.length
s.forEachIndexed { index, c ->
set.clear()
var pos = index + 1
set.add(c)
var next : Char? = if (pos < size) s.get(pos) else null
while (next != null) {
if (set.contains(next)) {
break
}
set.add(next)
pos++
next = if (pos < size) s.get(pos) else null
}
if (set.size > maxLength) {
maxLength = set.size
}
}
return maxLength
}
}
class LengthOfLongestSubstringSolution2 {
fun lengthOfLongestSubstring(s: String): Int {
var maxLength = 0
var hashMap = hashMapOf<Char, Int>()
var currentLength = 0
for (i in 0 until s.length) {
val c = s.get(i)
val preIndex = hashMap[c]
hashMap[c] = i
currentLength = if (preIndex == null || i - preIndex > currentLength) (currentLength + 1) else (i - preIndex)
if (currentLength > maxLength) {
maxLength = currentLength
}
}
return maxLength
}
}
fun main(args: Array<String>) {
println(LengthOfLongestSubstringSolution2().lengthOfLongestSubstring("abba"))
}
| [
{
"class_path": "linisme__LeetCodeInKotlin__4382afc/LengthOfLongestSubstringKt.class",
"javap": "Compiled from \"LengthOfLongestSubstring.kt\"\npublic final class LengthOfLongestSubstringKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
linisme__LeetCodeInKotlin__4382afc/FineMedianSortedArrays.kt | class FindMedianSortedArraysSolution {
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
var i1 = 0
var i2 = 0
var length1 = nums1.size
var length2 = nums2.size
var sortedSize = length1 + length2
var sortedArray = IntArray(sortedSize)
var k = 0
while (i1 < length1 || i2 < length2) {
var e1 = if (i1 < length1)nums1[i1] else null
var e2 = if (i2 < length2)nums2[i2] else null
if (e2 == null || (e1 != null && e1 < e2)) {
sortedArray[k] = e1!!
i1++
} else {
sortedArray[k] = e2
i2++
}
k++
}
if (sortedSize > 1 && sortedSize % 2 == 0) {
return (sortedArray[sortedSize / 2] + sortedArray[sortedSize / 2 - 1]) / 2.0
} else {
return sortedArray[sortedSize / 2].toDouble()
}
}
}
fun main(args: Array<String>) {
println(FindMedianSortedArraysSolution().findMedianSortedArrays(intArrayOf(), intArrayOf(2,3)))
}
| [
{
"class_path": "linisme__LeetCodeInKotlin__4382afc/FineMedianSortedArraysKt.class",
"javap": "Compiled from \"FineMedianSortedArrays.kt\"\npublic final class FineMedianSortedArraysKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
SelenaChen123__AdventOfCode2022__551af4f/src/Day04/Day04.kt | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
var duplicates = 0
for (line in input) {
val first = line.split(",")[0].split("-")
val second = line.split(",")[1].split("-")
if ((second[0].toInt() in first[0].toInt()..first[1].toInt() &&
second[1].toInt() in first[0].toInt()..first[1].toInt()) ||
(first[0].toInt() in second[0].toInt()..second[1].toInt() &&
first[1].toInt() in second[0].toInt()..second[1].toInt())
) {
duplicates++
}
}
return duplicates
}
fun part2(input: List<String>): Int {
var duplicates = 0
for (line in input) {
val first = line.split(",")[0].split("-")
val second = line.split(",")[1].split("-")
if (second[0].toInt() in first[0].toInt()..first[1].toInt() ||
second[1].toInt() in first[0].toInt()..first[1].toInt() ||
first[0].toInt() in second[0].toInt()..second[1].toInt() ||
first[1].toInt() in second[0].toInt()..second[1].toInt()
) {
duplicates++
}
}
return duplicates
}
val testInput = File("input", "Day04_test.txt").readLines()
val input = File("input", "Day04.txt").readLines()
val part1TestOutput = part1(testInput)
check(part1TestOutput == 2)
println(part1(input))
val part2TestOutput = part2(testInput)
check(part2TestOutput == 4)
println(part2(input))
}
| [
{
"class_path": "SelenaChen123__AdventOfCode2022__551af4f/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
SelenaChen123__AdventOfCode2022__551af4f/src/Day03/Day03.kt | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
var priorities = 0
for (line in input) {
val firstHalf = line.substring(0..line.length / 2 - 1).toSet()
val secondHalf = line.substring(line.length / 2).toSet()
val intersect = (firstHalf intersect secondHalf).first()
if (intersect.isLowerCase()) {
priorities += intersect - 'a' + 1
} else {
priorities += intersect - 'A' + 27
}
}
return priorities
}
fun part2(input: List<String>): Int {
var priorities = 0
for (index in 0..input.size - 1 step 3) {
val group1 = input[index].substring(0..input[index].length - 1).toSet()
val group2 = input[index + 1].substring(0..input[index + 1].length - 1).toSet()
val group3 = input[index + 2].substring(0..input[index + 2].length - 1).toSet()
val intersect = (group1 intersect group2 intersect group3).first()
if (intersect.isLowerCase()) {
priorities += intersect - 'a' + 1
} else {
priorities += intersect - 'A' + 27
}
}
return priorities
}
val testInput = File("input", "Day03_test.txt").readLines()
val input = File("input", "Day03.txt").readLines()
val part1TestOutput = part1(testInput)
check(part1TestOutput == 157)
println(part1(input))
val part2TestOutput = part2(testInput)
check(part2TestOutput == 70)
println(part2(input))
}
| [
{
"class_path": "SelenaChen123__AdventOfCode2022__551af4f/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
SelenaChen123__AdventOfCode2022__551af4f/src/Day02/Day02.kt | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
var points = 0
for (line in input) {
val them = line.split(" ")[0]
val you = line.split(" ")[1]
val theirValue =
when (them) {
"A" -> 1
"B" -> 2
"C" -> 3
else -> 0
}
val yourValue =
when (you) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
if (theirValue == yourValue) {
points += 3
} else if (theirValue + 1 == yourValue || (theirValue == 3 && yourValue == 1)) {
points += 6
}
points += yourValue
}
return points
}
fun part2(input: List<String>): Int {
var points = 0
for (line in input) {
val them = line.split(" ")[0]
val you = line.split(" ")[1]
val theirValue =
when (them) {
"A" -> 1
"B" -> 2
"C" -> 3
else -> 0
}
if (you == "Y") {
points += theirValue
points += 3
} else if (you == "Z") {
if (theirValue != 3) {
points += theirValue + 1
} else {
points += 1
}
points += 6
} else {
if (theirValue != 1) {
points += theirValue - 1
} else {
points += 3
}
}
}
return points
}
val testInput = File("input", "Day02_test.txt").readLines()
val input = File("input", "Day02.txt").readLines()
val part1TestOutput = part1(testInput)
check(part1TestOutput == 15)
println(part1(input))
val part2TestOutput = part2(testInput)
check(part2TestOutput == 12)
println(part2(input))
}
| [
{
"class_path": "SelenaChen123__AdventOfCode2022__551af4f/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
SelenaChen123__AdventOfCode2022__551af4f/src/Day01/Day01.kt | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
var globalMax = 0
var localMax = 0
for (line in input) {
if (line != "") {
localMax = localMax + line.toInt()
} else {
if (localMax.compareTo(globalMax) > 0) {
globalMax = localMax
}
localMax = 0
}
}
return globalMax
}
fun part2(input: List<String>): Int {
var max = ArrayList<Int>()
var localMax = 0
for (index in 0..input.size - 1) {
if (input[index] != "") {
localMax = localMax + input[index].toInt()
} else {
max.add(localMax)
if (index != input.size - 1) {
localMax = 0
}
}
}
max.add(localMax)
max.sort()
return max[max.size - 1] + max[max.size - 2] + max[max.size - 3]
}
val testInput = File("input", "Day01_test.txt").readLines()
val input = File("input", "Day01.txt").readLines()
val part1TestOutput = part1(testInput)
check(part1TestOutput == 24000)
println(part1(input))
val part2TestOutput = part2(testInput)
check(part2TestOutput == 45000)
println(part2(input))
}
| [
{
"class_path": "SelenaChen123__AdventOfCode2022__551af4f/Day01Kt.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
ryanclanigan__AdventOfCode2021__766fa81/src/main/kotlin/Day2.kt | import java.io.File
enum class Direction {
UP,
DOWN,
FORWARD
}
class SubmarineCommand(val direction: Direction, val magnitude: Int)
fun parseSubmarineCommand(command: String): SubmarineCommand {
val pieces = command.split(" ")
if (pieces.size != 2) throw Exception("Ruh roh")
return SubmarineCommand(Direction.valueOf(pieces[0].uppercase()), pieces[1].toInt())
}
fun day2Puzzle1() {
class Grid(val depth: Int, val horizontal: Int) {
fun applyCommand(command: SubmarineCommand) =
when (command.direction) {
Direction.UP -> Grid(depth - command.magnitude, horizontal)
Direction.DOWN -> Grid(depth + command.magnitude, horizontal)
Direction.FORWARD -> Grid(depth, horizontal + command.magnitude)
}
}
File("day2.txt").readLines()
.filter { it.isNotEmpty() }
.map { parseSubmarineCommand(it) }
.fold(Grid(0, 0)) { current, command -> current.applyCommand(command) }
.let { println(it.depth * it.horizontal) }
}
fun day2Puzzle2() {
class Grid(val depth: Int, val horizontal: Int, val aim: Int) {
fun applyCommand(command: SubmarineCommand) =
when (command.direction) {
Direction.UP -> Grid(depth, horizontal, aim - command.magnitude)
Direction.DOWN -> Grid(depth, horizontal, aim + command.magnitude)
Direction.FORWARD -> Grid(depth + aim * command.magnitude, horizontal + command.magnitude, aim)
}
}
File("day2.txt").readLines()
.filter { it.isNotEmpty() }
.map { parseSubmarineCommand(it) }
.fold(Grid(0, 0, 0)) { current, command -> current.applyCommand(command) }
.let { println(it.depth * it.horizontal) }
}
fun day3Puzzle2() {
val numbers = File("day3.txt").readLines()
.filter { it.isNotEmpty() }
val length = numbers[0].length
var sublist = numbers
(0..length).forEach {
if (sublist.size == 1) return@forEach
sublist = findSubListForCategory(Category.MOST, it, sublist)
}
val most = sublist[0].toInt(2)
sublist = numbers
(0..length).forEach {
if (sublist.size == 1) return@forEach
sublist = findSubListForCategory(Category.LEAST, it, sublist)
}
val least = sublist[0].toInt(2)
println(most * least)
}
fun findSubListForCategory(category: Category, index: Int, list: List<String>): List<String> {
var oneCount = 0
var zeroCount = 0
list.forEach { if (it[index] == '0') zeroCount += 1 else oneCount += 1 }
return when (category) {
Category.MOST -> list.filter {
val filterFor = if (oneCount >= zeroCount) '1' else '0'
it[index] == filterFor
}
Category.LEAST -> list.filter {
val filterFor = if (oneCount < zeroCount) '1' else '0'
it[index] == filterFor
}
}
}
enum class Category {
MOST,
LEAST
}
| [
{
"class_path": "ryanclanigan__AdventOfCode2021__766fa81/Day2Kt$day2Puzzle2$Grid$WhenMappings.class",
"javap": "Compiled from \"Day2.kt\"\npublic final class Day2Kt$day2Puzzle2$Grid$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 ... |
Javran__leetcode__f3899fe/bulb-switcher/Solution.kt | import java.lang.Math
/*
math problem in disguise.
First we figure out what determines the end state of i-th bulb (1-based):
take n = 5 as an example.
1st bulb is on because 1 has the only factor 1
2nd is off because 2 has two factors: 1,2
3rd is off because 3 has two factors: 1,3
4th: on, factors: 1,2,4
5th: off, factors: 1,5
now note that when i>1, i-th bulb is on if and only if i has odd number of factors
for any integer N, we can do factorization:
N = p1^a1 * p2^a2 ... * pk^ak where p are prime numbers
and the number of factors will be T = (a1 + 1)*(a2 + 1)* ... *(ak + 1)
if T is an odd, we know i-th bulb will be on.
since we need T = (a1 + 1)*(a2 + 1)* ... *(ak + 1) to be odd,
all of (a_ + 1) needs to be odd because any of them being even will cause T to be even,
which means all (a_) needs to be even.
N = p1^(b1*2) * p2^(b2*2) * ... * pk^(bk*2) where a_ = b_*2 ...
well, now we know that N has to be a square number.
Given n bulbs, if we count the # of square numbers in range of 1 .. n, that is the anwser
to the question - just do floor(sqrt(n)) and we are done.
*/
class Solution {
fun bulbSwitch(n: Int): Int {
return Math.floor(Math.sqrt(n.toDouble())).toInt()
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(Solution().bulbSwitch(10))
}
}
}
| [
{
"class_path": "Javran__leetcode__f3899fe/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class Solution {\n public static final Solution$Companion Companion;\n\n public Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Objec... |
colintheshots__ExercismKotlin__f284aec/kotlin/pig-latin/src/main/kotlin/PigLatin.kt | import java.util.*
object PigLatin {
private val vowels = setOf('a','e','i','o','u')
fun translate(input: String) : String {
require(input.all { it.isLowerCase() || it.isWhitespace() })
return input.replace("\\b\\w+\\b".toRegex()) { result : MatchResult ->
val word = result.value
when {
word[0] in vowels -> word + "ay"
word.startsWith("qu") -> word.substring(2) + "quay"
word.startsWith("squ") -> word.substring(3) + "squay"
word == "xray" -> word + "ay"
else -> {
val firstY = word.indexOfFirst { it == 'y' }
val firstVowel = word.indexOfFirst { it in vowels }
val beforeVowel = firstVowel == -1 || firstY < firstVowel
val yIsVowel = firstY != -1 && (word.length == firstY + 1
|| word.length > firstY + 1
&& word[firstY + 1] !in vowels)
if (beforeVowel && yIsVowel) {
val beforeY = word.substring(0, firstY)
val afterY = word.substring(firstY)
afterY + beforeY + "ay"
} else {
val beginning = if (firstVowel != -1) word.substring(firstVowel) else word
val remainder = if (firstVowel != -1) word.substring(0, firstVowel) else ""
beginning + remainder + "ay"
}
}
}
}
}
}
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val numTestCases = scanner.nextInt()
require(numTestCases in 1..20)
(0 until numTestCases).map {
val numThieves = scanner.nextInt()
require(numThieves in 1..100)
val duration = scanner.nextInt()
require(duration in 0..1000000)
val thiefSlots = mutableListOf(0, 0)
val entries = (0 until numThieves).map { scanner.nextInt() }
entries.forEach{ require(it in 0..100)}
entries.forEach{
thiefSlots.addToSmallest(it)
}
if (thiefSlots.max()!! > duration) {
"NO"
} else {
"YES"
}
}.forEach(::println)
}
fun MutableList<Int>.addToSmallest(duration : Int) : MutableList<Int> {
val indexOfSmallest = indexOfFirst { it == min() }
this[indexOfSmallest] += duration
return this
} | [
{
"class_path": "colintheshots__ExercismKotlin__f284aec/PigLatin.class",
"javap": "Compiled from \"PigLatin.kt\"\npublic final class PigLatin {\n public static final PigLatin INSTANCE;\n\n private static final java.util.Set<java.lang.Character> vowels;\n\n private PigLatin();\n Code:\n 0: aload_... |
colintheshots__ExercismKotlin__f284aec/kotlin/change/src/main/kotlin/ChangeCalculator.kt | class ChangeCalculator (list: List<Int>) {
private val sortedList = list.sortedDescending()
fun computeMostEfficientChange(total : Int) : List<Int> {
require(total >= 0) {"Negative totals are not allowed."}
if (total == 0) return emptyList() // no coins make zero change
val trimmed = sortedList.dropWhile { it > total } // drop useless values
var pairs = pairsOf(trimmed, total)
while(pairs.isNotEmpty() && pairs.none { it.first == total }) { // stop if no pairs remain or found match
pairs = pairsOf(trimmed, total, pairs)
}
if (pairs.isEmpty())
throw IllegalArgumentException("The total $total cannot be represented in the given currency.")
else return pairs.filter { it.first == total }
.minBy { it.second.size }?.second
?.reversed() ?: throw IllegalArgumentException("No minimum found")
}
// Memoize sums of lists to reduce problem complexity, i.e. dynamic programming
private fun pairsOf(left: Collection<Int>,
total: Int,
pairs: List<Pair<Int, List<Int>>> = listOf()): List<Pair<Int, List<Int>>> {
return if (pairs.isEmpty()) { // build up initial list with all pairs including single coins
left.flatMap { first ->
left.filter { it <= first }
.plus(0) // handle single coins by pairing values with zero
.map { second -> Pair(first + second, listOf(first, second)) }
.filter { it.first <= total }
.map { Pair(it.first, it.second.filter { it>0 }) } // filter out zeroes
}
} else { // add remaining candidate coins to each remaining pair
pairs.flatMap { pair ->
left.filter { it <= pair.second.last() }
.map { second -> Pair(pair.first + second, pair.second + second) }
.filter { it.first <= total }
}
}
}
} | [
{
"class_path": "colintheshots__ExercismKotlin__f284aec/ChangeCalculator.class",
"javap": "Compiled from \"ChangeCalculator.kt\"\npublic final class ChangeCalculator {\n private final java.util.List<java.lang.Integer> sortedList;\n\n public ChangeCalculator(java.util.List<java.lang.Integer>);\n Code:\n... |
indy256__codelibrary__4055526/kotlin/SuffixArray.kt | fun suffixArray(S: CharSequence): IntArray {
val n = S.length
// Stable sort of characters.
// Same characters are sorted by their position in descending order.
// E.g. last character which represents suffix of length 1 should be ordered first among same characters.
val sa = S.indices.reversed().sortedBy { S[it] }.toIntArray()
val classes = S.chars().toArray()
// sa[i] - suffix on i'th position after sorting by first len characters
// classes[i] - equivalence class of the i'th suffix after sorting by first len characters
var len = 1
while (len < n) {
// Calculate classes for suffixes of length len * 2
val c = classes.copyOf()
for (i in 0 until n) {
// Condition sa[i - 1] + len < n emulates 0-symbol at the end of the string.
// A separate class is created for each suffix followed by emulated 0-symbol.
classes[sa[i]] =
if (i > 0 && c[sa[i - 1]] == c[sa[i]] && sa[i - 1] + len < n
&& c[sa[i - 1] + len / 2] == c[sa[i] + len / 2]) classes[sa[i - 1]]
else i
}
// Suffixes are already sorted by first len characters
// Now sort suffixes by first len * 2 characters
val cnt = IntArray(n) { it }
val s = sa.copyOf()
for (i in 0 until n) {
// s[i] - order of suffixes sorted by first len characters
// (s[i] - len) - order of suffixes sorted only by second len characters
val s1 = s[i] - len
// sort only suffixes of length > len, others are already sorted
if (s1 >= 0)
sa[cnt[classes[s1]]++] = s1
}
len *= 2
}
return sa
}
// Usage example
fun main() {
val s = "abcab"
val sa = suffixArray(s)
// print suffixes in lexicographic order
// print suffixes in lexicographic order
for (p in sa) println(s.substring(p))
}
| [
{
"class_path": "indy256__codelibrary__4055526/SuffixArrayKt.class",
"javap": "Compiled from \"SuffixArray.kt\"\npublic final class SuffixArrayKt {\n public static final int[] suffixArray(java.lang.CharSequence);\n Code:\n 0: aload_0\n 1: ldc #9 // String S\n ... |
indy256__codelibrary__4055526/kotlin/MaxBipartiteMatchingEV.kt | // https://en.wikipedia.org/wiki/Matching_(graph_theory)#In_unweighted_bipartite_graphs in O(V * E)
fun maxMatching(graph: Array<out List<Int>>, n2: Int): Int {
val n1 = graph.size
val vis = BooleanArray(n1)
val matching = IntArray(n2) { -1 }
val findPath = DeepRecursiveFunction { u1 ->
vis[u1] = true
for (v in graph[u1]) {
val u2 = matching[v]
if (u2 == -1 || !vis[u2] && callRecursive(u2) == 1) {
matching[v] = u1
return@DeepRecursiveFunction 1
}
}
0
}
return (0 until n1).sumOf { vis.fill(false); findPath(it) }
}
// Usage example
fun main() {
val g = (1..2).map { arrayListOf<Int>() }.toTypedArray()
g[0].add(0)
g[0].add(1)
g[1].add(1)
println(2 == maxMatching(g, 2))
}
| [
{
"class_path": "indy256__codelibrary__4055526/MaxBipartiteMatchingEVKt$maxMatching$findPath$1.class",
"javap": "Compiled from \"MaxBipartiteMatchingEV.kt\"\nfinal class MaxBipartiteMatchingEVKt$maxMatching$findPath$1 extends kotlin.coroutines.jvm.internal.RestrictedSuspendLambda implements kotlin.jvm.funct... |
indy256__codelibrary__4055526/kotlin/Dijkstra.kt | object Dijkstra {
data class Edge(val target: Int, val cost: Int)
data class ShortestPaths(val dist: IntArray, val pred: IntArray)
fun shortestPaths(graph: Array<out List<Edge>>, s: Int): ShortestPaths {
val n = graph.size
val dist = IntArray(n) { Int.MAX_VALUE }
dist[s] = 0
val pred = IntArray(n) { -1 }
val visited = BooleanArray(n)
for (i in 0 until n) {
var u = -1
for (j in 0 until n) {
if (!visited[j] && (u == -1 || dist[u] > dist[j]))
u = j
}
if (dist[u] == Int.MAX_VALUE)
break
visited[u] = true
for (e in graph[u]) {
val v = e.target
val nprio = dist[u] + e.cost
if (dist[v] > nprio) {
dist[v] = nprio
pred[v] = u
}
}
}
return ShortestPaths(dist, pred)
}
// Usage example
@JvmStatic
fun main(args: Array<String>) {
val cost = arrayOf(intArrayOf(0, 3, 2), intArrayOf(0, 0, -2), intArrayOf(0, 0, 0))
val n = cost.size
val graph = (1..n).map { arrayListOf<Edge>() }.toTypedArray()
for (i in 0 until n) {
for (j in 0 until n) {
if (cost[i][j] != 0) {
graph[i].add(Edge(j, cost[i][j]))
}
}
}
println(graph.contentToString())
val (dist, pred) = shortestPaths(graph, 0)
println(0 == dist[0])
println(3 == dist[1])
println(1 == dist[2])
println(-1 == pred[0])
println(0 == pred[1])
println(1 == pred[2])
}
}
| [
{
"class_path": "indy256__codelibrary__4055526/Dijkstra.class",
"javap": "Compiled from \"Dijkstra.kt\"\npublic final class Dijkstra {\n public static final Dijkstra INSTANCE;\n\n private Dijkstra();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<i... |
indy256__codelibrary__4055526/kotlin/MaxFlowDinic.kt | // https://en.wikipedia.org/wiki/Dinic%27s_algorithm in O(V^2 * E)
class MaxFlowDinic(nodes: Int) {
data class Edge(val t: Int, val rev: Int, val cap: Int, var f: Int = 0)
val graph = (1..nodes).map { arrayListOf<Edge>() }.toTypedArray()
val dist = IntArray(nodes)
fun addBidiEdge(s: Int, t: Int, cap: Int) {
graph[s].add(Edge(t, graph[t].size, cap))
graph[t].add(Edge(s, graph[s].size - 1, 0))
}
fun dinicBfs(src: Int, dest: Int, dist: IntArray): Boolean {
dist.fill(-1)
dist[src] = 0
val q = IntArray(graph.size)
var sizeQ = 0
q[sizeQ++] = src
var i = 0
while (i < sizeQ) {
val u = q[i++]
for (e in graph[u]) {
if (dist[e.t] < 0 && e.f < e.cap) {
dist[e.t] = dist[u] + 1
q[sizeQ++] = e.t
}
}
}
return dist[dest] >= 0
}
fun dinicDfs(ptr: IntArray, dest: Int, u: Int, f: Int): Int {
if (u == dest)
return f
while (ptr[u] < graph[u].size) {
val e = graph[u][ptr[u]]
if (dist[e.t] == dist[u] + 1 && e.f < e.cap) {
val df = dinicDfs(ptr, dest, e.t, Math.min(f, e.cap - e.f))
if (df > 0) {
e.f += df
graph[e.t][e.rev].f -= df
return df
}
}
++ptr[u]
}
return 0
}
fun maxFlow(src: Int, dest: Int): Int {
var flow = 0
while (dinicBfs(src, dest, dist)) {
val ptr = IntArray(graph.size)
while (true) {
val df = dinicDfs(ptr, dest, src, Int.MAX_VALUE)
if (df == 0)
break
flow += df
}
}
return flow
}
// invoke after maxFlow()
fun minCut() = dist.map { it != -1 }.toBooleanArray()
fun clearFlow() {
for (edges in graph)
for (edge in edges)
edge.f = 0
}
}
// Usage example
fun main(args: Array<String>) {
val flow = MaxFlowDinic(3)
flow.addBidiEdge(0, 1, 3)
flow.addBidiEdge(0, 2, 2)
flow.addBidiEdge(1, 2, 2)
println(4 == flow.maxFlow(0, 2))
}
| [
{
"class_path": "indy256__codelibrary__4055526/MaxFlowDinicKt.class",
"javap": "Compiled from \"MaxFlowDinic.kt\"\npublic final class MaxFlowDinicKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: in... |
indy256__codelibrary__4055526/kotlin/Determinant.kt | import kotlin.math.abs
// https://en.wikipedia.org/wiki/Determinant
fun det(matrix: Array<DoubleArray>): Double {
val EPS = 1e-10
val a = matrix.map { it.copyOf() }.toTypedArray()
val n = a.size
var res = 1.0
for (i in 0 until n) {
val p = (i until n).maxByOrNull { abs(a[it][i]) }!!
if (abs(a[p][i]) < EPS)
return 0.0
if (i != p) {
res = -res
a[i] = a[p].also { a[p] = a[i] }
}
res *= a[i][i]
for (j in i + 1 until n)
a[i][j] /= a[i][i]
for (j in 0 until n)
if (j != i && abs(a[j][i]) > EPS /*optimizes overall complexity to O(n^2) for sparse matrices*/)
for (k in i + 1 until n)
a[j][k] -= a[i][k] * a[j][i]
}
return res
}
// Usage example
fun main() {
val d = det(arrayOf(doubleArrayOf(0.0, 1.0), doubleArrayOf(-1.0, 0.0)))
println(abs(d - 1) < 1e-10)
}
| [
{
"class_path": "indy256__codelibrary__4055526/DeterminantKt.class",
"javap": "Compiled from \"Determinant.kt\"\npublic final class DeterminantKt {\n public static final double det(double[][]);\n Code:\n 0: aload_0\n 1: ldc #9 // String matrix\n 3: invokestat... |
indy256__codelibrary__4055526/kotlin/Rational.kt | import java.math.BigInteger
class Rational(n: BigInteger, d: BigInteger = BigInteger.ONE) : Comparable<Rational> {
val num: BigInteger
val den: BigInteger
init {
val gcd = n.gcd(d)
val g = if (d.signum() > 0) gcd else if (d.signum() < 0) gcd.negate() else BigInteger.ONE
num = n.divide(g)
den = d.divide(g)
}
constructor(num: Long, den: Long = 1) : this(BigInteger.valueOf(num), BigInteger.valueOf(den))
operator fun plus(r: Rational): Rational = Rational(num.multiply(r.den).add(r.num.multiply(den)), den.multiply(r.den))
operator fun minus(r: Rational): Rational = Rational(num.multiply(r.den).subtract(r.num.multiply(den)), den.multiply(r.den))
operator fun times(r: Rational): Rational = Rational(num.multiply(r.num), den.multiply(r.den))
operator fun div(r: Rational): Rational = Rational(num.multiply(r.den), den.multiply(r.num))
operator fun unaryMinus(): Rational = Rational(num.negate(), den)
fun inverse(): Rational = Rational(den, num)
fun abs(): Rational = Rational(num.abs(), den)
fun signum(): Int = num.signum()
fun doubleValue(): Double = num.toDouble() / den.toDouble()
fun longValue(): Long = num.toLong() / den.toLong()
override fun compareTo(other: Rational): Int = num.multiply(other.den).compareTo(other.num.multiply(den))
override fun equals(other: Any?): Boolean = num == (other as Rational).num && den == other.den
override fun hashCode(): Int = num.hashCode() * 31 + den.hashCode()
override fun toString(): String = "$num/$den"
companion object {
val ZERO = Rational(0)
val ONE = Rational(1)
val POSITIVE_INFINITY = Rational(1, 0)
val NEGATIVE_INFINITY = Rational(-1, 0)
}
}
// Usage example
fun main() {
val a = Rational(1, 3)
val b = Rational(1, 6)
val s1 = Rational(1, 2)
val s2 = a + b
println(true == (s1 == s2))
println(a * b / b - a)
println(a * Rational.ZERO)
}
| [
{
"class_path": "indy256__codelibrary__4055526/RationalKt.class",
"javap": "Compiled from \"Rational.kt\"\npublic final class RationalKt {\n public static final void main();\n Code:\n 0: new #8 // class Rational\n 3: dup\n 4: lconst_1\n 5: ldc2_w ... |
indy256__codelibrary__4055526/kotlin/ConvexHull.kt | data class Point(val x: Int, val y: Int)
// Convex hull in O(n*log(n))
fun convexHull(points: Array<Point>): Array<Point> {
fun isNotRightTurn(p3: List<Point>): Boolean {
val (a, b, c) = p3
val cross = (a.x - b.x).toLong() * (c.y - b.y) - (a.y - b.y).toLong() * (c.x - b.x)
val dot = (a.x - b.x).toLong() * (c.x - b.x) + (a.y - b.y).toLong() * (c.y - b.y)
return cross < 0 || cross == 0L && dot <= 0
}
val sortedPoints = points.sortedArrayWith(compareBy({ it.x }, { it.y }))
val n = sortedPoints.size
val hull = arrayListOf<Point>()
for (i in 0 until 2 * n) {
val j = if (i < n) i else 2 * n - 1 - i
while (hull.size >= 2 && isNotRightTurn(hull.takeLast(2) + sortedPoints[j]))
hull.removeAt(hull.size - 1)
hull.add(sortedPoints[j])
}
return hull.subList(0, hull.size - 1).toTypedArray()
}
// Usage example
fun main() {
val points = arrayOf(Point(0, 0), Point(2, 2), Point(1, 1), Point(0, 1), Point(1, 0), Point(0, 0))
val hull = convexHull(points)
println(hull.contentToString())
}
| [
{
"class_path": "indy256__codelibrary__4055526/ConvexHullKt.class",
"javap": "Compiled from \"ConvexHull.kt\"\npublic final class ConvexHullKt {\n public static final Point[] convexHull(Point[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String points\n 3: invokest... |
indy256__codelibrary__4055526/kotlin/PersistentTree.kt | // https://en.wikipedia.org/wiki/Persistent_data_structure
object PersistentTree {
data class Node(
val left: Node? = null,
val right: Node? = null,
val sum: Int = (left?.sum ?: 0) + (right?.sum ?: 0)
)
fun build(left: Int, right: Int): Node {
if (left == right)
return Node(null, null)
val mid = left + right shr 1
return Node(build(left, mid), build(mid + 1, right))
}
fun sum(a: Int, b: Int, root: Node, left: Int, right: Int): Int {
if (a == left && b == right)
return root.sum
val mid = left + right shr 1
var s = 0
if (a <= mid)
s += sum(a, minOf(b, mid), root.left!!, left, mid)
if (b > mid)
s += sum(maxOf(a, mid + 1), b, root.right!!, mid + 1, right)
return s
}
fun set(pos: Int, value: Int, root: Node, left: Int, right: Int): Node {
if (left == right)
return Node(null, null, value)
val mid = left + right shr 1
return if (pos <= mid)
Node(set(pos, value, root.left!!, left, mid), root.right)
else
Node(root.left, set(pos, value, root.right!!, mid + 1, right))
}
// Usage example
@JvmStatic
fun main(args: Array<String>) {
val n = 10
val t1 = build(0, n - 1)
val t2 = set(0, 1, t1, 0, n - 1)
println(0 == sum(0, 9, t1, 0, n - 1))
println(1 == sum(0, 9, t2, 0, n - 1))
}
}
| [
{
"class_path": "indy256__codelibrary__4055526/PersistentTree.class",
"javap": "Compiled from \"PersistentTree.kt\"\npublic final class PersistentTree {\n public static final PersistentTree INSTANCE;\n\n private PersistentTree();\n Code:\n 0: aload_0\n 1: invokespecial #8 /... |
indy256__codelibrary__4055526/kotlin/Gauss.kt | import kotlin.math.abs
import java.util.Random
// https://en.wikipedia.org/wiki/Gauss–Jordan_elimination
// returns x such that A * x = b. requires |A| > 0
fun gauss(A: Array<DoubleArray>, b: DoubleArray): DoubleArray {
val a = A.mapIndexed { i, Ai -> Ai + b[i] }.toTypedArray()
val n = a.size
for (i in 0 until n) {
val pivot = (i until n).maxByOrNull { abs(a[it][i]) }!!
a[i] = a[pivot].also { a[pivot] = a[i] }
for (j in i + 1..n)
a[i][j] /= a[i][i]
for (j in 0 until n)
if (j != i && a[j][i] != 0.0)
for (k in i + 1..n)
a[j][k] -= a[i][k] * a[j][i]
}
return a.map { it[n] }.toDoubleArray()
}
// random test
fun main() {
val rnd = Random(1)
for (step in 0..9999) {
val n = rnd.nextInt(5) + 1
val a = (0 until n).map { (0 until n).map { (rnd.nextInt(10) - 5).toDouble() }.toDoubleArray() }.toTypedArray()
if (abs(det(a)) > 1e-6) {
val b = (0 until n).map { (rnd.nextInt(10) - 5).toDouble() }.toDoubleArray()
val x = gauss(a, b)
for (i in a.indices) {
val y = a[i].zip(x).sumOf { it.first * it.second }
if (abs(b[i] - y) > 1e-9)
throw RuntimeException()
}
}
}
}
| [
{
"class_path": "indy256__codelibrary__4055526/GaussKt.class",
"javap": "Compiled from \"Gauss.kt\"\npublic final class GaussKt {\n public static final double[] gauss(double[][], double[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String A\n 3: invokestatic #15 ... |
JC6__LeetCode__493dbe8/004.median-of-two-sorted-arrays/solution.kt | import kotlin.math.max
import kotlin.math.min
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val size = nums1.size + nums2.size
return if (size % 2 == 0) {
(findK(nums1, nums2, size / 2) + findK(nums1, nums2, size / 2 + 1)) / 2.0
} else {
findK(nums1, nums2, size / 2 + 1).toDouble()
}
}
fun findK(nums1: IntArray, nums2: IntArray, k: Int): Int {
var i = max(0, k - nums2.size)
var j = min(k, nums1.size)
while (i < j) {
val m = (i + j) / 2
if (nums1[m] < nums2[k - m - 1]) {
i = m + 1
} else {
j = m
}
}
return when (i) {
0 -> nums2[k - i - 1]
k -> nums1[i - 1]
else -> max(nums1[i - 1], nums2[k - i - 1])
}
}
| [
{
"class_path": "JC6__LeetCode__493dbe8/SolutionKt.class",
"javap": "Compiled from \"solution.kt\"\npublic final class SolutionKt {\n public static final double findMedianSortedArrays(int[], int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String nums1\n 3: invoke... |
shencang__note__f321a2e/语言知识(Language knowledge)/Kotlin/Practice/src/Main.kt | //顶层变量:
val Pi = 3.14159265358979
var temp = 0
fun main(){
//定义只读局部变量使⽤关键字 val 定义。只能为其赋值⼀次
val a: Int = 1 // ⽴即赋值
val b = 2 // ⾃动推断出 `Int` 类型
val c: Int // 如果没有初始值类型不能省略
c = 3 // 明确赋值
var edge = a*b*c
println("S-P-D-B")
println(sum(a,b))
edge*=2
println(sum1(b,c))
println(sum2(a,c))
println(sum3(b,c))
println("sum:${sum(edge,edge)}")
println(incrementX())
println(maxOf(a,b))
}
//带有两个 Int 参数、返回 Int 的函数
fun sum(a:Int,b:Int):Int{
return a+b
}
//将表达式作为函数体、返回值类型⾃动推断的函数
fun sum1(a:Int,b:Int)= a+b
//函数返回⽆意义的值:
fun sum2(a:Int,b:Int):Unit{
println("sum of $a and $b is ${a+b}")
}
//Unit 返回类型可以省略:
fun sum3(a:Int,b:Int){
println("sum of $a and $b is ${a+b}")
}
fun incrementX():Int{
temp +=9
temp *=temp
println(Pi)
val sz = "temp is $temp"
temp = 10086
println(sz)
val so = "${sz.replace("is","was")},but new is $temp"
println(so)
return temp
}
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
| [
{
"class_path": "shencang__note__f321a2e/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n private static final double Pi;\n\n private static int temp;\n\n public static final double getPi();\n Code:\n 0: getstatic #10 // Field Pi:D\n 3: ... |
SimonMarquis__advent-of-code-2020__560e322/src/main/kotlin/Day03.kt | class Day03(raw: List<String>) {
private val forest: Forest = Forest.parse(raw)
fun part1(): Long = forest.trees(Slope(right = 3, down = 1))
fun part2(): Long = listOf(
Slope(right = 1, down = 1),
Slope(right = 3, down = 1),
Slope(right = 5, down = 1),
Slope(right = 7, down = 1),
Slope(right = 1, down = 2),
).map(forest::trees).reduce { acc, i -> acc * i }
data class Forest(val raw: List<BooleanArray>) {
companion object {
fun parse(lines: List<String>): Forest = lines.map { line ->
line.map { it.toTree() }.toBooleanArray()
}.let(::Forest)
private fun Char.toTree() = when (this) {
'#' -> true
'.' -> false
else -> throw Exception()
}
}
private operator fun get(position: Position): Boolean = raw[position.y].let { it[position.x % it.size] }
private fun horizontal(slope: Slope): Sequence<Int> = generateSequence(0) { x -> x + slope.right }
private fun vertical(slope: Slope): Sequence<Int> = generateSequence(0) { y -> (y + slope.down).takeUnless { it >= raw.size } }
private fun positions(slope: Slope): Sequence<Position> = horizontal(slope).zip(vertical(slope), ::Position)
fun trees(slope: Slope): Long = positions(slope).count { this[it] }.toLong()
}
data class Slope(val right: Int, val down: Int)
data class Position(val x: Int, val y: Int)
} | [
{
"class_path": "SimonMarquis__advent-of-code-2020__560e322/Day03$Forest$positions$1.class",
"javap": "Compiled from \"Day03.kt\"\nfinal class Day03$Forest$positions$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function2<java.lang.Integer, java.lang.Integer, Day03$Posi... |
reitzig__advent-of-code-2020__f17184f/src/main/kotlin/shared.kt | import kotlin.math.absoluteValue
data class Either<T, U>(val t: T? = null, val u: U? = null) {
init {
assert((t == null) != (u == null)) { "Exactly one parameter must be null" }
}
override fun toString(): String = "${t ?: ""}${u ?: ""}"
}
fun <T> List<T>.split(splitEntry: T): List<List<T>> =
this.fold(mutableListOf(mutableListOf<T>())) { acc, line ->
if (line == splitEntry) {
acc.add(mutableListOf())
} else {
acc.last().add(line)
}
return@fold acc
}
fun <T> List<T>.replace(index: Int, newElement: T): List<T> =
mapIndexed { i, elem ->
if (i == index) {
newElement
} else {
elem
}
}
fun <T> List<T>.replace(index: Int, replacer: (T) -> T): List<T> =
mapIndexed { i, elem ->
if (i == index) {
replacer(elem)
} else {
elem
}
}
fun <T> List<List<T>>.replace(index: Pair<Int, Int>, newElement: T): List<List<T>> =
replace(index.first) { it.replace(index.second, newElement) }
fun <T> (MutableList<T>).removeAllAt(indices: IntRange): List<T> {
val result = this.subList(indices.first, indices.last + 1).toList()
indices.forEach { _ -> removeAt(indices.first) }
return result
}
fun <T> (MutableList<T>).rotateLeft(by: Int) {
for (i in 1..(by % size)) {
add(removeAt(0))
}
}
fun <T, U> List<T>.combinationsWith(other: List<U>): List<Pair<T, U>> =
flatMap { left -> other.map { right -> Pair(left, right) } }
fun <T> List<T>.combinations(): List<Pair<T, T>> =
combinationsWith(this)
fun <T> List<T>.combinations(times: Int): List<List<T>> =
when (times) {
0 -> listOf()
1 -> map { listOf(it) }
else -> combinations(times - 1).let { tails ->
tails.flatMap { tail -> this.map { head -> tail + head } }
}
}
fun <T : Comparable<T>> List<T>.indexOfMaxOrNull(): Int? =
mapIndexed { i, e -> Pair(i, e) }.maxByOrNull { it.second }?.first
fun <T, R : Comparable<R>> List<T>.indexOfMaxByOrNull(selector: (T) -> R): Int? =
mapIndexed { i, e -> Pair(i, selector(e)) }.maxByOrNull { it.second }?.first
fun <S, T, U> Pair<S, Pair<T, U>>.flatten(): Triple<S, T, U> =
Triple(this.first, this.second.first, this.second.second)
//fun <S, T, U> Pair<Pair<S, T>, U>.flatten(): Triple<S, T, U> =
// Triple(this.first.first, this.first.second, this.second)
operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> =
Pair(first + other.first, second + other.second)
operator fun Pair<Int, Int>.times(factor: Int): Pair<Int, Int> =
Pair(first * factor, second * factor)
fun Pair<Int, Int>.manhattanFrom(origin: Pair<Int, Int> = Pair(0, 0)): Int =
(origin.first - this.first).absoluteValue +
(origin.second - this.second).absoluteValue
//fun Pair<Int, Int>.projectRay(): Sequence<Pair<Int, Int>> =
// generateSequence(this) { it + this }
fun Pair<Int, Int>.projectRay(
direction: Pair<Int, Int>,
isInBounds: (Pair<Int, Int>).() -> Boolean = { true }
): Sequence<Pair<Int, Int>> =
generateSequence(this) { (it + direction).takeIf(isInBounds) }
data class Quadruple<out A, out B, out C, out D>(
public val first: A,
public val second: B,
public val third: C,
public val fourth: D
) {
override fun toString(): String = "($first, $second, $third, $fourth)"
}
fun <T> Quadruple<T, T, T, T>.toList(): List<T> = listOf(first, second, third, fourth) | [
{
"class_path": "reitzig__advent-of-code-2020__f17184f/SharedKt.class",
"javap": "Compiled from \"shared.kt\"\npublic final class SharedKt {\n public static final <T> java.util.List<java.util.List<T>> split(java.util.List<? extends T>, T);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
BrightOS__os_2__84f5b71/src/main/kotlin/Main.kt | import java.io.File
const val QUANTUM_TIME = 2
private var numberOfPriorityTicks = 0
fun parseInputFile(file: File): Pair<ArrayList<Process>, Int> {
var resultNumberOfTicks = 0
val list = arrayListOf<Process>().apply {
file.forEachLine {
it.split(" ").let {
add(
Process(
name = it[0],
numberOfTicks = it[1].toInt(),
priority = it[2].toInt(),
afterWhatTick = (if (it.size > 3) it[3] else "0").toInt()
).let {
if (it.priority > 0)
numberOfPriorityTicks += it.numberOfTicks
resultNumberOfTicks += it.numberOfTicks
it
}
)
}
}
}
return Pair(list, resultNumberOfTicks)
}
fun main() {
val numberOfActualTicks: Int
var numberOfWaitTicks = 0
var numberOfAbstractTicks = 0
val processList = parseInputFile(
// File("test1")
File("test2")
// File("test3")
).let {
numberOfActualTicks = it.second
it.first
}.apply {
sortBy { it.priority }
}
val ticks = arrayListOf<String>()
repeat(numberOfActualTicks / QUANTUM_TIME) {
if (it < (numberOfActualTicks - numberOfPriorityTicks) / QUANTUM_TIME)
processList.filter { it.priority == 0 }.forEach { process ->
if (process.ticksLeft > 0) {
repeat(minOf(QUANTUM_TIME, process.ticksLeft)) {
process.ticksLeft--
ticks.add(process.name)
}
}
}
else
processList.filter { it.priority > 0 }.forEach { process ->
if (process.ticksLeft > 0) {
repeat(minOf(QUANTUM_TIME, process.ticksLeft)) {
process.ticksLeft--
ticks.add(process.afterWhatTick, process.name)
}
}
}
}
processList.forEach { process ->
print(
"${process.name} ${process.priority} ${process.numberOfTicks} "
)
ticks.subList(0, ticks.indexOfLast { it.contains(process.name) } + 1).forEach {
print(it.contains(process.name).let {
if (!it) numberOfWaitTicks++
numberOfAbstractTicks++
if (it) "И" else "Г"
})
}
println()
}
// println(ticks)
println("Efficiency: ${"%.${2}f".format(((1 - numberOfWaitTicks.toFloat() / numberOfAbstractTicks) * 100))}% | With quantum time: $QUANTUM_TIME")
}
data class Process(
val name: String,
val numberOfTicks: Int,
val priority: Int,
val afterWhatTick: Int = 0,
var ticksLeft: Int = numberOfTicks
) | [
{
"class_path": "BrightOS__os_2__84f5b71/MainKt$main$lambda$6$$inlined$sortBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class MainKt$main$lambda$6$$inlined$sortBy$1<T> implements java.util.Comparator {\n public MainKt$main$lambda$6$$inlined$sortBy$1();\n Code:\n 0: aload_0... |
chynerdu__JAV1001-Lab2__7492690/ArrayTools.kt |
fun main() {
println("Hello World")
println(averageArray(arrayOf(1, 2, 2, 4, 4)))
println(averageArray(arrayOf(1, -2, -2, 4, 4)))
println(checkValueExistence(arrayOf(1, 2, 2, 4, 4), 8))
println(reverseArray(arrayOf(1, 2, 3, 4, 5, 6, 7, 34, 28)))
val ciphertext = caesarCipherFunc()
println(ciphertext)
println(findMaxValue(arrayOf(-1, -2, -3, -4, -5)))
}
/**
* Find the average of an array
* @param inputArray contains the array to be averaged
* @return the average of type Double
*/
fun averageArray(inputArray: Array<Int>): Double {
var listSum = 0.0
for (datax in inputArray) {
listSum += datax
}
return listSum / inputArray.size
}
/**
* Check if a value exist in an array
* @param valueList contains an array of string
* @param value is the value to check if it exist in the array
* @return A boolean value if the value exists or not
*/
fun checkValueExistence(valueList: Array<Int>, value: Int): Boolean {
for (x in valueList) {
if (x == value) {
return true
}
}
return false
}
/**
* Reverse an array
* @param inputArray contains the array to be reversed
* @return A mutable list of the reversed array
*/
fun reverseArray(inputArray: Array<Int>): MutableList<Int> {
var reversedList = MutableList<Int>(inputArray.size) { 0 }
var index = inputArray.size - 1
println(index)
for (num in inputArray) {
reversedList[index] = num
index--
}
return reversedList
}
/**
* Caeser Cipher function encrypts the string entered by the user by a specific shift value
* @return An encrypted string
*/
fun caesarCipherFunc(): String {
try {
val shiftedText = StringBuilder()
println("Enter input string to encrypt")
val stringValue = readLine()
println("Enter the shift value")
val shift = readLine()?.toInt()
if (!stringValue.isNullOrEmpty() && shift != null) {
for (char in stringValue) {
if (char.isLetter()) {
val startOffset = if (char.isUpperCase()) 'A' else 'a'
val shiftedChar = (((char.toInt() - startOffset.toInt()) + shift) % 26 + startOffset.toInt()).toChar()
shiftedText.append(shiftedChar)
} else {
shiftedText.append(char)
}
}
}
return shiftedText.toString()
} catch (e: NumberFormatException) {
return "Invalid input entered"
}
}
fun findMaxValue(inputList: Array<Int>): Int {
var maxValue = Int.MIN_VALUE
for (value in inputList) {
if (value > maxValue) {
maxValue = value
}
}
return maxValue
}
| [
{
"class_path": "chynerdu__JAV1001-Lab2__7492690/ArrayToolsKt.class",
"javap": "Compiled from \"ArrayTools.kt\"\npublic final class ArrayToolsKt {\n public static final void main();\n Code:\n 0: ldc #8 // String Hello World\n 2: getstatic #14 //... |
jcornaz__aoc-kotlin-2022__979c00c/src/main/kotlin/Day15.kt | import kotlin.math.abs
object Day15 {
fun part1(input: String): Long = numberOfNonBeacon(input, 2000000).toLong()
fun part2(input: String, searchScope: Int): Long {
val scan = Scan.parse(input)
val beacon = (0..searchScope)
.asSequence()
.map { y -> y to scan.uncoveredRange(y, 0..searchScope) }
.first { (_, range) -> range.size > 0 }
.let { (y, range) -> range.asSequence().map { Position(it, y) } }
.first()
return beacon.x.toLong() * 4_000_000 + beacon.y.toLong()
}
private val LINE_REGEX = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
fun numberOfNonBeacon(input: String, y: Int): Int {
val scan = Scan.parse(input)
val searchRange = scan.minX..scan.maxX
val uncovered = scan.uncoveredRange(y, scan.minX..scan.maxX)
return searchRange.size - uncovered.size - scan.beacons.count { it.y == y }
}
private class Scan private constructor(val beacons: Set<Position>, private val sensors: List<Sensor>) {
val minX get() = sensors.minOf { it.minX }
val maxX get() = sensors.maxOf { it.maxX }
fun uncoveredRange(y: Int, initialRange: IntRange): SearchRange =
sensors.fold(SearchRange(initialRange)) { range, sensor ->
sensor.coverage(y)?.let(range::remove) ?: range
}
companion object {
fun parse(input: String): Scan {
val beacons = mutableSetOf<Position>()
val sensors = mutableListOf<Sensor>()
input.lineSequence()
.forEach { line ->
val (sensorPosition, beaconPosition) = parseLine(line)
beacons.add(beaconPosition)
sensors.add(Sensor(sensorPosition, sensorPosition.distanceTo(beaconPosition)))
}
return Scan(beacons, sensors)
}
}
}
private fun parseLine(line: String): Pair<Position, Position> {
val (_, sx, sy, bx, by) = LINE_REGEX.find(line)!!.groupValues
return Position(sx.toInt(), sy.toInt()) to Position(bx.toInt(), by.toInt())
}
private data class Position(val x: Int, val y: Int) {
fun distanceTo(other: Position): Int {
return abs(x - other.x) + abs(y - other.y)
}
}
private data class Sensor(val position: Position, val range: Int) {
val minX = position.x - range
val maxX = position.x + range
operator fun contains(otherPosition: Position) =
coverage(otherPosition.y)?.let { otherPosition.x in it } ?: false
fun coverage(y: Int): IntRange? {
val vDist = abs(y - position.y)
if (vDist > range) return null
val extent = range - vDist
return (position.x - extent)..(position.x + extent)
}
}
private class SearchRange private constructor(val ranges: List<IntRange>) {
constructor(range: IntRange) : this(listOf(range))
val size: Int get() = ranges.sumOf { it.size }
fun asSequence() = ranges.asSequence().flatMap { it.asSequence() }
fun remove(range: IntRange): SearchRange {
if (ranges.isEmpty()) return this
return SearchRange(ranges.flatMap { it.remove(range) })
}
private fun IntRange.remove(other: IntRange): List<IntRange> = buildList {
(first .. minOf(other.first - 1, last))
.takeUnless { it.isEmpty() }
?.let(::add)
(maxOf(other.last + 1, first)..endInclusive)
.takeUnless { it.isEmpty() }
?.let(::add)
}
}
val IntRange.size: Int get() = last - first + 1
}
| [
{
"class_path": "jcornaz__aoc-kotlin-2022__979c00c/Day15.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15 {\n public static final Day15 INSTANCE;\n\n private static final kotlin.text.Regex LINE_REGEX;\n\n private Day15();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
jcornaz__aoc-kotlin-2022__979c00c/src/main/kotlin/Day02.kt | object Day02 {
private val plays = Play.values().asSequence()
private val results = Result.values().asSequence()
enum class Play(val symbol: String, val score: Int) {
Rock("A", 1),
Paper("B", 2),
Scissors("C", 3),
}
enum class Result(val symbol: String, val score: Int) {
Lose("X", 0),
Draw("Y", 3),
Win("Z", 6),
}
fun part1(input: String): Int =
input.lines().sumOf(::part1ScoreOf)
fun part2(input: String): Int =
input.lineSequence().sumOf(::part2ScoreOf)
private fun parsePlay(input: String): Play = plays.first { it.symbol == input }
private fun parseResult(input: String): Result = results.first { it.symbol == input }
private fun part1ScoreOf(line: String): Int {
val (opponent, me) = line.split(' ')
return score(
parsePlay(opponent),
when (me) {
"X" -> Play.Rock
"Y" -> Play.Paper
else -> Play.Scissors
}
)
}
private fun part2ScoreOf(line: String): Int {
val (opponent, wanted) = line.split(' ')
.let { (op, wanted) -> parsePlay(op) to parseResult(wanted) }
val me = whatToPlay(opponent, wanted)
return wanted.score + me.score
}
private fun score(opponent: Play, me: Play): Int =
resultOf(opponent, me).score + me.score
private fun resultOf(opponent: Play, me: Play): Result =
results.first { whatToPlay(opponent, it) == me }
fun whatToPlay(opponent: Play, wantedResult: Result): Play = when (wantedResult) {
Result.Draw -> opponent
Result.Win -> when (opponent) {
Play.Rock -> Play.Paper
Play.Paper -> Play.Scissors
Play.Scissors -> Play.Rock
}
Result.Lose -> plays.first { whatToPlay(it, Result.Win) == opponent }
}
}
| [
{
"class_path": "jcornaz__aoc-kotlin-2022__979c00c/Day02$Play.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02$Play extends java.lang.Enum<Day02$Play> {\n private final java.lang.String symbol;\n\n private final int score;\n\n public static final Day02$Play Rock;\n\n public static ... |
jcornaz__aoc-kotlin-2022__979c00c/src/main/kotlin/Day16.kt | import java.util.*
private typealias ValveId = String
object Day16 {
private val LINE_REGEX = Regex("Valve ([A-Z]+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)")
fun part1(input: String, time: Int = 30): Int {
val valves = input.lineSequence()
.map(::parseValve)
.toMap()
val solver = Solver(maxStep = time, initialState = SearchState(valves.keys.first(), valves.mapValues { false }, 0, null), valves = valves)
return solver.solve()
}
private fun parseValve(input: String): Pair<ValveId, Valve> {
val (_, valve, rate, edges) =LINE_REGEX.find(input)?.groupValues ?: error("failed to match input line: $input")
return valve to Valve(rate.toInt(), edges.split(", "))
}
@Suppress("UNUSED_PARAMETER")
fun part2(input: String): Long = TODO()
data class Valve(val rate: Int, val connections: Collection<ValveId>)
class SearchState(val valve: ValveId, val openValves: Map<ValveId, Boolean>, val step: Int, val parent: SearchState?) {
override fun equals(other: Any?): Boolean {
if (other !is SearchState) return false
return valve == other.valve && openValves == other.openValves
}
override fun hashCode(): Int = valve.hashCode() + 31 * openValves.hashCode()
override fun toString(): String = "$valve at $step (${openValves.filterValues { it }.keys})"
}
class Solver(val maxStep: Int, private val initialState: SearchState, private val valves: Map<ValveId, Valve>) {
private val visitedStates: MutableSet<SearchState> = mutableSetOf()
private val priorityQueue: PriorityQueue<Pair<SearchState, Int>> = PriorityQueue<Pair<SearchState, Int>>(compareBy { -it.second })
.apply { add(initialState to 0) }
private fun getSuccessorState(searchState: SearchState, score: Int): Sequence<Pair<SearchState, Int>> {
if (searchState.step >= maxStep) return emptySequence()
val currentValve = valves[searchState.valve] ?: return emptySequence()
val nextStep = searchState.step + 1
val connectedStates = currentValve.connections.asSequence().map {
SearchState(it, searchState.openValves, nextStep, searchState) to score
}
return if(searchState.openValves[searchState.valve] == false && currentValve.rate != 0)
connectedStates + (SearchState(searchState.valve, searchState.openValves + (searchState.valve to true), nextStep, searchState.parent) to computeScore(score, nextStep, currentValve.rate))
else
connectedStates
}
private fun computeScore(score: Int, step: Int, rate: Int) = score + ((maxStep - step) * rate)
fun solve() : Int {
var bestStateThusFar = initialState to 0
while (!priorityQueue.isEmpty()) {
val (state, score) = priorityQueue.poll()
visitedStates.add(state)
if (bestStateThusFar.second < score) bestStateThusFar = state to score
getSuccessorState(state, score)
.filter { it.first !in visitedStates }
.forEach { priorityQueue.add(it) }
}
val seq = sequence {
var currentState: SearchState = bestStateThusFar.first
while (currentState.parent != null) {
yield(currentState)
currentState = currentState.parent!!
}
}
seq.toList().reversed().forEach(::println)
return bestStateThusFar.second
}
}
}
| [
{
"class_path": "jcornaz__aoc-kotlin-2022__979c00c/Day16$Solver$solve$seq$1.class",
"javap": "Compiled from \"Day16.kt\"\nfinal class Day16$Solver$solve$seq$1 extends kotlin.coroutines.jvm.internal.RestrictedSuspendLambda implements kotlin.jvm.functions.Function2<kotlin.sequences.SequenceScope<? super Day16... |
jcornaz__aoc-kotlin-2022__979c00c/src/main/kotlin/Day12.kt | object Day12 {
@Suppress("UNUSED_PARAMETER")
fun part1(input: String): Long = TODO()
@Suppress("UNUSED_PARAMETER")
fun part2(input: String): Long = TODO()
private const val START_CHARACTER = 'S'
private const val GOAL_CHARACTER = 'E'
fun findPath(input: String): String {
val map = parseMap(input)
var currentState = findInitialState(map)
val maxY = map.size - 1
val maxX = map.first().size - 1
val outputMap: List<MutableList<Char>> = map.map { it.mapTo(mutableListOf()) { '.' } }
while (map[currentState.y][currentState.x] != GOAL_CHARACTER) {
print(map[currentState.y][currentState.x])
val (direction, nextState) = getSuccessors(currentState, maxX, maxY)
// .filter { (_, coordinate) ->
// map[coordinate.y][coordinate.x] == GOAL_CHARACTER || map[coordinate.y][coordinate.x] - map[currentState.y][currentState.x] <= 1
// }
.maxBy { (_, coordinate) ->
val value = map[coordinate.y][coordinate.x]
if (value == GOAL_CHARACTER) 'z' + 1 else value
}
outputMap[currentState.y][currentState.x] = direction.char
currentState = nextState
}
outputMap[currentState.y][currentState.x] = GOAL_CHARACTER
return outputMap.joinToString(separator = "\n") { it.joinToString(separator = "")}
}
private fun parseMap(input: String): List<List<Char>> = input.lines().map { it.toList() }
private fun findInitialState(map: List<List<Char>>) : Coordinate =
map.withIndex()
.map { (row, l) ->
Coordinate(l.withIndex().find { (_, c) -> c == START_CHARACTER }!!.index, row)
}
.first()
private fun getSuccessors(currentCoordinate: Coordinate, maxX: Int, maxY: Int) = Direction.values()
.map { it to it.getNextSquare(currentCoordinate) }
.filter { (_, target) -> target.x in (0 .. maxX) && target.y in (0 .. maxY) }
class Coordinate(val x: Int, val y: Int)
enum class Direction(val char: Char) {
UP('^') {
override fun getNextSquare(currentCoordinate: Coordinate) =
Coordinate(currentCoordinate.x, currentCoordinate.y - 1)
},
DOWN('v') {
override fun getNextSquare(currentCoordinate: Coordinate) =
Coordinate(currentCoordinate.x, currentCoordinate.y + 1)
},
LEFT('<') {
override fun getNextSquare(currentCoordinate: Coordinate): Coordinate =
Coordinate(currentCoordinate.x - 1, currentCoordinate.y)
},
RIGHT('>') {
override fun getNextSquare(currentCoordinate: Coordinate) =
Coordinate(currentCoordinate.x + 1, currentCoordinate.y)
};
abstract fun getNextSquare(currentCoordinate: Coordinate) : Coordinate
}
}
| [
{
"class_path": "jcornaz__aoc-kotlin-2022__979c00c/Day12$Direction$DOWN.class",
"javap": "Compiled from \"Day12.kt\"\nfinal class Day12$Direction$DOWN extends Day12$Direction {\n Day12$Direction$DOWN();\n Code:\n 0: aload_0\n 1: aload_1\n 2: iload_2\n 3: bipush 118\n ... |
jcornaz__aoc-kotlin-2022__979c00c/src/main/kotlin/Day13.kt | import java.lang.StringBuilder
object Day13 {
fun part1(input: String): Int =
input.split("\n\n").withIndex()
.filter { (_, both) ->
isInCorrectOrder(both.lines().first(), both.lines().last())!!
}
.sumOf { it.index + 1 }
@Suppress("UNUSED_PARAMETER")
fun part2(input: String): Int {
val dividers = listOf("[[2]]", "[[6]]")
val sorted = (input.lines() + dividers)
.filter { it.isNotBlank() }
.sortedWith { left, right ->
isInCorrectOrder(left, right)
?.let { if (it) -1 else 1 }
?: 0
}
return dividers.map { sorted.indexOf(it) + 1 }.fold(1) { a, b -> a * b }
}
fun isInCorrectOrder(left: String, right: String): Boolean? {
return if (left.startsWith("[") || right.startsWith("[")) {
val leftArray = left.toArray()
val rightArray = right.toArray()
leftArray.zip(rightArray).forEach { (a, b) ->
isInCorrectOrder(a, b)?.let { return it }
}
isInCorrectOrder(leftArray.size, rightArray.size)
} else {
isInCorrectOrder(left.toInt(), right.toInt())
}
}
private fun isInCorrectOrder(left: Int, right: Int): Boolean? =
if (left < right) true else if (left > right) false else null
private fun String.toArray(): List<String> {
if (!startsWith("[")) return listOf(this)
return buildList {
var nestedLevel = 0
val current = StringBuilder()
removePrefix("[")
.forEach { char ->
if ((char == ',' || char == ']') && nestedLevel == 0 && current.isNotBlank()) {
add(current.toString())
current.clear()
} else {
current.append(char)
if (char == '[') {
nestedLevel += 1
} else if (char == ']') {
nestedLevel -= 1
}
}
}
}
}
} | [
{
"class_path": "jcornaz__aoc-kotlin-2022__979c00c/Day13.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13 {\n public static final Day13 INSTANCE;\n\n private Day13();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\... |
jcornaz__aoc-kotlin-2022__979c00c/src/main/kotlin/Day05.kt | import java.util.*
object Day05 {
fun part1(input: String): String {
val stacks = input.initialState()
input.instructions().forEach { instruction ->
repeat(instruction.count) {
stacks[instruction.to].push(stacks[instruction.from].pop())
}
}
return topOfStackToString(stacks)
}
fun part2(input: String): String {
val stacks = input.initialState()
input.instructions().forEach { instruction ->
(1..instruction.count)
.map { stacks[instruction.from].pop() }
.reversed()
.forEach { stacks[instruction.to].push(it) }
}
return topOfStackToString(stacks)
}
private fun topOfStackToString(stacks: List<Stack<Char>>): String =
stacks
.map { it.pop() }
.joinToString(separator = "")
private fun String.initialState(): List<Stack<Char>> {
val indices = generateSequence(1) { it + 4 }
val initialStateLines = lines().takeWhile { "1" !in it }
return indices
.takeWhile { it < initialStateLines.first().length }
.map { i ->
val stack = Stack<Char>()
initialStateLines.mapNotNull { line -> line.getOrNull(i)?.takeIf { !it.isWhitespace() } }
.forEach(stack::push)
stack.reverse()
stack
}.toList()
}
private fun String.instructions(): Sequence<Instruction> =
lineSequence()
.dropWhile { it.isNotBlank() }
.drop(1)
.map {
val (n, _, from, _, to) = it.removePrefix("move ").split(" ")
Instruction(n.toInt(), from.toInt() - 1, to.toInt() - 1)
}
}
data class Instruction(val count: Int, val from: Int, val to: Int)
| [
{
"class_path": "jcornaz__aoc-kotlin-2022__979c00c/Day05.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class Day05 {\n public static final Day05 INSTANCE;\n\n private Day05();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\... |
pkleczek__Kotlin_Koans__48e2cc5/Generics/Generic functions/src/Task.kt | fun <T, C : MutableCollection<T>> Iterable<T>.partitionTo(
first: C,
second: C,
predicate: (T) -> Boolean
): Pair<C, C> =
this.partition(predicate)
.let {
first.addAll(it.first)
second.addAll(it.second)
first to second
}
fun partitionWordsAndLines() {
val (words, lines) = listOf("a", "a b", "c", "d e")
.partitionTo(ArrayList(), ArrayList()) { s -> !s.contains(" ") }
check(words == listOf("a", "c"))
check(lines == listOf("a b", "d e"))
}
fun partitionLettersAndOtherSymbols() {
val (letters, other) = setOf('a', '%', 'r', '}')
.partitionTo(HashSet(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z' }
check(letters == setOf('a', 'r'))
check(other == setOf('%', '}'))
}
| [
{
"class_path": "pkleczek__Kotlin_Koans__48e2cc5/TaskKt.class",
"javap": "Compiled from \"Task.kt\"\npublic final class TaskKt {\n public static final <T, C extends java.util.Collection<T>> kotlin.Pair<C, C> partitionTo(java.lang.Iterable<? extends T>, C, C, kotlin.jvm.functions.Function1<? super T, java.l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.