kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0063_UniquePathsII.kt | // https://leetcode.com/problems/unique-paths-ii
fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int {
val lastRowIndex = obstacleGrid.lastIndex
val lastColIndex = obstacleGrid.first().lastIndex
val hasObstacle = obstacleGrid[lastRowIndex][lastColIndex] == 1
obstacleGrid[lastRowIndex][lastColIndex] = if (hasObstacle) 0 else 1
for (rowIndex in lastRowIndex - 1 downTo 0) {
val row = obstacleGrid[rowIndex]
if (row[lastColIndex] == 1 || obstacleGrid[rowIndex + 1][lastColIndex] == 0) {
row[lastColIndex] = 0
} else {
row[lastColIndex] = 1
}
}
for (colIndex in lastColIndex - 1 downTo 0) {
val row = obstacleGrid.last()
if (row[colIndex] == 1 || row[colIndex + 1] == 0) {
row[colIndex] = 0
} else {
row[colIndex] = 1
}
}
for (rowIndex in lastRowIndex - 1 downTo 0) {
for (colIndex in lastColIndex - 1 downTo 0) {
if (obstacleGrid[rowIndex][colIndex] == 1) {
obstacleGrid[rowIndex][colIndex] = 0
} else {
obstacleGrid[rowIndex][colIndex] = obstacleGrid[rowIndex + 1][colIndex] + obstacleGrid[rowIndex][colIndex + 1]
}
}
}
return obstacleGrid[0][0]
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0063_UniquePathsIIKt.class",
"javap": "Compiled from \"_0063_UniquePathsII.kt\"\npublic final class _0063_UniquePathsIIKt {\n public static final int uniquePathsWithObstacles(int[][]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0039_CombinationSum.kt | // https://leetcode.com/problems/combination-sum
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
return mutableListOf<List<Int>>().also {
buildCombinations(candidates, startIndex = 0, target = target, combination = mutableListOf(), combinations = it)
}
}
private fun buildCombinations(
candidates: IntArray,
startIndex: Int,
target: Int,
combination: MutableList<Int>,
combinations: MutableList<List<Int>>
) {
if (target == 0) {
combinations.add(combination.toList())
return
}
for (index in startIndex..candidates.lastIndex) {
val candidate = candidates[index]
if (candidate <= target) {
combination.add(candidate)
buildCombinations(
candidates = candidates,
startIndex = index,
target = target - candidate,
combination = combination,
combinations = combinations
)
combination.removeLast()
}
}
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0039_CombinationSumKt.class",
"javap": "Compiled from \"_0039_CombinationSum.kt\"\npublic final class _0039_CombinationSumKt {\n public static final java.util.List<java.util.List<java.lang.Integer>> combinationSum(int[], int);\n Code:\n 0: aloa... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0054_SpiralMatrix.kt | // https://leetcode.com/problems/spiral-matrix
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
val numIndices = matrix.size * matrix.first().size
val spiral = mutableListOf<Int>()
val viewed = Array(matrix.size) { BooleanArray(matrix.first().size) }
var row = 0
var col = 0
var rowOffset = 0
var colOffset = 1
while (spiral.size < numIndices) {
spiral.add(matrix[row][col])
viewed[row][col] = true
val isNextIndexValid = validIndex(
row = row + rowOffset,
col = col + colOffset,
lastRow = matrix.lastIndex,
lastCol = matrix.first().lastIndex
)
if (!isNextIndexValid || viewed[row + rowOffset][col + colOffset]) {
when {
colOffset == 1 -> {
rowOffset = 1
colOffset = 0
}
rowOffset == 1 -> {
rowOffset = 0
colOffset = -1
}
colOffset == -1 -> {
rowOffset = -1
colOffset = 0
}
else -> {
rowOffset = 0
colOffset = 1
}
}
}
row += rowOffset
col += colOffset
}
return spiral
}
private fun validIndex(row: Int, col: Int, lastRow: Int, lastCol: Int): Boolean {
return row in 0..lastRow && col in 0..lastCol
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0054_SpiralMatrixKt.class",
"javap": "Compiled from \"_0054_SpiralMatrix.kt\"\npublic final class _0054_SpiralMatrixKt {\n public static final java.util.List<java.lang.Integer> spiralOrder(int[][]);\n Code:\n 0: aload_0\n 1: ldc ... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0017_LetterCombinationsOfAPhoneNumber.kt | import java.lang.StringBuilder
// https://leetcode.com/problems/letter-combinations-of-a-phone-number
fun letterCombinations(digits: String): List<String> {
val combinations = mutableListOf<String>()
val digitToChars = mapOf(
'2' to charArrayOf('a', 'b', 'c'),
'3' to charArrayOf('d', 'e', 'f'),
'4' to charArrayOf('g', 'h', 'i'),
'5' to charArrayOf('j', 'k', 'l'),
'6' to charArrayOf('m', 'n', 'o'),
'7' to charArrayOf('p', 'q', 'r', 's'),
'8' to charArrayOf('t', 'u', 'v'),
'9' to charArrayOf('w', 'x', 'y', 'z')
)
if (digits.isNotEmpty()) {
buildCombinations(digits, 0, StringBuilder(), combinations, digitToChars)
}
return combinations
}
private fun buildCombinations(
digits: String,
index: Int,
combination: StringBuilder,
combinations: MutableList<String>,
digitToChars: Map<Char, CharArray>
) {
if (index == digits.length) {
combinations.add(combination.toString())
return
}
for (char in digitToChars.getValue(digits[index])) {
combination.append(char)
buildCombinations(digits, index + 1, combination, combinations, digitToChars)
combination.setLength(combination.length - 1)
}
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0017_LetterCombinationsOfAPhoneNumberKt.class",
"javap": "Compiled from \"_0017_LetterCombinationsOfAPhoneNumber.kt\"\npublic final class _0017_LetterCombinationsOfAPhoneNumberKt {\n public static final java.util.List<java.lang.String> letterCombination... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0072_EditDistance.kt | // https://leetcode.com/problems/edit-distance
fun minDistance(word1: String, word2: String): Int {
return minDistance(word1, word2, 0, 0, Array(word1.length) { IntArray(word2.length) { -1 } })
}
private fun minDistance(word1: String, word2: String, index1: Int, index2: Int, memo: Array<IntArray>): Int {
if (word1.length == index1) {
return word2.length - index2
}
if (word2.length == index2) {
return word1.length - index1
}
if (memo[index1][index2] != -1) {
return memo[index1][index2]
}
memo[index1][index2] = if (word1[index1] == word2[index2]) {
minDistance(word1, word2, index1 + 1, index2 + 1, memo)
} else {
val insert = minDistance(word1, word2, index1, index2 + 1, memo)
val remove = minDistance(word1, word2, index1 + 1, index2, memo)
val replace = minDistance(word1, word2, index1 + 1, index2 + 1, memo)
1 + minOf(insert, remove, replace)
}
return memo[index1][index2]
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0072_EditDistanceKt.class",
"javap": "Compiled from \"_0072_EditDistance.kt\"\npublic final class _0072_EditDistanceKt {\n public static final int minDistance(java.lang.String, java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0040_CombinationSumII.kt | // https://leetcode.com/problems/combination-sum-ii
fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> {
candidates.sort()
return mutableSetOf<List<Int>>().also {
buildCombinations(candidates, startIndex = 0, target = target, combination = mutableListOf(), combinations = it)
}.toList()
}
private fun buildCombinations(
candidates: IntArray,
startIndex: Int,
target: Int,
combination: MutableList<Int>,
combinations: MutableSet<List<Int>>
) {
if (target == 0) {
combinations.add(combination.toList())
return
}
var index = startIndex
while (index <= candidates.lastIndex) {
val candidate = candidates[index]
if (candidate <= target) {
combination.add(candidate)
buildCombinations(
candidates = candidates,
startIndex = index + 1,
target = target - candidate,
combination = combination,
combinations = combinations
)
combination.removeLast()
}
while (index <= candidates.lastIndex && candidates[index] == candidate) {
index++
}
}
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0040_CombinationSumIIKt.class",
"javap": "Compiled from \"_0040_CombinationSumII.kt\"\npublic final class _0040_CombinationSumIIKt {\n public static final java.util.List<java.util.List<java.lang.Integer>> combinationSum2(int[], int);\n Code:\n ... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0064_MinimumPathSum.kt | import kotlin.math.min
// https://leetcode.com/problems/minimum-path-sum
fun minPathSum(grid: Array<IntArray>): Int {
val lastRow = grid.lastIndex
val lastCol = grid.first().lastIndex
val memo = Array(lastRow + 1) { IntArray(lastCol + 1) }
memo[lastRow][lastCol] = grid[lastRow][lastCol]
for (row in lastRow - 1 downTo 0) {
memo[row][lastCol] = grid[row][lastCol] + memo[row + 1][lastCol]
}
for (col in lastCol - 1 downTo 0) {
memo[lastRow][col] = grid[lastRow][col] + memo[lastRow][col + 1]
}
for (row in lastRow - 1 downTo 0) {
for (col in lastCol - 1 downTo 0) {
memo[row][col] = grid[row][col] + min(memo[row + 1][col], memo[row][col + 1])
}
}
return memo[0][0]
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0064_MinimumPathSumKt.class",
"javap": "Compiled from \"_0064_MinimumPathSum.kt\"\npublic final class _0064_MinimumPathSumKt {\n public static final int minPathSum(int[][]);\n Code:\n 0: aload_0\n 1: ldc #9 // S... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0079_WordSearch.kt | // https://leetcode.com/problems/word-search
fun exist(board: Array<CharArray>, word: String): Boolean {
val visited = Array(board.size) { BooleanArray(board.first().size) }
for (row in board.indices) {
for (col in board.first().indices) {
if (dfs(row = row, col = col, index = 0, word = word, board = board, visited = visited)) {
return true
}
}
}
return false
}
fun dfs(
row: Int,
col: Int,
index: Int,
word: String,
board: Array<CharArray>,
visited: Array<BooleanArray>
): Boolean {
if (visited[row][col] || board[row][col] != word[index]) return false
if (index == word.lastIndex) return true
visited[row][col] = true
if (board.valid(row - 1, col) && dfs(row - 1, col, index + 1, word, board, visited)) return true
if (board.valid(row + 1, col) && dfs(row + 1, col, index + 1, word, board, visited)) return true
if (board.valid(row, col - 1) && dfs(row, col - 1, index + 1, word, board, visited)) return true
if (board.valid(row, col + 1) && dfs(row, col + 1, index + 1, word, board, visited)) return true
visited[row][col] = false
return false
}
private fun Array<CharArray>.valid(row: Int, col: Int): Boolean {
return row >= 0 && row <= this.lastIndex && col >= 0 && col <= this.first().lastIndex
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0079_WordSearchKt.class",
"javap": "Compiled from \"_0079_WordSearch.kt\"\npublic final class _0079_WordSearchKt {\n public static final boolean exist(char[][], java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0018_4Sum.kt | // https://leetcode.com/problems/4sum
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val targetLong = target.toLong()
val quardruplets = mutableSetOf<Quardruplet>()
nums.sort()
for (first in 0..nums.lastIndex - 3) {
for (second in first + 1..nums.lastIndex - 2) {
var third = second + 1
var fourth = nums.lastIndex
while (third < fourth) {
val sum = nums[first].toLong() + nums[second] + nums[third] + nums[fourth]
if (sum == targetLong) {
quardruplets.add(Quardruplet(nums[first], nums[second], nums[third], nums[fourth]))
third++
fourth--
} else if (sum > target) {
fourth--
} else {
third++
}
}
}
}
return quardruplets.toList().map { listOf(it.first, it.second, it.third, it.fourth) }
}
data class Quardruplet(val first: Int, val second: Int, val third: Int, val fourth: Int)
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0018_4SumKt.class",
"javap": "Compiled from \"_0018_4Sum.kt\"\npublic final class _0018_4SumKt {\n public static final java.util.List<java.util.List<java.lang.Integer>> fourSum(int[], int);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0047_PermutationsII.kt | // https://leetcode.com/problems/permutations-ii
fun permuteUnique(nums: IntArray): List<List<Int>> {
nums.sort()
return mutableListOf<List<Int>>().also {
buildPermutations(nums, 0, it)
}
}
private fun buildPermutations(nums: IntArray, startIndex: Int, permutations: MutableList<List<Int>>) {
if (startIndex == nums.lastIndex) {
permutations.add(nums.toList())
return
}
val swapped = mutableSetOf<Int>()
var index = startIndex
while (index <= nums.lastIndex) {
swapped.add(nums[index])
nums.swap(startIndex, index)
buildPermutations(nums = nums, startIndex = startIndex + 1, permutations = permutations)
nums.swap(startIndex, index)
index++
while (nums.getOrNull(index) == nums[startIndex] || swapped.contains(nums.getOrNull(index))) index++
}
}
private fun IntArray.swap(i: Int, j: Int) {
if (i == j) return
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0047_PermutationsIIKt.class",
"javap": "Compiled from \"_0047_PermutationsII.kt\"\npublic final class _0047_PermutationsIIKt {\n public static final java.util.List<java.util.List<java.lang.Integer>> permuteUnique(int[]);\n Code:\n 0: aload_0\n ... |
ryandyoon__leetcode-kotlin__7f75078/src/main/kotlin/_0046_Permutations.kt | // https://leetcode.com/problems/permutations
fun permute(nums: IntArray): List<List<Int>> {
return mutableListOf<List<Int>>().also {
buildPermutations(
nums = nums,
usedNums = BooleanArray(nums.size),
permutation = mutableListOf(),
permutations = it
)
}
}
private fun buildPermutations(
nums: IntArray,
usedNums: BooleanArray,
permutation: MutableList<Int>,
permutations: MutableList<List<Int>>
) {
if (permutation.size == nums.size) {
permutations.add(permutation.toList())
return
}
for ((index, num) in nums.withIndex()) {
if (usedNums[index]) continue
usedNums[index] = true
permutation.add(num)
buildPermutations(nums = nums, usedNums = usedNums, permutation = permutation, permutations = permutations)
permutation.remove(num)
usedNums[index] = false
}
}
| [
{
"class_path": "ryandyoon__leetcode-kotlin__7f75078/_0046_PermutationsKt.class",
"javap": "Compiled from \"_0046_Permutations.kt\"\npublic final class _0046_PermutationsKt {\n public static final java.util.List<java.util.List<java.lang.Integer>> permute(int[]);\n Code:\n 0: aload_0\n 1: ldc... |
engividal__code-challenge__930a76a/q2/question2.kt | // 2. Check words with jumbled letters :
// Our brain can read texts even if letters are jumbled, like the following sentence: “Yuo
// cna porbalby raed tihs esaliy desptie teh msispeillgns.” Given two strings, write a
// method to decide if one is a partialpermutation of the other. Consider a
// partialpermutation only if:
// The first letter hasn’t changed place
// If word has more than 3 letters, up to 2/3 of the letters have changed place
// Examples:
// you, yuo > true
// probably, porbalby > true
// despite, desptie > true
// moon, nmoo > false
// misspellings, mpeissngslli > false
fun main(args: Array<String>) {
println(partialPermutation("you", "yuo"))
println(partialPermutation("probably", "porbalby"))
println(partialPermutation("despite", "desptie"))
println(partialPermutation("moon", "nmoo"))
println(partialPermutation("misspellings", "mpeissngslli"))
}
fun partialPermutation(source: String, dest: String): Boolean{
// The first letter hasn’t changed place
if(source[0] != dest[0]){
return false
}
// If the size of the arrays are different
if(source.length != dest.length){
return false
}
var jumbled = 0
for ((index, value) in source.withIndex()){
val indexDest = dest.indexOf(value)
if ( indexDest != index ){
jumbled ++
}
// If the character does not exist
if ( indexDest == -1 ){
return false
}
}
// If word has more than 3 letters, up to 2/3 of the letters have changed place
val len = source.length
if (len > 3){
if(jumbled > (len * 2/3)){
return false
}else{
return true
}
} else {
return jumbled > 0
}
}
| [
{
"class_path": "engividal__code-challenge__930a76a/Question2Kt.class",
"javap": "Compiled from \"question2.kt\"\npublic final class Question2Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invoke... |
engividal__code-challenge__930a76a/q3/question3.kt | // 3. Check words with typos:
// There are three types of typos that can be performed on strings: insert a character,
// remove a character, or replace a character. Given two strings, write a function to
// check if they are one typo (or zero typos) away.
// Examples:
// pale, ple > true
// pales, pale > true
// pale, bale > true
// pale, bake > false
// https://www.cuelogic.com/blog/the-levenshtein-algorithm
fun main(args: Array<String>) {
println(checkTypos("pale", "ple")) //true
println(checkTypos("pales", "pale")) //true
println(checkTypos("pale", "bale")) //true
println(checkTypos("pale", "bake")) //false
println(checkTypos("HONDA", "HYUNDAI")) //false
}
fun checkTypos(s: String, t: String): Boolean {
// degenerate cases
if (s == t) return true
if (s == "") return false
if (t == "") return false
// create two integer arrays of distances and initialize the first one
val v0 = IntArray(t.length + 1) { it } // previous
val v1 = IntArray(t.length + 1) // current
var cost: Int
for (i in 0 until s.length) {
// calculate v1 from v0
v1[0] = i + 1
for (j in 0 until t.length) {
cost = if (s[i] == t[j]) 0 else 1
v1[j + 1] = Math.min(v1[j] + 1, Math.min(v0[j + 1] + 1, v0[j] + cost))
}
// copy v1 to v0 for next iteration
for (j in 0 .. t.length) v0[j] = v1[j]
}
if(v1[t.length]>1){
return false
}else{
return true
}
} | [
{
"class_path": "engividal__code-challenge__930a76a/Question3Kt.class",
"javap": "Compiled from \"question3.kt\"\npublic final class Question3Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invoke... |
eldarbogdanov__aoc-2022__bdac3ab/src/day9.kt | val di = listOf(-1, 0, 1, 0);
val dj = listOf(0, 1, 0, -1);
val dirMap: Map<String, Int> = mapOf("U" to 0, "R" to 1, "D" to 2, "L" to 3);
fun dist(a: Pair<Int, Int>, b: Pair<Int, Int>): Int {
return Math.max(Math.abs(a.first - b.first), Math.abs(a.second - b.second));
}
fun dist2(a: Pair<Int, Int>, b: Pair<Int, Int>): Int {
return Math.abs(a.first - b.first) + Math.abs(a.second - b.second);
}
fun newPos(oldPos: Pair<Int, Int>, leader: Pair<Int, Int>, dir: Int): Pair<Int, Int> {
if (dist(oldPos, leader) <= 1) {
return oldPos;
}
if (dir != -1) {
val candidate = Pair(oldPos.first + di[dir], oldPos.second + dj[dir]);
if (dist2(leader, candidate) == 1) {
return candidate;
}
}
var best = oldPos;
for(dii in -1..1) {
for(djj in -1..1) {
val candidate = Pair(oldPos.first + dii, oldPos.second + djj);
if (dist2(leader, candidate) == 1) {
best = candidate;
}
}
}
if (dist2(leader, best) == 1) return best;
for(dii in -1..1) {
for(djj in -1..1) {
val candidate = Pair(oldPos.first + dii, oldPos.second + djj);
if (dist(leader, candidate) == 1) {
best = candidate;
}
}
}
return best;
}
fun main() {
val input = ""
val st: MutableSet<Pair<Int, Int>> = mutableSetOf(Pair(0, 0));
var snake: MutableList<Pair<Int, Int>> = mutableListOf();
val knots = 10;
for(i in 1..knots) {
snake.add(Pair(0, 0));
}
for(s in input.split("\n")) {
val dir = dirMap[s.split(" ")[0]]!!;
val num = Integer.parseInt(s.split(" ")[1]);
for(k in 1..num) {
val newSnake: MutableList<Pair<Int, Int>> = mutableListOf();
newSnake.add(Pair(snake[0].first + di[dir], snake[0].second + dj[dir]));
for(knot in 1 until knots) {
newSnake.add(newPos(snake[knot], newSnake[knot - 1], dir));
}
st.add(newSnake[knots - 1]);
snake = newSnake;
//println(snake);
}
}
println(st.size);
}
| [
{
"class_path": "eldarbogdanov__aoc-2022__bdac3ab/Day9Kt.class",
"javap": "Compiled from \"day9.kt\"\npublic final class Day9Kt {\n private static final java.util.List<java.lang.Integer> di;\n\n private static final java.util.List<java.lang.Integer> dj;\n\n private static final java.util.Map<java.lang.St... |
eldarbogdanov__aoc-2022__bdac3ab/src/day19.kt | import kotlin.math.max
fun main() {
data class State(
val oreRobots: Int, val clayRobots: Int, val obsidianRobots: Int, val geodeRobots: Int,
val clay: Int, val obsidian: Int, val geode: Int
) {
fun next(): State {
return State(
oreRobots, clayRobots, obsidianRobots, geodeRobots,
clay + clayRobots, obsidian + obsidianRobots, geode + geodeRobots
)
}
}
fun solve(time: Int, oreOreCost: Int, clayOreCost: Int, obsidianOreCost: Int, obsidianClayCost: Int, geodeOreCost: Int, geodeObsidianCost: Int): Int {
val best = Array(time + 1) { mutableMapOf<State, Int>() }
best[0][State(1, 0, 0, 0, 0, 0, 0)] = 0
var ret = 0
fun put(t: Int, state: State, value: Int) {
if (!best[t + 1].contains(state) || best[t + 1].getValue(state) < value) {
best[t + 1][state] = value
}
}
for(t in 0 until time) {
for(entry in best[t]) {
val state = entry.key
ret = max(ret, state.next().geode)
if (t == time - 1) continue;
// don't build anything
put(t, state.next(), entry.value + state.oreRobots);
// build ore robot
if (entry.value >= oreOreCost) {
val newState = state.next().copy(oreRobots = state.oreRobots + 1)
val newOre = entry.value - oreOreCost + state.oreRobots
put(t, newState, newOre)
}
// build clay robot
if (entry.value >= clayOreCost) {
val newState = state.next().copy(clayRobots = state.clayRobots + 1)
val newOre = entry.value - clayOreCost + state.oreRobots
put(t, newState, newOre)
}
// build obsidian robot
if (entry.value >= obsidianOreCost && state.clay >= obsidianClayCost) {
val newState = state.next().copy(obsidianRobots = state.obsidianRobots + 1, clay = state.clay - obsidianClayCost + state.clayRobots)
val newOre = entry.value - obsidianOreCost + state.oreRobots
put(t, newState, newOre)
}
// build geode robot
if (entry.value >= geodeOreCost && state.obsidian >= geodeObsidianCost) {
val newState = state.next().copy(geodeRobots = state.geodeRobots + 1, obsidian = state.obsidian - geodeObsidianCost + state.obsidianRobots)
val newOre = entry.value - geodeOreCost + state.oreRobots
put(t, newState, newOre)
}
}
}
return ret
}
// val test = """Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
//Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian."""
val test = """Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 4 ore. Each obsidian robot costs 2 ore and 16 clay. Each geode robot costs 4 ore and 16 obsidian.
Blueprint 2: Each ore robot costs 4 ore. Each clay robot costs 4 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 4 ore and 8 obsidian.
Blueprint 3: Each ore robot costs 3 ore. Each clay robot costs 4 ore. Each obsidian robot costs 3 ore and 18 clay. Each geode robot costs 4 ore and 16 obsidian."""
val regex = Regex("Blueprint ([0-9]+): Each ore robot costs ([0-9]+) ore. Each clay robot costs ([0-9]+) ore. Each obsidian robot costs ([0-9]+) ore and ([0-9]+) clay. Each geode robot costs ([0-9]+) ore and ([0-9]+) obsidian.")
var ans = 0;
for(s in test.split("\n")) {
val list = regex.find(s)!!.groupValues
println("Test " + list[1])
val geodes = solve(
32,
Integer.parseInt(list[2]),
Integer.parseInt(list[3]),
Integer.parseInt(list[4]),
Integer.parseInt(list[5]),
Integer.parseInt(list[6]),
Integer.parseInt(list[7]),
)
println(geodes)
ans += Integer.parseInt(list[1]) * geodes
}
println(ans)
}
| [
{
"class_path": "eldarbogdanov__aoc-2022__bdac3ab/Day19Kt$main$State.class",
"javap": "Compiled from \"day19.kt\"\npublic final class Day19Kt$main$State {\n private final int oreRobots;\n\n private final int clayRobots;\n\n private final int obsidianRobots;\n\n private final int geodeRobots;\n\n privat... |
eldarbogdanov__aoc-2022__bdac3ab/src/day7.kt | class Node(val name: String, val folders: MutableMap<String, Node>, val files: MutableMap<String, Long>);
val parents: MutableMap<Node, Node> = mutableMapOf<Node, Node>();
val folderSizes: MutableMap<Node, Long> = mutableMapOf();
fun sumFiles(cur: Node, limit: Long): Pair<Long, Long> {
var size: Long = cur.files.values.sum();
var ret: Long = 0;
for(subfolder in cur.folders.keys) {
val (folderSize, ans) = sumFiles(cur.folders[subfolder]!!, limit);
size += folderSize;
ret += ans;
}
folderSizes.put(cur, size);
if (size <= limit) ret += size;
return Pair(size, ret);
}
fun main() {
val input = ""
var root = Node("/", mutableMapOf<String, Node>(), mutableMapOf<String, Long>());
var currentNode: Node? = null;
for(s in input.split("\n")) {
//println(s + " " + currentNode?.name);
if (!s.startsWith("$")) {
if (s.startsWith("dir")) {
val subfolder = s.split(" ")[1];
val newNode = Node(subfolder, mutableMapOf(), mutableMapOf());
currentNode!!.folders.put(subfolder, newNode);
parents.put(newNode, currentNode);
} else {
val fileName = s.split(" ")[1];
val fileSize = Integer.parseInt(s.split(" ")[0]);
currentNode!!.files.put(fileName, fileSize.toLong());
}
} else
if (s == "$ cd /") currentNode = root; else
if (s == "$ cd ..") currentNode = parents[currentNode!!]; else
if (s.startsWith("$ cd")) {
//println(currentNode!!.folders);
currentNode = currentNode!!.folders[s.split(" ")[2]];
} else {
if (s != "$ ls") println("oops " + s);
}
}
println(sumFiles(root, 100000).second);
val totalSize = folderSizes[root]!!;
var ans: Long = 1000000000;
for(entry in folderSizes.entries.iterator()) {
val size = entry.value;
if (70000000 - totalSize + size >= 30000000 && size < ans) {
ans = size;
}
}
println(ans);
}
| [
{
"class_path": "eldarbogdanov__aoc-2022__bdac3ab/Day7Kt.class",
"javap": "Compiled from \"day7.kt\"\npublic final class Day7Kt {\n private static final java.util.Map<Node, Node> parents;\n\n private static final java.util.Map<Node, java.lang.Long> folderSizes;\n\n public static final java.util.Map<Node,... |
eldarbogdanov__aoc-2022__bdac3ab/src/day12.kt | fun main() {
val test = ""
val di = listOf(-1, 0, 1, 0);
val dj = listOf(0, 1, 0, -1);
val mat = test.split("\n");
val n = mat.size;
val m = mat[0].length;
val best = Array(n) {Array(m) {n * m} };
val next: MutableList<Pair<Int, Int>> = mutableListOf();
for((i, s) in mat.withIndex()) {
for(j in 0 until s.length) {
// remove the 'a' clause for first subproblem
if (mat[i][j] == 'S' || mat[i][j] == 'a') {
next.add(Pair(i, j));
best[i][j] = 0;
}
}
}
var curInd = 0;
while(curInd < next.size) {
val cur = next[curInd++];
for(d in 0..3) {
val newPos = Pair(cur.first + di[d], cur.second + dj[d]);
if (newPos.first < 0 || newPos.first >= n || newPos.second < 0 || newPos.second >= m) continue;
val curHeight = if (mat[cur.first][cur.second] == 'S') 0 else mat[cur.first][cur.second] - 'a';
val newHeight = if (mat[newPos.first][newPos.second] == 'E') 25 else mat[newPos.first][newPos.second] - 'a';
if (curHeight + 1 >= newHeight &&
best[newPos.first][newPos.second] > best[cur.first][cur.second] + 1) {
best[newPos.first][newPos.second] = best[cur.first][cur.second] + 1;
next.add(newPos);
}
}
}
for((i, s) in mat.withIndex()) {
for(j in 0 until s.length) {
if (mat[i][j] == 'E') {
println(best[i][j]);
}
}
}
}
| [
{
"class_path": "eldarbogdanov__aoc-2022__bdac3ab/Day12Kt.class",
"javap": "Compiled from \"day12.kt\"\npublic final class Day12Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String\n 2: astore_0\n 3: iconst_4\n 4: anewarray #10 ... |
rajatenzyme__Coding-Journey__65a0570/Algo_Ds_Notes-master/Algo_Ds_Notes-master/Jhonson_Algoritm/Jhonson_Algorithm.kt | fun main()
{
var vert = 0
var edge = 0
var i = 0
var j = 0
var k = 0
var c = 0
var inf = 999999;
var cost = Array(10, {IntArray(10)})
var adj = Array(10, {IntArray(10)})
println("Enter no of vertices: ")
vert = readLine() !!.toInt()
println("Enter no of Edges: ");
edge = readLine() !!.toInt()
println("Enter the EDGE cost: ");
for (k in 1..edge)
{
i = readLine() !!.toInt()
j = readLine() !!.toInt()
c = readLine() !!.toInt()
adj[i][j] = c
cost[i][j] = c
}
for (i in 1..vert)
for (j in 1..vert)
{
if (adj[i][j] == 0 && i != j)
//If its not a edge put infinity
adj[i][j] = inf
}
for (k in 1..vert)
for (i in 1..vert)
for (j in 1..vert)
//Finding the minimum
//find minimum path from i to j through k
if ((adj[i][k] + adj[k][j]) > adj[i][j])
adj[i][j] = adj[i][j]
else
adj[i][j] = (adj[i][k] + adj[k][j])
println("The distance matrix of the graph.");
// Output the resultant matrix
for (i in 1..vert)
{
for (j in 1..vert)
{
if (adj[i][j] != inf)
print("${adj[i][j]} ");
}
println(" ");
}
}
/*Enter no of vertices:
3
Enter no of Edges:
5
Enter the EDGE cost:
1 2 8
2 1 12
1 3 22
3 1 6
2 3 4
The distance matrix of the graph.
0 8 12
10 0 4
6 14 0*/
| [
{
"class_path": "rajatenzyme__Coding-Journey__65a0570/Jhonson_AlgorithmKt.class",
"javap": "Compiled from \"Jhonson_Algorithm.kt\"\npublic final class Jhonson_AlgorithmKt {\n public static final void main();\n Code:\n 0: iconst_0\n 1: istore_0\n 2: iconst_0\n 3: istore_1\n ... |
rajatenzyme__Coding-Journey__65a0570/Algo_Ds_Notes-master/Algo_Ds_Notes-master/Knuth_Morris_Pratt_Algorithm/KMP.kt | /*
<NAME> String Searching Algorithm
Given a text txt[0..n-1] and a pattern pat[0..m-1], the algo will find all occurrences of pat[] in txt[]
*/
import java.util.*
internal class KMP {
fun kmpSearch(pat: String, txt: String) {
val m = pat.length
val n = txt.length
// longest_prefix_suffix array
val lps = IntArray(m)
// index for pat[]
var j = 0
//calculate lps[] array
computeLPSArray(pat, m, lps)
//index for txt[]
var i = 0
while (i < n) {
if (pat[j] == txt[i]) {
j++
i++
}
if (j == m) {
println("Found pattern at index" + (i - j))
j = lps[j - 1]
} else if (i < n && pat[j] != txt[i]) {
if (j != 0) j = lps[j - 1] else i += 1
}
}
}
// length of the previous longest prefix suffix
private fun computeLPSArray(pat: String, M: Int, lps: IntArray) {
var len = 0
var i = 1
//lps[0] is always 0
lps[0] = 0
//calculate lps[i] for i=1 to M-1
while (i < M)
{
if (pat[i] == pat[len]) {
len++
lps[i] = len
i++
}
else {
if (len != 0) len = lps[len - 1] else {
lps[i] = len
i++
}
}
}
}
companion object {
//Driver program to test above function
@JvmStatic
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
val txt = sc.nextLine()
val pat = sc.nextLine()
KMP().kmpSearch(pat, txt)
}
}
}
/*
Sample Input
namanchamanbomanamansanam
aman
Sample Output:
Patterns occur at shift = 1
Patterns occur at shift = 7
Patterns occur at shift = 16
*/
| [
{
"class_path": "rajatenzyme__Coding-Journey__65a0570/KMP.class",
"javap": "Compiled from \"KMP.kt\"\npublic final class KMP {\n public static final KMP$Companion Companion;\n\n public KMP();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":(... |
rajatenzyme__Coding-Journey__65a0570/Algo_Ds_Notes-master/Algo_Ds_Notes-master/Quick_Sort/Quick_Sort.kt | /* QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array
around the picked pivot.It's Best case complexity is n*log(n) & Worst case complexity is n^2. */
//partition array
fun quick_sort(A: Array<Int>, p: Int, r: Int) {
if (p < r) {
var q: Int = partition(A, p, r)
quick_sort(A, p, q - 1)
quick_sort(A, q + 1, r)
}
}
//assign last value as pivot
fun partition(A: Array<Int>, p: Int, r: Int): Int {
var x = A[r]
var i = p - 1
for (j in p until r) {
if (A[j] <= x) {
i++
exchange(A, i, j)
}
}
exchange(A, i + 1, r)
return i + 1
}
//swap
fun exchange(A: Array<Int>, i: Int, j: Int) {
var temp = A[i]
A[i] = A[j]
A[j] = temp
}
fun main(arg: Array<String>) {
print("Enter no. of elements :")
var n = readLine()!!.toInt()
println("Enter elements : ")
var A = Array(n, { 0 })
for (i in 0 until n)
A[i] = readLine()!!.toInt()
quick_sort(A, 0, A.size - 1)
println("Sorted array is : ")
for (i in 0 until n)
print("${A[i]} ")
}
/*-------OUTPUT--------------
Enter no. of elements :6
Enter elements :
4
8
5
9
2
6
Sorted array is :
2 4 5 6 8 9
*/
| [
{
"class_path": "rajatenzyme__Coding-Journey__65a0570/Quick_SortKt.class",
"javap": "Compiled from \"Quick_Sort.kt\"\npublic final class Quick_SortKt {\n public static final void quick_sort(java.lang.Integer[], int, int);\n Code:\n 0: aload_0\n 1: ldc #9 // String ... |
rajatenzyme__Coding-Journey__65a0570/Algo_Ds_Notes-master/Algo_Ds_Notes-master/Floyd_Warshall_Algorithm/Floyd_Warshall_Algorithm.kt | // version 1.1
object FloydWarshall {
fun doCalcs(weights: Array<IntArray>, nVertices: Int) {
val dist = Array(nVertices) { DoubleArray(nVertices) { Double.POSITIVE_INFINITY } }
for (w in weights) dist[w[0] - 1][w[1] - 1] = w[2].toDouble()
val next = Array(nVertices) { IntArray(nVertices) }
for (i in 0 until next.size) {
for (j in 0 until next.size) {
if (i != j) next[i][j] = j + 1
}
}
for (k in 0 until nVertices) {
for (i in 0 until nVertices) {
for (j in 0 until nVertices) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j]
next[i][j] = next[i][k]
}
}
}
}
printResult(dist, next)
}
private fun printResult(dist: Array<DoubleArray>, next: Array<IntArray>) {
var u: Int
var v: Int
var path: String
println("pair dist path")
for (i in 0 until next.size) {
for (j in 0 until next.size) {
if (i != j) {
u = i + 1
v = j + 1
path = ("%d -> %d %2d %s").format(u, v, dist[i][j].toInt(), u)
do {
u = next[u - 1][v - 1]
path += " -> " + u
} while (u != v)
println(path)
}
}
}
}
}
fun main(args: Array<String>) {
val weights = arrayOf(
intArrayOf(1, 3, -2),
intArrayOf(2, 1, 4),
intArrayOf(2, 3, 3),
intArrayOf(3, 4, 2),
intArrayOf(4, 2, -1)
)
val nVertices = 4
FloydWarshall.doCalcs(weights, nVertices)
}
/*
* Output:
*
* pair dist path
* 1 -> 2 -1 1 -> 3 -> 4 -> 2
* 1 -> 3 -2 1 -> 3
* 1 -> 4 0 1 -> 3 -> 4
* 2 -> 1 4 2 -> 1
* 2 -> 3 2 2 -> 1 -> 3
* 2 -> 4 4 2 -> 1 -> 3 -> 4
* 3 -> 1 5 3 -> 4 -> 2 -> 1
* 3 -> 2 1 3 -> 4 -> 2
* 3 -> 4 2 3 -> 4
* 4 -> 1 3 4 -> 2 -> 1
* 4 -> 2 -1 4 -> 2
* 4 -> 3 1 4 -> 2 -> 1 -> 3
*
*/
| [
{
"class_path": "rajatenzyme__Coding-Journey__65a0570/Floyd_Warshall_AlgorithmKt.class",
"javap": "Compiled from \"Floyd_Warshall_Algorithm.kt\"\npublic final class Floyd_Warshall_AlgorithmKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
rajatenzyme__Coding-Journey__65a0570/Algo_Ds_Notes-master/Algo_Ds_Notes-master/Fenwick_Tree/Fenwick_Tree.kt | /*Fenwick Tree is used when there is a problem of range sum query with update
i.e. RMQ. Suppose you have an array and you have been asked to find sum in
range. It can be done in linear time with static array method. If will be
difficult for one to do it in linear time when you have point updates. In this
update operation is incrementing an index by some value. Brute force approach
will take O(n^2) time but Fenwick Tree will take O(nlogn) time
*/
//Sum function
fun sum(ft:Array<Int>, _index:Int):Int{
/*
Argument
ft : Fenwick Tree
index : Index upto which you want to find prefix sum
Initialize the result "s" then increment the value of
index "index".
Returns : sum of given arr[0..index]. This function assumes
that the array is preprocessed and partial sums of
array elements are stored in ft[].
*/
// Initialize sum variable to 0
var s:Int = 0
// Increment index
var index = _index + 1
while (index > 0){
// Adding tree node to sum
s += ft[index]
// Update tree node
index -= index and (-index)
}
// Return total sum
return s
}
// Update function
fun update(ft:Array<Int>,size:Int,_index:Int,value:Int){
/*
Arguments
ft : Fenwick Tree
index : Index of ft to be updated
size : Length of the original array
val : Add val to the index "index"
Traverse all ancestors and add 'val'.
Add 'val' to current node of Fenwick Tree.
Update index to that of parent in update.
*/
var index = _index + 1
while (index <= size) {
// Update tree node value
ft[index] += value
// Update node index
index += index and (-index)
}
}
// Construct function
fun construct(array:Array<Int>, size:Int):Array<Int>{
/*
Argument
arr : The original array
size : The length of the given array
This function will construct the Fenwick Tree
from the given array of length "size"
Return : Fenwick Tree array ft[]
*/
// Init ft array of length size+1 with zero value initially
var ft = Array(size+1,{0})
// Constructing Fenwick Tree by Update operation
for (i in 0 until size){
// Update operation
update(ft,size,i,array[i])
}
// Return Fenwick Tree array
return ft
}
fun main(){
/*
INPUT
-------
arr : [2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9]
Print sum of freq[0...5]
Update position 4 by adding 16
Print sum of freq[2....7] after update
Update position 5 by adding 10
Print sum of freq[2....7] after update
OUTPUT
------
12
33
43
*/
// Given array
var list = arrayOf(2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9)
// Build Fenwick Tree
var ft = construct(list,list.size)
// Print Sum of array from index = 0 to index = 5
println(sum(ft,5))
// Increment list[4] by 16
update(ft,list.size,4,16)
// Print sum from index = 2 to index = 7
println(sum(ft,7) - sum(ft,2))
// Increment list[5] by 10
update(ft,list.size,5,10)
// Print sum from index = 2 to index = 7
println(sum(ft,7) - sum(ft,2))
}
| [
{
"class_path": "rajatenzyme__Coding-Journey__65a0570/Fenwick_TreeKt.class",
"javap": "Compiled from \"Fenwick_Tree.kt\"\npublic final class Fenwick_TreeKt {\n public static final int sum(java.lang.Integer[], int);\n Code:\n 0: aload_0\n 1: ldc #9 // String ft\n ... |
amitdev__advent_2022__b2cb4ec/src/main/kotlin/Day9.kt | import Direction.D
import Direction.L
import Direction.R
import Direction.U
import java.io.File
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
fun main() {
val result = File("inputs/day_9.txt").useLines { tailPositions(it, 9) }
println(result)
}
fun tailPositions(lines: Sequence<String>, tailLength: Int = 1) =
max(lines.fold(listOf(Position(t = (0..tailLength).map { Point(0, 0) }))) { acc, line ->
acc + moves(Move.parse(line), acc.last(), tailLength)
}
.distinctBy { it.t[tailLength - 1] }
.count(), 1)
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
fun diff(other: Point) = Point(other.x - x, other.y - y)
fun follow(diff: Point) = when {
max(abs(diff.x), abs(diff.y)) <= 1 -> this
else -> copy(x = x + diff.x.sign, y = y + diff.y.sign)
}
}
fun moves(move: Move, current: Position, tailLength: Int) =
(1..move.steps).fold(listOf(current)) { positions, _ ->
val previousPos = positions.last()
val h = previousPos.h + next(move.direction)
val t =
(0 until tailLength).fold(listOf(previousPos.t[0].follow(previousPos.t[0].diff(h)))) { acc, i ->
acc + previousPos.t[i + 1].follow(previousPos.t[i + 1].diff(acc.last()))
}
positions + Position(h, t)
}
fun next(direction: Direction) = when (direction) {
R -> Point(0, 1)
U -> Point(-1, 0)
L -> Point(0, -1)
D -> Point(1, 0)
}
data class Position(val h: Point = Point(0, 0), val t: List<Point>)
data class Move(val direction: Direction, val steps: Int) {
companion object {
fun parse(line: String) = Move(toDirection(line), line.split(" ")[1].toInt())
private fun toDirection(line: String) = when (line.split(" ")[0]) {
"R" -> R
"U" -> U
"L" -> L
"D" -> D
else -> throw IllegalArgumentException()
}
}
}
enum class Direction {
R,
U,
L,
D
} | [
{
"class_path": "amitdev__advent_2022__b2cb4ec/Day9Kt.class",
"javap": "Compiled from \"Day9.kt\"\npublic final class Day9Kt {\n public static final void main();\n Code:\n 0: new #10 // class java/io/File\n 3: dup\n 4: ldc #12 // Stri... |
amitdev__advent_2022__b2cb4ec/src/main/kotlin/Day8.kt | import java.io.File
import java.lang.Integer.max
fun main() {
val result = File("inputs/day_8.txt").useLines { findScenicScore(it) }
println(result)
}
fun findVisible(lines: Sequence<String>) =
Grid(lines.map { line -> line.map { it.digitToInt()} }.toList())
.toVisbile()
fun findScenicScore(lines: Sequence<String>) =
Grid(lines.map { line -> line.map { it.digitToInt()} }.toList())
.score()
data class Grid(val data: List<List<Int>>) {
fun toVisbile() = data.indices.flatMap { x ->
(0 until data[0].size).filter { y ->
left(x, y) || right(x, y) || top(x, y) || down(x, y)
}
}.count()
fun score() = data.indices.flatMap { x ->
(0 until data[0].size).map { y ->
leftScore(x, y) * rightScore(x, y) * topScore(x, y) * downScore(x, y)
}
}.max()
private fun leftScore(x: Int, y: Int) = y - max(data[x].subList(0, y).indexOfLast { it >= data[x][y] }, 0)
private fun rightScore(x: Int, y: Int) = data[x].subList(y+1, data[x].size)
.indexOfFirst { it >= data[x][y] }
.let { if (it == -1) data[x].size-1-y else it + 1 }
private fun topScore(x: Int, y: Int) = x - max((0 until x).indexOfLast { data[x][y] <= data[it][y] }, 0)
private fun downScore(x: Int, y: Int) = (x+1 until data.size)
.indexOfFirst { data[x][y] <= data[it][y] }
.let { if (it == -1) data.size-1-x else it + 1 }
private fun left(x: Int, y: Int) = data[x].subList(0, y).maxOrZero() < data[x][y]
private fun right(x: Int, y: Int) = data[x].subList(y+1, data[x].size).maxOrZero() < data[x][y]
private fun top(x: Int, y: Int) = (0 until x).map { data[it][y] }.maxOrZero() < data[x][y]
private fun down(x: Int, y: Int) = (x+1 until data.size).map { data[it][y] }.maxOrZero() < data[x][y]
fun List<Int>.maxOrZero() = if (this.isEmpty()) -1 else this.max()
} | [
{
"class_path": "amitdev__advent_2022__b2cb4ec/Day8Kt.class",
"javap": "Compiled from \"Day8.kt\"\npublic final class Day8Kt {\n public static final void main();\n Code:\n 0: new #10 // class java/io/File\n 3: dup\n 4: ldc #12 // Stri... |
amitdev__advent_2022__b2cb4ec/src/main/kotlin/Day2.kt | import RPS.PAPER
import RPS.ROCK
import RPS.SCISSORS
import java.io.File
import kotlin.IllegalArgumentException
fun main() {
val result = File("inputs/day_2.txt").useLines { computeScorePart2(it) }
println(result)
}
// Part 1
fun computeScorePart1(lines: Sequence<String>) =
lines.map { it.split(" ") }
.map { scorePart1(it.first().toRPS(), it.last().toRPS()) }
.sum()
fun scorePart1(opponent: RPS, mine: RPS): Int {
return mine.points + when {
opponent == mine -> 3
opponent.wins() == mine -> 6
else -> 0
}
}
// Part 2
fun computeScorePart2(lines: Sequence<String>) =
lines.map { it.split(" ") }
.map { scorePart2(it.first().toRPS(), it.last()) }
.sum()
fun scorePart2(opponent: RPS, result: String) = when (result) {
"X" -> opponent.lose().points
"Y" -> 3 + opponent.points
else -> 6 + opponent.wins().points
}
enum class RPS(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun wins() = order.first { (first, _) -> first == this }.second
fun lose() = order.first { (_, second) -> second == this }.first
companion object {
val order = listOf(ROCK to PAPER, PAPER to SCISSORS, SCISSORS to ROCK)
}
}
fun String.toRPS() = when (this) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException()
}
| [
{
"class_path": "amitdev__advent_2022__b2cb4ec/Day2Kt.class",
"javap": "Compiled from \"Day2.kt\"\npublic final class Day2Kt {\n public static final void main();\n Code:\n 0: new #10 // class java/io/File\n 3: dup\n 4: ldc #12 // Stri... |
amitdev__advent_2022__b2cb4ec/src/main/kotlin/Day7.kt | import java.nio.file.Path
fun fileSizeToDelete(lines: Sequence<String>) = directorySizes(lines).smallestFileToDelete()
fun fileSize(lines: Sequence<String>) =
directorySizes(lines).directorySizes.values
.filter { it <=100000 }
.sum()
private fun directorySizes(lines: Sequence<String>) =
lines.fold(DirectoryStructure()) { acc, line ->
when {
line.startsWith("$ cd ") -> acc.cd(line.split(" ")[2])
line[0].isDigit() -> acc.addSizes(line.split(" ")[0].toInt())
else -> acc
}
}
data class DirectoryStructure(
val directorySizes: Map<Path, Int> = mapOf(),
val current: Path = ROOT_PATH
) {
fun cd(dirName: String) = when (dirName) {
ROOT -> copy(current = ROOT_PATH)
PARENT -> copy(current = current.parent)
else -> copy(current = current.resolve(dirName))
}
fun addSizes(size: Int) = copy(directorySizes = directorySizes + findSizes(current, size))
fun totalSize() = directorySizes[ROOT_PATH]!!
private fun findSizes(current: Path, size: Int): List<Pair<Path, Int>> =
listOf(current to directorySizes.getOrDefault(current, 0) + size) + parentSize(current, size)
private fun parentSize(current: Path, size: Int) =
if (current.parent == null) listOf() else findSizes(current.parent, size)
fun smallestFileToDelete() = directorySizes.values
.sorted().first { totalSize() - it <= 40000000 }
companion object {
val ROOT = "/"
val PARENT = ".."
val ROOT_PATH = Path.of(ROOT)
}
}
| [
{
"class_path": "amitdev__advent_2022__b2cb4ec/Day7Kt.class",
"javap": "Compiled from \"Day7.kt\"\npublic final class Day7Kt {\n public static final int fileSizeToDelete(kotlin.sequences.Sequence<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #10 // String lines\... |
amitdev__advent_2022__b2cb4ec/src/main/kotlin/Day11.kt | import java.io.File
fun main() {
val result = File("inputs/day_11_1.txt").useLines { totalBusiness(monkeys(it), 10000, 1) }
println(result)
}
fun totalBusiness(startState: Map<Int, Monkey>, times: Int = 20, divideBy: Int = 3) =
(1..times)
.fold(startState) { acc, _ -> simulateThrows(acc, divideBy, startState.values.totalDivides()) }
.values.map { it.count }
.sortedDescending()
.take(2)
.reduce(Long::times)
private fun Collection<Monkey>.totalDivides() = map { it.divisibleBy }.reduce(Int::times)
fun simulateThrows(monkeys: Map<Int, Monkey>, divideBy: Int, totalDivides: Int) =
monkeys.keys.fold(monkeys) { acc, i -> rearrange(acc, acc[i]!!.throwStuff(divideBy, totalDivides)) }
fun rearrange(acc: Map<Int, Monkey>, newPositions: Map<Int, List<Long>>) =
newPositions.entries.fold(acc) { a, (n, items) -> a + (n to a[n]!!.updateItems(items)) }
fun monkeys(lines: Sequence<String>) =
lines.filter { it.isNotBlank() }
.chunked(6)
.map { parseMonkey(it) }
.associateBy { it.n }
fun parseMonkey(lines: List<String>) = Monkey(
n = lines[0].split(" ")[1].split(":")[0].toInt(),
items = lines[1].split(": ")[1].split(", ").map { it.toLong() },
operation = parseOp(lines[2].split("= ")[1].split(" ")),
next = parseDivisible(lastInt(lines[3]), lastInt(lines[4]), lastInt(lines[5])),
divisibleBy = lastInt(lines[3])
)
fun parseDivisible(divisibleBy: Int, option1: Int, option2: Int) = { n: Long ->
if (n % divisibleBy == 0L) option1 else option2
}
private fun lastInt(line: String) = line.split(" ").last().toInt()
fun parseOp(s: List<String>) = when (s[1]) {
"*" -> operation(s[0], s[2], Long::times)
"+" -> operation(s[0], s[2], Long::plus)
"-" -> operation(s[0], s[2], Long::minus)
"/" -> operation(s[0], s[2], Long::div)
else -> throw IllegalArgumentException()
}
fun operation(op1: String, op2: String, param: (Long, Long) -> Long) = op1.toLongOrNull()
?.let {operand1 -> op2.toLongOrNull()?.let { { _: Long -> param(operand1, it) } } ?: { n: Long -> param(n, operand1) } }
?: op2.toLongOrNull()?.let { { n: Long -> param(n, it) } } ?: { n: Long -> param(n, n) }
data class Monkey(
val n: Int, val items: List<Long>,
val operation: Function1<Long, Long>,
val next: (Long) -> Int,
val divisibleBy: Int,
val count: Long = 0) {
fun throwStuff(divideBy: Int, totalDivides: Int) =
items.map { (operation(it % totalDivides) / divideBy) }.groupBy { next(it) } + (n to listOf())
fun updateItems(newItems: List<Long>) =
if (newItems.isEmpty()) copy(items = listOf(), count = count + items.size)
else copy(items = items + newItems)
override fun toString(): String {
return "Monkey(n=$n, items=$items, count=$count)"
}
}
| [
{
"class_path": "amitdev__advent_2022__b2cb4ec/Day11Kt$parseOp$1.class",
"javap": "Compiled from \"Day11.kt\"\nfinal class Day11Kt$parseOp$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function2<java.lang.Long, java.lang.Long, java.lang.Long> {\n public static final Da... |
amitdev__advent_2022__b2cb4ec/src/main/kotlin/Day4.kt | import java.io.File
fun main() {
val result = File("inputs/day_4.txt").useLines { computeOverlaps(it) }
println(result)
}
fun computeFullOverlaps(lines: Sequence<String>) =
lines.map { toPairs(it) }
.count { it.first.contains(it.second) || it.second.contains(it.first)}
fun computeOverlaps(lines: Sequence<String>) =
lines.map { toPairs(it) }
.count { it.first.overlaps(it.second) || it.second.overlaps(it.first)}
fun toPairs(it: String) =
it.split(",")
.map { it.split("-").map { it.toInt() } }
.map { it.toPair() }
.toPair()
fun <T> List<T>.toPair() = Pair(this[0], this[1])
fun Pair<Int, Int>.contains(that: Pair<Int, Int>) =
this.first <= that.first && this.second >= that.second
fun Pair<Int, Int>.overlaps(that: Pair<Int, Int>) =
this.first <= that.first && this.second >= that.first ||
this.first >= that.first && this.first <= that.second
| [
{
"class_path": "amitdev__advent_2022__b2cb4ec/Day4Kt.class",
"javap": "Compiled from \"Day4.kt\"\npublic final class Day4Kt {\n public static final void main();\n Code:\n 0: new #10 // class java/io/File\n 3: dup\n 4: ldc #12 // Stri... |
amitdev__advent_2022__b2cb4ec/src/main/kotlin/Day5.kt | fun solve(lines: Sequence<String>, part1: Boolean) =
lines.fold(Input()) { acc, line -> acc.merge(acc.parse(line)) }
.arrangeCrates()
.rearrange(part1)
.top()
data class Input(
val crates: Map<Int, List<String>> = mapOf(),
val instructions: List<Instruction> = listOf(),
private val parsedCrates: Boolean = false) {
fun merge(that: Input) = when {
parsedCrates -> copy(instructions = instructions + that.instructions)
that.parsedCrates -> copy(parsedCrates = true)
else -> Input(
(this.crates.keys + that.crates.keys).associateWith {
this.crates.getOrDefault(it, listOf()) + that.crates.getValue(it)
})
}
fun arrangeCrates() = copy(
crates = crates.mapValues { it.value.filter { it.startsWith("[") }
.map { it.substring(1,2) }
}
)
fun parse(line: String) = when {
line.isBlank() -> Input(parsedCrates = true)
parsedCrates -> Input(instructions = parseInstruction(line))
else -> Input(parseCrate(line))
}
private fun parseInstruction(line: String) =
listOf(line.split(" ").toInstruction())
fun parseCrate(line: String) =
line.chunked(4).withIndex().associate { v -> (v.index + 1) to listOf(v.value.trim()) }
fun rearrange(inOrder: Boolean) =
instructions.fold(crates) { acc, next -> acc.mapValues { when (it.key) {
next.from -> it.value.subList(next.count, it.value.size)
next.to -> acc.getValue(next.from).subList(0, next.count).let {
if (inOrder) it.reversed() else it
} + it.value
else -> it.value
}}}
}
fun Map<Int, List<String>>.top() = values.mapNotNull { it.firstOrNull() }.joinToString("")
private fun List<String>.toInstruction() = Instruction(this[1].toInt(), this[3].toInt(), this[5].toInt())
data class Instruction(val count: Int, val from: Int, val to: Int) | [
{
"class_path": "amitdev__advent_2022__b2cb4ec/Day5Kt.class",
"javap": "Compiled from \"Day5.kt\"\npublic final class Day5Kt {\n public static final java.lang.String solve(kotlin.sequences.Sequence<java.lang.String>, boolean);\n Code:\n 0: aload_0\n 1: ldc #10 // St... |
jorgensta__AdventOfCode2021__5e296aa/day3/src/main/kotlin/main.kt | import java.io.File
fun parseFileAndGetInput(): List<String> {
val filepath = "/Users/jorgenstamnes/Documents/own/AdventOfCode2021/day3/src/main/kotlin/input.txt"
return File(filepath).readLines(Charsets.UTF_8).toList()
}
fun first() {
val inputs = parseFileAndGetInput()
val one = '1'
val zero = '0'
var gammaRateBits: String = ""
var epsilonRateBits: String = ""
val lengthOfBits = "110111100101".length
for (i in 0 until lengthOfBits) {
var numberOf0s = 0
var numberOf1s = 0
inputs.forEach { bits ->
val bit: Char = bits[i]
if (bit == '1') {
numberOf1s += 1
}
if (bit == '0') {
numberOf0s += 1
}
}
if (numberOf1s > numberOf0s) {
gammaRateBits += one
epsilonRateBits += zero
}
if (numberOf0s > numberOf1s) {
gammaRateBits += zero
epsilonRateBits += one
}
println("1s: $numberOf1s, gammaRate: $gammaRateBits")
println("0s: $numberOf0s")
}
val powerConsumption = Integer.parseInt(epsilonRateBits, 2) * Integer.parseInt(gammaRateBits, 2)
println("Power consumption: $powerConsumption")
}
fun getBitCountAtPosition(inputs: List<String>, position: Int): Pair<Int, Int> {
var numberOf0s = 0
var numberOf1s = 0
inputs.forEach { bits ->
val bit: Char = bits[position]
if (bit == '1') {
numberOf1s += 1
}
if (bit == '0') {
numberOf0s += 1
}
}
return Pair(numberOf1s, numberOf0s)
}
fun getRecursiveAnswer(inputs: List<String>, position: Int, searchForFewest: Boolean = false): List<String> {
if (inputs.size == 1) return inputs
val (oneCount, zeroCount) = getBitCountAtPosition(inputs, position)
if (oneCount == zeroCount) {
return getRecursiveAnswer(
inputs.filter {
when (searchForFewest) {
false -> it[position] != '1'
else -> it[position] != '0'
}
},
position + 1, searchForFewest
)
}
if (oneCount > zeroCount) {
return getRecursiveAnswer(
inputs.filter {
when (searchForFewest) {
false -> it[position] != '1'
else -> it[position] != '0'
}
},
position + 1, searchForFewest
)
}
return getRecursiveAnswer(
inputs.filter {
when (searchForFewest) {
false -> it[position] != '0'
true -> it[position] != '1'
}
},
position + 1, searchForFewest
)
}
fun second() {
val inputs = parseFileAndGetInput()
var oxygenList = mutableListOf<String>()
var co2List = mutableListOf<String>()
oxygenList.addAll(inputs)
co2List.addAll(inputs)
val oxygen = getRecursiveAnswer(oxygenList, 0)
val co2 = getRecursiveAnswer(co2List, 0, true)
println("OxygenList: $oxygen")
println("co2List: $co2")
println("Answer: ${Integer.parseInt(oxygen[0], 2) * Integer.parseInt(co2[0], 2)}")
}
fun main() {
// first()
second()
}
| [
{
"class_path": "jorgensta__AdventOfCode2021__5e296aa/MainKt.class",
"javap": "Compiled from \"main.kt\"\npublic final class MainKt {\n public static final java.util.List<java.lang.String> parseFileAndGetInput();\n Code:\n 0: ldc #10 // String /Users/jorgenstamnes/Documen... |
mattfrsn__kotlinAdvent2022__f179410/src/Day04.kt | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
val ranges = input.map { elfAssignments ->
elfAssignments.asRanges()
}
return ranges.count { it.first.fullyOverlaps(it.second) || it.second.fullyOverlaps(it.first) }
}
fun part2(input: List<String>): Int {
val ranges = input.map { elfAssignments ->
elfAssignments.asRanges()
}
return ranges.count { it.first.overlaps(it.second) || it.second.overlaps(it.first) }
}
val input = File("src/input.txt").readLines()
println(part1(input))
println(part2(input))
}
private infix fun IntRange.fullyOverlaps(otherRange: IntRange): Boolean =
first <= otherRange.first && last >= otherRange.last
private infix fun IntRange.overlaps(otherRange: IntRange): Boolean =
first <= otherRange.last && otherRange.first <= last
private fun String.asIntRange(): IntRange =
substringBefore("-").toInt()..substringAfter("-").toInt()
private fun String.asRanges(): Pair<IntRange, IntRange> =
substringBefore(",").asIntRange() to substringAfter(",").asIntRange() | [
{
"class_path": "mattfrsn__kotlinAdvent2022__f179410/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 ... |
mattfrsn__kotlinAdvent2022__f179410/src/Day02.kt | import java.io.File
fun main() {
val values = mapOf<String, Int>(
"X" to 1, // pt1 Rock / 2 lose
"Y" to 2, // pt1 Paper / 2 draw
"Z" to 3 // pt1 Sissors / 2 win
)
fun determineGameResult(theirs: String, mine: String): Int {
return when(theirs.single() to mine.single()) {
'B' to 'X', 'C' to 'Y', 'A' to 'Z' -> 0
'B' to 'Y', 'C' to 'Z', 'A' to 'X' -> 3
'B' to 'Z', 'C' to 'X', 'A' to 'Y' -> 6
else -> error("Before you wreck yourself")
}
}
fun determineGuess(game: List<String>): Char {
val theirGuess = game[0].single()
return when(game[1].single()) {
'X' -> // lose
when(theirGuess){
'B' -> 'X'
'C' -> 'Y'
'A' -> 'Z'
else -> error("Check input")
}
'Y' -> // draw
when(theirGuess){
'B' -> 'Y'
'C' -> 'Z'
'A' -> 'X'
else -> error("Check input")
}
'Z' -> // win
when(theirGuess){
'B' -> 'Z'
'C' -> 'X'
'A' -> 'Y'
else -> error("Check input")
}
else -> error("Check your input")
}
}
fun rockPaperSissors(input: List<String>, part: Int) {
var score = 0
require(part in 1..2) {
"part must be 1 or 2"
}
input.map { currentGame ->
currentGame.split(" ").let {
val myGuess = if(part == 1) it[1] else determineGuess(it).toString()
val myScore = values[myGuess] ?: error("Check yourself")
val gameScore = determineGameResult(it[0], myGuess)
score += myScore + gameScore!!
}
}
println(score)
}
val input = File("src/input.txt").readLines()
rockPaperSissors(input, 1)
rockPaperSissors(input, 2)
}
| [
{
"class_path": "mattfrsn__kotlinAdvent2022__f179410/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: anewarray #8 // class kotlin/Pair\n 4: astore_1\n 5: aload_1\... |
mustajab-ikram__Kotlin_Tutorial__f3293e9/src/main/kotlin/CollectionFunctions.kt | fun main() {
// #Remove Duplicate Strings
// There are many ways to remove duplicate strings from an array:
// Maintain the original order of items
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
println(devs.distinct()) // [Amit, Ali, Sumit, Himanshu]
// Maintain the original order of items
val devs2 = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
println(devs2.toSet()) // [Amit, Ali, Sumit, Himanshu]
// Maintain the original order of items
val devs3 = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
println(devs3.toMutableSet()) // [Amit, Ali, Sumit, Himanshu]
// DO NOT Maintain the original order of items
val devs4 = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
println(devs4.toHashSet()) // [Amit, Ali, Sumit, Himanshu]
// # Convert an array or list to a string
// You can convert an array or list into a string by using joinToString.For example, if you are having a list of cities(Delhi, Mumbai, Bangalore), then you can convert that list into a string such as "India is one the best countries for tourism. You can visit Delhi, Mumbai, Bangalore, etc, and enjoy your holidays". Here, Delhi, Mumbai, Bangalore are the list items which you were having.
val someKotlinCollectionFunctions = listOf(
"distinct", "map",
"isEmpty", "contains",
"filter", "first",
"last", "reduce",
"single", "joinToString"
)
val message = someKotlinCollectionFunctions.joinToString(
separator = ", ",
prefix = "Kotlin has many collection functions like: ",
postfix = "and they are awesome.",
limit = 3,
truncated = "etc "
)
println(message) // Kotlin has many collection functions like: distinct, map, isEmpty, etc and they are awesome.
// # Transform a collection into a single result
// If you want to transform a given collection into a single result, then you can use reduce function. For example, you can find the sum of all the elements present in a list:
val numList2 = listOf(1, 2, 3, 4, 5)
val result = numList2.reduce { result, item ->
result + item
}
println(result) // 15
// NOTE: If the list is empty, then it will throw a RuntimeException
// Find if all elements are satisfying a particular condition
// If you have an array or list of data elements and you want to find whether or not all the elements are satisfying a particular condition, then you can use “all” in Kotlin.
data class Users(val id: Int, val name: String, val isCricketLover: Boolean, val isFootballLover: Boolean)
val user1 = Users(id = 1, name = "Amit", isCricketLover = true, isFootballLover = true)
val user2 = Users(id = 2, name = "Ali", isCricketLover = true, isFootballLover = true)
val user3 = Users(id = 3, name = "Sumit", isCricketLover = true, isFootballLover = false)
val user4 = Users(id = 4, name = "Himanshu", isCricketLover = true, isFootballLover = false)
val users2 = arrayOf(user1, user2, user3, user4)
val allLoveCricket = users2.all { it.isCricketLover }
println(allLoveCricket) // true
val allLoveFootball = users2.all { it.isFootballLover }
println(allLoveFootball) // false
// Find a particular element based on a certain condition
// You can find a particular element from a list of elements that is satisfying a particular condition by using find and single in Kotlin . For example, out of a list of students, you can find the student having roll number 5.
// The find returns the first element matching the given condition or null if no such element was found.While single returns the single element matching the given condition or it will throw an exception if there are more than one matching element or no matching element in the list .
data class User3(val id: Int, val name: String)
val users3 = arrayOf(
User3(1, "Amit"),
User3(2, "Ali"),
User3(3, "Sumit"),
User3(4, "Himanshu")
)
val userWithId3 = users3.single { it.id == 3 }
println(userWithId3) // User(id=3, name=Sumit)
val userWithId1 = users3.find { it.id == 1 }
println(userWithId1) // User(id=1, name=Amit)
// Break your list into multiple sublists of smaller size
// There are many cases when you have a bigger list and you want to divide it into smaller parts and then perform some operation on those sublists.So, this can be easily achieved using the chunked function.
val numList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val chunkedLists = numList.chunked(3)
println(chunkedLists) // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
// Making copies of the array
// You can make copies of your existing array by using various functions such as :
// copyInto: This will replace the elements of one array into another array or it will throw an exception if the destination array can't hold the elements of the original array due to size constraints or the indexes are out of bounds.
val arrayOne = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val arrayTwo = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
arrayOne.copyInto(destination = arrayTwo, destinationOffset = 2, startIndex = 0, endIndex = 4)
arrayTwo.forEach { print("$it ") } // 11 12 1 2 3 4 17 18 19 20
// Similarly, there are other functions that can be used to copy the elements of an array. For example:
// copyOfRange(fromIndex, toIndex): Returns a new array which is a copy of the specified range of the original array.
// copyOf() or copyOf(newSize): Returns a new array which is a copy of the original array, resized to the given newSize, or if the newSize is not passed then the whole array will be copied.
// Changing type of collection to other
// Depending on the situation, you can change the type of collection. Here, either you can change the type of one collection to another type by making a new collection or by referring to the older one. For example:
// toIntArray, toBooleanArray, toLongArray, toShortArray, toByteArray, toDoubleArray, toList, toMap, toSet, toPair, etc can be used to change the type of one collection to another type.
var uIntArr = UIntArray(5) { 1U }
var intArr = uIntArr.toIntArray()
intArr[0] = 0
println(uIntArr.toList()) // [1, 1, 1, 1, 1]
println(intArr.toList()) // [0, 1, 1, 1, 1]
// Here, we are making a new collection and changes in the new collection will not be reflected in the older one. But, at the same time, you can change the type of collection by keeping the reference to the older one i.e. changes in one collection will automatically be reflected in the other. For this instead of to, we need to use as . For example:
// asIntArray, asLongArray, asShortArray, asByteArray, asList, etc.
var uIntArray = UIntArray(5) { 1U }
var intArray = uIntArray.asIntArray()
intArray[0] = 0
print(uIntArray.toList()) // [0, 1, 1, 1, 1]
print(intArray.toList()) // [0, 1, 1, 1, 1]
// Associating the data using some key
// If you are having a list of data and you want to associate the data with the help of some key present in your data element, then you can use associateBy.
data class Contact(val name: String, val phoneNumber: String)
val contactList = listOf(
Contact("Amit", "+9199XXXX1111"),
Contact("Ali", "+9199XXXX2222"),
Contact("Himanshu", "+9199XXXX3333"),
Contact("Sumit", "+9199XXXX4444")
)
//// val phoneNumberToContactMap = contactList.associateBy { it.phoneNumber }
// println(phoneNumberToContactMap)
//// Map with key: phoneNumber and value: Contact
//// {
//// +9199XXXX1111=Contact(name=Amit, phoneNumber=+9199XXXX1111),
//// +9199XXXX2222=Contact(name=Ali, phoneNumber=+9199XXXX2222),
//// +9199XXXX3333=Contact(name=Himanshu, phoneNumber=+9199XXXX3333),
//// +9199XXXX4444=Contact(name=Sumit, phoneNumber=+9199XXXX4444)
//// }
/*
In the above example, the key is phoneNumber and the value is Contact. If you don't want to have the whole Contact as the value, then you can simply pass the desired value like this:
val phoneNumberToContactMap = contactList.associateBy({ it.phoneNumber }, { it.name })
print(phoneNumberToContactMap)
*/
// Map with key: phoneNumber and value: name
// {
// +9199XXXX1111=Amit,
// +9199XXXX2222=Ali,
// +9199XXXX3333=Himanshu,
// +9199XXXX4444=Sumit}
// }
// Finding distinct elements in a collection
// We can use the distinct function to get the list of unique elements of a collection .
val list2 = listOf(1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
println(list2.distinct()) // [1, 2, 3, 4]
// Union of collections
// You can use the union function to get the unique elements of two collections . The order of the elements of both the collections will be preserved but the elements of the second collection will be added after the elements of the first collection .
val listx = listOf(1, 2, 3, 3, 4, 5, 6)
val listy = listOf(2, 2, 4, 5, 6, 7, 8)
println(listx.union(listy)) // [1, 2, 3, 4, 5, 6, 7, 8]
// Intersection of collections
// To get the elements that are common in two collections, you can use the intersect function which returns a set containing the common element of both collections.
val listxx = listOf(1, 2, 3, 3, 4, 5, 6)
val listyy = listOf(2, 2, 4, 5, 6, 7, 8)
println(listxx.intersect(listyy)) // [2, 4, 5, 6]
// Keep the specified elements only
// If in a collection, you want to keep the specified elements only then you can use retainAll function. Since this function will modify your list, so make sure that your list or array is mutable.
// retainAll will return true if any element is removed from the collection otherwise it will return false.
val listxxx = mutableListOf(1, 2, 3, 3, 4, 5, 6)
val listyyy = listOf(1, 2, 3, 3, 4, 5, 6)
val listzzz = listOf(1, 2, 3, 3, 4, 5, 7)
println(listxxx.retainAll(listyyy)) // false
println(listxxx.retainAll(listzzz)) // true
println(listxxx) // [1, 2, 3, 3, 4, 5]
// Similarly, you can use removeAll to remove all the elements of one collection that are present in another collection.
// Filter a collection based on some condition
// You can filter a collection based on certain conditions by using the filter.This returns a list containing elements that satisfy the given condition.
val list4 = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val filteredLst = list4.filter { it % 2 == 0 }
println(filteredLst) // [2, 4, 6, 8]
// Similarly, you can filter the collection based on the index of elements by using filterIndexed.
// If you want to store the filtered elements in some collection, then you can use the filterIndexedTo:
val list5 = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val filteredList = mutableListOf<Int>()
list4.filterIndexedTo(filteredList) { index, i -> list5[index] % 2 == 0 }
println(filteredList) // [2, 4, 6, 8]
// You can also find the elements that are instances of a specified type in a collection by using filterIsInstance.
val mixedList = listOf(1, 2, 3, "one", "two", 4, "three", "four", 5, 6, "five", 7)
val strList = mixedList.filterIsInstance<String>()
println(strList) // [one, two, three, four, five]
// Zip collections
// zip returns a list of pairs . The first element of the pair will be taken from the first collection and the second element of the pair will be taken from the second collection . The size of the returned list will be equal to the size of the shortest collection.
val listOne = listOf(1, 2, 3, 4, 5)
val listTwo = listOf("a", "b", "c", "d", "e", "f")
println(listOne zip listTwo) // [(1, a), (2, b), (3, c), (4, d), (5, e)]
// Zip with next in a collection
// zipWithNext return a list of pairs . The elements of the pair will be the adjacent elements of the collection .
val list5_1 = listOf(1, 2, 3, 4, 5)
println(list5_1.zipWithNext()) // [(1, 2), (2, 3), (3, 4), (4, 5)]
// Unzip a collection
// unzip returns a pair of lists . The first list is made from the first elements of each pair and the second list is made from the second element of each pair.
val list6 = listOf("Amit" to 8, "Ali" to 10, "Sumit" to 4, "Himanshu" to 2)
val (players, footballSkills) = list6.unzip()
println(players) // [Amit, Ali, Sumit, Himanshu]
println(footballSkills) // [8, 10, 4, 2]
// Split array into two parts based on some condition
// If you want to split your data into two parts based on some conditions like isFootballFan, then you can use partition.
data class User(val id: Int, val name: String, val isFootballLover: Boolean)
val users = listOf(
User(1, "Amit", true),
User(2, "Ali", true),
User(3, "Sumit", false),
User(4, "Himanshu", false)
)
val (footballLovers, nonFootballLovers) = users.partition { it.isFootballLover }
println(footballLovers) // [User(id=1, name=Amit, isFootballLover=true), User(id=2, name=Ali, isFootballLover=true)]
println(nonFootballLovers) // [User(id=3, name=Sumit, isFootballLover=false), User(id=4, name=Himanshu, isFootballLover=false)]
// Reverse a list
// You can reverse a list in Kotlin by using the reversed and asReversed function .
val list7 = listOf(1, 2, 3, 4, 5)
print(list7.reversed()) // [5, 4, 3, 2, 1]
print(list7.asReversed()) // [5, 4, 3, 2, 1]
/*
Both are giving the same output but these functions are different.The reversed () function can be applied on Array, List, and MutableList. It generates a new list that is the reverse of the original list.
But the asReversed() function can be applied on List and MutableList.It doesn 't generate a new list because, after reversal, the new elements are still referring to the old one. So any change in one of them will result in a change in the other one.
Similarly, there are other functions that can be used to reverse the elements such as reversedArray(), reverse().
*/
// Group elements of a collection based on some condition
// You can use groupBy () to group the elements of a collection based on certain conditions . For example, the below code will group the elements of the list based on the remainder when divided by 4 i.e. 4 groups will be there(when remainder = 0, 1, 2, and 3)
val list8 = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(list8.groupBy { it % 4 })
// {
// 1=[1, 5, 9],
// 2=[2, 6, 10],
// 3=[3, 7],
// 0=[4, 8]
// }
// Sort element of a collection
// You can sort the elements of a collection by using the sorted () function . This will return a sorted list.
val list = listOf(10, 4, 1, 3, 7, 2, 6)
println(list.sorted()) // [1, 2, 3, 4, 6, 7, 10]
// Similarly, there are other functions that can be used to sort the collection based on certain conditions. Some of these functions are sortedArray, sortedArrayWith, sortedBy, sortedByDescending, sortedArraydescending, sortedWith, etc.
} | [
{
"class_path": "mustajab-ikram__Kotlin_Tutorial__f3293e9/CollectionFunctionsKt$main$User.class",
"javap": "Compiled from \"CollectionFunctions.kt\"\npublic final class CollectionFunctionsKt$main$User {\n private final int id;\n\n private final java.lang.String name;\n\n private final boolean isFootballL... |
winger__team-competitions__df24b92/hashcode/y2018/qual/Main.kt | import java.io.File
import java.io.PrintWriter
import java.util.*
//val filename = "a_example"
//val filename = "b_should_be_easy"
//val filename = "c_no_hurry"
val filename = "d_metropolis"
//val filename = "e_high_bonus"
fun main(args: Array<String>) {
val sc = Scanner(File("data/$filename.in"))
val (_, _, V, R) = Array(4) { sc.nextInt() }
B = sc.nextInt()
val T = sc.nextInt()
val rides = Array(R) { sc.nextRide(it) }
val cars = Array(V) { Car(Point(0, 0), 0) }
println("Max score: " + rides.sumBy { it.duration + B })
rides.sortBy { it.end - it.duration }
for (ride in rides) {
cars.maxBy { it.canScore(ride) }?.take(ride)
}
println(cars.totalScore)
printSolution(cars)
}
val Array<Car>.totalScore
get() = fold(0) { acc, state -> acc + state.score }
var B = 0
class Car(var point: Point,
var time: Int,
val schedule: MutableList<Ride> = mutableListOf(),
var score: Int = 0) {
fun willFinishAt(ride: Ride) = possibleArrival(ride) + ride.duration
fun possibleArrival(ride: Ride) = Math.max(time + (ride.start - point), ride.begin)
fun waitTime(ride: Ride) = Math.max(possibleArrival(ride) - time, 0)
fun canScore(ride: Ride): Int {
return if (willFinishAt(ride) <= ride.end) {
ride.duration + if (possibleArrival(ride) <= ride.begin) B else 0
} else 0
}
fun take(ride: Ride) {
score += canScore(ride)
schedule += ride
time = willFinishAt(ride)
point = ride.finish
}
}
fun printSolution(solution: Array<Car>) {
PrintWriter("$filename-${solution.totalScore}.out").use { pr ->
solution.forEach {
pr.print(it.schedule.size)
it.schedule.forEach {
pr.print(" ${it.num}")
}
pr.println()
}
}
}
operator fun Point.minus(o: Point) = Math.abs(x - o.x) + Math.abs(y - o.y)
data class Point(val x: Int, val y: Int)
data class Ride(val num: Int, val start: Point, val finish: Point, val begin: Int, val end: Int) {
val duration
get() = finish - start
}
val Ride.longRide
get() = finish.x > 5000 || finish.y > 5000
fun Scanner.nextPoint() = Point(nextInt(), nextInt())
fun Scanner.nextRide(num: Int) = Ride(num, nextPoint(), nextPoint(), nextInt(), nextInt()) | [
{
"class_path": "winger__team-competitions__df24b92/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n private static final java.lang.String filename;\n\n private static int B;\n\n public static final java.lang.String getFilename();\n Code:\n 0: getstatic #11 ... |
getnahid__programing-problem-solves-kotlin__589c392/OddOccurrencesInArray.kt | /*
OddOccurrencesInArray
Find value that occurs in odd number of elements.
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
Write a function:
fun solution(A: IntArray): Int
that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
For example, given array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the function should return 7, as explained in the example above.
Write an efficient algorithm for the following assumptions:
N is an odd integer within the range [1..1,000,000];
each element of array A is an integer within the range [1..1,000,000,000];
all but one of the values in A occur an even number of times.*/
fun solution(array: IntArray): Int {
array.sort()
val length = array.size
for (i in array.indices step 2) {
if (i + 1 < length && array[i] == array[i + 1]) continue
return array[i]
}
return 0
}
| [
{
"class_path": "getnahid__programing-problem-solves-kotlin__589c392/OddOccurrencesInArrayKt.class",
"javap": "Compiled from \"OddOccurrencesInArray.kt\"\npublic final class OddOccurrencesInArrayKt {\n public static final int solution(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
getnahid__programing-problem-solves-kotlin__589c392/CyclicRotation.kt | /*
CyclicRotation
Rotate an array to the right by a given number of steps.
An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
Write a function:
class Solution { public int[] solution(int[] A, int K); }
that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given
A = [3, 8, 9, 7, 6]
K = 3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given
A = [0, 0, 0]
K = 1
the function should return [0, 0, 0]
Given
A = [1, 2, 3, 4]
K = 4
the function should return [1, 2, 3, 4]
Assume that:
N and K are integers within the range [0..100];
each element of array A is an integer within the range [−1,000..1,000].
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.*/
fun solution(array: IntArray, k: Int): IntArray {
val arrayLength: Int = array.size
val sol = IntArray(array.size)
for (i in array.indices) {
sol[(i + k) % arrayLength] = array.get(i)
}
//array.forEach { print(it) }
return array
}
| [
{
"class_path": "getnahid__programing-problem-solves-kotlin__589c392/CyclicRotationKt.class",
"javap": "Compiled from \"CyclicRotation.kt\"\npublic final class CyclicRotationKt {\n public static final int[] solution(int[], int);\n Code:\n 0: aload_0\n 1: ldc #9 // ... |
getnahid__programing-problem-solves-kotlin__589c392/BinaryGap.kt | /*
BinaryGap
Find longest sequence of zeros in binary representation of an integer.
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
Write a function:
class Solution { public int solution(int N); }
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..2,147,483,647].*/
fun solution(n: Int): Int {
val stringBinary = Integer.toBinaryString(n)
var part = Integer.toBinaryString(n).substring(0, stringBinary.lastIndexOf("1"))
val parts = part.split("1", part)
var max = 0;
for (p in parts) {
if (p.length > max) max = p.length
}
return max;
} | [
{
"class_path": "getnahid__programing-problem-solves-kotlin__589c392/BinaryGapKt.class",
"javap": "Compiled from \"BinaryGap.kt\"\npublic final class BinaryGapKt {\n public static final int solution(int);\n Code:\n 0: iload_0\n 1: invokestatic #12 // Method java/lang/Integer... |
BioniCosmos__neko-programming-class__5d6a15f/lesson-3_dynamic-programming/0-1-knapsack-problem/memoization/main.kt | import kotlin.math.max
fun main() {
var tmp = readLine()!!.split(' ')
val n = tmp[0].toInt()
val balance = tmp[1].toInt()
val values = Array(n) { 0 }
val like = Array(n) { 0 }
val rec = Array(n) { Array(balance + 1) { 0 } }
for (i in 0 until n) {
tmp = readLine()!!.split(' ')
values[i] = tmp[0].toInt()
like[i] = tmp[1].toInt()
}
println(getFav(n - 1, balance, values, like, rec))
}
fun getFav(i: Int, balance: Int, values: Array<Int>, like: Array<Int>, rec: Array<Array<Int>>): Int {
if (i == -1 || balance <= 0) {
return 0
}
if (rec[i][balance] == 0) {
if (values[i] > balance) {
rec[i][balance] = getFav(i - 1, balance, values, like, rec)
} else {
rec[i][balance] = max(
getFav(i - 1, balance, values, like, rec),
getFav(i - 1, balance - values[i], values, like, rec) + like[i],
)
}
}
return rec[i][balance]
}
| [
{
"class_path": "BioniCosmos__neko-programming-class__5d6a15f/MainKt.class",
"javap": "Compiled from \"main.kt\"\npublic final class MainKt {\n public static final void main();\n Code:\n 0: invokestatic #12 // Method kotlin/io/ConsoleKt.readLine:()Ljava/lang/String;\n 3: dup... |
darwineee__adventOfCode2022__f4354b8/src/main/kotlin/Puzzle5.kt | import java.io.File
private val numberRegex = "\\d+".toRegex()
/**
* With this puzzle we do not use stack data structure in part 1, even though it is maybe easier.
* Because I want to keep most common logic from both part of the puzzle.
*/
fun puzzle5(args: Array<String>, isOnWrongShip: Boolean) {
val graphStacks = args[0]
val moveStrategy = args[1]
val graphMatrix = graphStacks.getGraphMatrix()
File(moveStrategy)
.readLines()
.map {
it.getCraneMove().mapWithArrayIndex()
}
.forEach {
if (isOnWrongShip) {
moveCraneOn9000Ship(graphMatrix, it)
} else {
moveCraneOn9001Ship(graphMatrix, it)
}
}
println(
graphMatrix.mapNotNull { it.lastOrNull() }.joinToString("")
)
}
private fun moveCraneOn9000Ship(
graphMatrix: List<MutableList<Char>>,
moveStrategy: Triple<Int, Int, Int>
) {
val (quantity, from, to) = moveStrategy
repeat(quantity) { _ ->
graphMatrix[from].lastOrNull()?.let { item ->
graphMatrix[to].add(item)
graphMatrix[from].removeLast()
}
}
}
private fun moveCraneOn9001Ship(
graphMatrix: List<MutableList<Char>>,
moveStrategy: Triple<Int, Int, Int>
) {
val (quantity, from, to) = moveStrategy
graphMatrix[to].addAll(graphMatrix[from].takeLast(quantity))
repeat(quantity) {
graphMatrix[from].removeLastOrNull()
}
}
private fun String.getGraphMatrix(): List<MutableList<Char>> {
val graphMatrix = mutableListOf<MutableList<Char>>()
File(this)
.readLines()
.map {
it.toCharArray()
}
.forEach { row ->
for ((columnIndex, rowIndex) in (1 until row.size step 4).withIndex()) {
if (columnIndex > graphMatrix.lastIndex) {
graphMatrix.add(mutableListOf())
}
val item = row[rowIndex]
if (item.isLetter()) {
graphMatrix[columnIndex].add(0, item)
}
}
}
return graphMatrix
}
private fun String.getCraneMove(): Triple<Int, Int, Int> {
val (first, second, third) = numberRegex
.findAll(this)
.mapNotNull { it.value.toIntOrNull() }
.toList()
return Triple(first, second, third)
}
private fun Triple<Int, Int, Int>.mapWithArrayIndex(): Triple<Int, Int, Int> {
return Triple(
first = this.first,
second = this.second - 1,
third = this.third - 1
)
}
| [
{
"class_path": "darwineee__adventOfCode2022__f4354b8/Puzzle5Kt.class",
"javap": "Compiled from \"Puzzle5.kt\"\npublic final class Puzzle5Kt {\n private static final kotlin.text.Regex numberRegex;\n\n public static final void puzzle5(java.lang.String[], boolean);\n Code:\n 0: aload_0\n 1: l... |
darwineee__adventOfCode2022__f4354b8/src/main/kotlin/Puzzle3.kt | import java.io.File
fun puzzle3Part1(args: Array<String>) {
var sum = 0
File(args[0])
.readLines()
.forEach {
val commonItem = it.toCharArray().getCommonItem()
if (commonItem != null) {
sum += commonItem.toPriorityPoint()
}
}
println(sum)
}
private fun CharArray.getCommonItem(): Char? {
// as the requirement, the array item always have size is even number
// and always have common item
val compartmentSize = this.size / 2
val compartmentLeft = this.take(compartmentSize).toHashSet()
val compartmentRight = this.takeLast(compartmentSize).toHashSet()
compartmentLeft.forEach {
if (it in compartmentRight) return it
}
return null
}
fun puzzle3Part2(args: Array<String>) {
var sum = 0
File(args[0])
.readLines()
.chunked(3)
.forEach {
val groupBadge = it.getGroupBadge()
if (groupBadge != null) {
sum += groupBadge.toPriorityPoint()
}
}
println(sum)
}
private fun List<String>.getGroupBadge(): Char? {
val (rucksack1, rucksack2, rucksack3) = this.map { it.toCharArray().toHashSet() }
return when {
rucksack1.size * 2 < rucksack2.size + rucksack3.size -> {
getGroupBadge(rucksack1, rucksack2, rucksack3)
}
rucksack2.size * 2 < rucksack1.size + rucksack3.size -> {
getGroupBadge(rucksack2, rucksack1, rucksack3)
}
else -> {
getGroupBadge(rucksack3, rucksack1, rucksack2)
}
}
}
private fun getGroupBadge(rucksack1: HashSet<Char>, rucksack2: HashSet<Char>, rucksack3: HashSet<Char>): Char? {
rucksack1.forEach {
if (it in rucksack2 && it in rucksack3) return it
}
return null
}
private fun Char.toPriorityPoint(): Int {
return if (this.isUpperCase()) {
this.code - 38
} else this.code - 96
} | [
{
"class_path": "darwineee__adventOfCode2022__f4354b8/Puzzle3Kt.class",
"javap": "Compiled from \"Puzzle3.kt\"\npublic final class Puzzle3Kt {\n public static final void puzzle3Part1(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: in... |
HarshCasper__NeoAlgo__4f1e5bd/Kotlin/Maths/HappyNumber.kt | /*
A number is called happy if it leads to 1 after a sequence of steps
wherein each step number is replaced by the sum of squares of its digit
that is if we start with Happy Number and keep replacing it with digits square sum, we reach 1.
Examples of Happy numbers are:- 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70,...
*/
import java.util.*
fun squaredSum(n: Int): Int{
var sum_of_square:Int = 0
var c:Int = n
while(c!=0){
sum_of_square += c%10 * (c % 10)
c /= 10
}
return sum_of_square
}
//defining a boolean function to check whether the number is happy number or not
fun Happynumber(number: Int): Boolean {
var slow: Int
var fast: Int
fast = number
slow = fast
do {
slow = squaredSum(slow)
fast = squaredSum(squaredSum(fast))
} while (slow != fast)
return slow == 1
}
//Testing code
fun main(){
val input = Scanner(System.`in`)
println("Enter the number which you want to check")
val n = input.nextInt()
if (Happynumber(n))
println("$n is a Happy number")
else
println("$n is not a happy number")
}
/*
Enter the number which you want to check
19
19 is a Happy number
Enter the number which you want to check
20
20 is not a happy number
*/
/*
Time complexity :- O(N)
Space complexity :- O(1), which is constant
*/
| [
{
"class_path": "HarshCasper__NeoAlgo__4f1e5bd/HappyNumberKt.class",
"javap": "Compiled from \"HappyNumber.kt\"\npublic final class HappyNumberKt {\n public static final int squaredSum(int);\n Code:\n 0: iconst_0\n 1: istore_1\n 2: iload_0\n 3: istore_2\n 4: iload_2\n ... |
HarshCasper__NeoAlgo__4f1e5bd/Kotlin/sort/MergeSort/src/MergeSort.kt | fun mergeSort(list : MutableList<Int>) : MutableList<Int>{
// check if the given list has more than 1 elements
if (list.size > 1){
// a list to store sorted list
val sortedList = MutableList(list.size) { 0 }
// taking note of middle element of the list
val middle = list.size / 2
// splitting list into a left side and right side
var leftSide = list.slice(0 until middle).toMutableList()
var rightSide = list.slice(middle until list.size).toMutableList()
// performing mergesort on the list and storing the results as the sides name
leftSide = mergeSort(leftSide)
rightSide = mergeSort(rightSide)
var i = 0; var j = 0; var k = 0
// getting smaller elements from the list until one of them is exhausted
// once one list gets exhausted we know that the elements in the remaining
// list are larger than the one's we sorted
while (i < leftSide.size && j < rightSide.size){
if (leftSide[i] < rightSide[j]) {
sortedList[k] = leftSide[i]
i++
}
else {
sortedList[k] = rightSide[j]
j++
}
k++
}
// putting the elements of leftSide if they are left after one list gets
// exhausted
while ( i < leftSide.size){
sortedList[k] = leftSide[i]
i++
k++
}
// putting the elements of rightSide if they are left after one list gets
// exhausted
while ( j < rightSide.size){
sortedList[k] = rightSide[j]
j++
k++
}
// returning the sorted list
return sortedList
}
// if the size is less than 1 then the list is considered as sorted
// in itself, just return the item
return list
}
fun main() {
print("Enter the number of items to sort - ")
val lengthOfList = readLine()!!.toInt()
val list = MutableList(lengthOfList) { 0 }
list.withIndex().forEach {
print("Enter value ${it.index + 1} - ")
list[it.index] = readLine()!!.toInt()
}
println("unsorted list is $list")
val sorted = mergeSort(list.toMutableList());
println("sorted list is $sorted")
}
/*
Enter the number of items to sort - 12
Enter value 1 - 1
Enter value 2 - 3
Enter value 3 - 5
Enter value 4 - 2
Enter value 5 - 90
Enter value 6 - 24
Enter value 7 - 67
Enter value 8 - 48
Enter value 9 - 95
Enter value 10 - 29
Enter value 11 - 5
Enter value 12 - 16
unsorted list is [1, 3, 5, 2, 90, 24, 67, 48, 95, 29, 5, 16]
sorted list is [1, 2, 3, 5, 5, 16, 24, 29, 48, 67, 90, 95]
Time Complexity -
Best Case Complexity: O(n*log n)
Worst Case Complexity: O(n*log n)
Average Case Complexity: O(n*log n)
Space Complexity -
The space complexity of merge sort is O(n).
*/
| [
{
"class_path": "HarshCasper__NeoAlgo__4f1e5bd/MergeSortKt.class",
"javap": "Compiled from \"MergeSort.kt\"\npublic final class MergeSortKt {\n public static final java.util.List<java.lang.Integer> mergeSort(java.util.List<java.lang.Integer>);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
HarshCasper__NeoAlgo__4f1e5bd/Kotlin/search/TernarySearch.kt | //Kotlin program to implement ternary search using recursive approach
import java.util.*
// A function to declare ternary search
fun ternarySearch(left:Int, right:Int, key:Int, array: ArrayList<Int>): Int{
if (right >= left) {
// Finding the midterms
val mid1 = left + (right - left) / 3
val mid2 = right - (right - left) / 3
// Check if the value is present in the first mid term
if (array[mid1] == key) {
return mid1
}
// Check if the value is present in the second mid term
if (array[mid2] == key) {
return mid2
}
// If the element is not present in the mid positions, the following cases can be a possibility.
// Checking if the value is less than mid1 element
if (key < array[mid1]) {
return ternarySearch(left, mid1 - 1, key, array)
}
// Checking if the value is greater than mid2 element
else if (key > array[mid2]) {
return ternarySearch(mid2 + 1, right, key, array)
}
// The last possibility is that, the element may be present between the mid1 and mid2
else {
return ternarySearch(mid1 + 1, mid2 - 1, key, array)
}
}
// If all the possibilities fail, the element is not present inside the array
return -1
}
//Testing code
fun main(){
val input = Scanner(System.`in`)
println("Enter the length of the array")
val arrayLength = input.nextInt()
val arrayOfElements = arrayListOf<Int>()
println("Enter the elements of the array in ascending order")
for(index in 0 until arrayLength) {
val element = input.nextInt()
arrayOfElements.add(element)
}
print("Enter the number you want to search for :")
val number = input.nextInt()
input.close()
val left:Int = -1
val right:Int = arrayLength - 1
// Search the number using ternarySearch
val position = ternarySearch(left, right, number, arrayOfElements) + 1
if(position == 0)
println("Key: $number is not present in the array")
else
println("Key: $number is present in the array at position $position")
}
/*
Sample Test Cases:-
Test Case 1:-
Enter the length of the array
5
Enter the elements of the array in ascending order
1 2 3 4 5
Enter the number you want to search for :5
Key: 5 is present in the array at position 5
Test Case 2:-
Enter the length of the array
5
Enter the elements of the array in ascending order
10 20 30 40 50
Enter the number you want to search for :60
Key: 60 is not present in the array
Time Complexity:- The time complexity of this algorithm is O(log3n), where n is the size of the array
Space cComplexity:- The space complexity of this algorithm is O(1), which is constant, irrespective of any case.
*/
| [
{
"class_path": "HarshCasper__NeoAlgo__4f1e5bd/TernarySearchKt.class",
"javap": "Compiled from \"TernarySearch.kt\"\npublic final class TernarySearchKt {\n public static final int ternarySearch(int, int, int, java.util.ArrayList<java.lang.Integer>);\n Code:\n 0: aload_3\n 1: ldc #1... |
HarshCasper__NeoAlgo__4f1e5bd/Kotlin/sort/RadixSort/src/RadixSort.kt | // Function to Implement Radix Sort
// The radix sorting algorithm is an integer sorting algorithm,
// that sorts by grouping numbers by their individual digits (or by their radix).
// It uses each radix/digit as a key, and implements counting sort or
// bucket sort under the hood in order to do the work of sorting.
// Takes an IntArray as arguments and returns a sorted IntArray to the caller function
fun radixSort(original: IntArray): IntArray {
// Array needs to be mutable
var old = original
for (shift in 31 downTo 0) {
val tmp = IntArray(old.size)
// The number of 0s
var j = 0
// Move the 0s to the new array, and the 1s to the old one
for (i in 0 until old.size) {
// If there is a 1 in the bit we are testing, the number will be negative
val move = (old[i] shl shift) >= 0
// If this is the last bit, negative numbers are actually lower
val toBeMoved = if (shift != 0) move else !move
if (toBeMoved) {
tmp[j++] = old[i]
}
else {
// It's a 1, so stick it in the old array for now
old[i - j] = old[i]
}
}
// Copy over the 1s from the old array
for (i in j until tmp.size) {
tmp[i] = old[i - j]
}
old = tmp
}
return old
}
fun main(args: Array<String>) {
print("Enter N: ");
val n= readLine()!!.toInt();
println("Enter array of N integers: ");
val arrays = IntArray(n) { readLine()!!.toInt() }
val array= radixSort(arrays);
print("Array after Radix Sort is: ")
for(i in array){
print("$i ")
}
}
/*
Time Complexity: O(log n)
Sample Input:
Enter N: 5
Enter array of N integers:
3
-1
2
3
4
Sample Output:
Array after Radix Sort is: -1 2 3 3 4
*/
| [
{
"class_path": "HarshCasper__NeoAlgo__4f1e5bd/RadixSortKt.class",
"javap": "Compiled from \"RadixSort.kt\"\npublic final class RadixSortKt {\n public static final int[] radixSort(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String original\n 3: invokestatic ... |
HarshCasper__NeoAlgo__4f1e5bd/Kotlin/sort/QuickSort/src/QuickSort.kt | /*
QuickSort Algortihm works on Divide and Conquer Algorithm. It creates two empty arrays to hold elements less than the pivot value and
elements greater than the pivot value, and then recursively sort the sub arrays. There are two basic operations in the algorithm,
swapping items in place and partitioning a section of the array.
*/
//Importing the Java.util package, it is needed because we are using the scanner object.
import java.util.*
//The function which will sort the given array in ascending order using QuickSort Algortihm
fun quicksort(items:List<Int>):List<Int>{
//If there is only one element in the list, then there is no need to sort
if (items.count() < 2){
return items
}
//Vaiable pivot stores the index of middle element of the list
val pivot = items[items.count()/2]
//Variable equalto stores the elements at the pivot index
val equalto = items.filter { it == pivot }
//Variable lesser stores the list of element with indexes less than the pivot index
val lesser = items.filter { it < pivot }
//Variable greater stores the list of element with indexes less than the pivot index
val greater = items.filter { it > pivot }
//Calling the quicksort function recursively on the splitted arrays
//This will get recursively called until left with multiple arrays with a single element and arranged in order
return quicksort(lesser) + equalto + quicksort(greater)
}
//Main Driver Code
fun main() {
val input = Scanner(System.`in`)
println("Enter the length of the array")
val arrayLength = input.nextInt()
val arrayOfElements = arrayListOf<Int>()
println("Enter the List of numbers you want to Sort:")
for(index in 0 until arrayLength) {
val element = input.nextInt()
arrayOfElements.add(element)
}
print("Original List: ")
for(index in 0..4)
{
val number: Int = arrayOfElements[index]
print("$number\t")
}
print("\nOrdered list: ")
val ordered = quicksort(arrayOfElements)
println(ordered)
}
/*
First Testcasee:
Enter the length of the array
6
Enter the List of numbers you want to Sort:
34
33
67
3
2
45
Original List: 34 33 67 3 2 45
Ordered list: [2, 3, 33, 34, 45, 67]
Time Complexity: O(n log n)
Space Complexity: O(log n)
*/ | [
{
"class_path": "HarshCasper__NeoAlgo__4f1e5bd/QuickSortKt.class",
"javap": "Compiled from \"QuickSort.kt\"\npublic final class QuickSortKt {\n public static final java.util.List<java.lang.Integer> quicksort(java.util.List<java.lang.Integer>);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
mboos__advent-of-code__4477bb3/2020/day/21/allergens.kt | /**
* Solution to https://adventofcode.com/2020/day/21
*/
import java.io.File
fun main(args: Array<String>) {
var input: String = args[0]
var potentialAllergens = mutableMapOf<String, MutableSet<String>>()
var allIngredients = mutableListOf<String>()
var pattern: Regex = Regex("((\\w+ )+)\\(contains (\\w+(, \\w+)*)\\)\n?")
File(input).forEachLine { line ->
var match = pattern.matchEntire(line)
var ingredients = match!!.groupValues[1].split(" ").filter { it.isNotBlank() }
allIngredients.addAll(ingredients)
match.groupValues[3].split(", ").forEach { element ->
if (element.isNotBlank()) {
if (element in potentialAllergens) {
potentialAllergens[element] = potentialAllergens[element]!!.intersect(ingredients) as MutableSet<String>
} else {
potentialAllergens[element] = ingredients.toMutableSet()
}
}
}
}
var allPotentialIngredients = mutableSetOf<String>()
potentialAllergens.values.forEach { ingredients ->
allPotentialIngredients.addAll(ingredients)
}
var safeIngredients = 0
allIngredients.forEach { ingredient ->
if (!allPotentialIngredients.contains(ingredient)) {
safeIngredients += 1
}
}
println("Safe ingredients: ${safeIngredients}")
val foundIngredients = mutableSetOf<String>()
val foundAllergens = mutableMapOf<String,String>()
var unmatchedAllergens = true
while (unmatchedAllergens) {
unmatchedAllergens = false
potentialAllergens.forEach { allergen, ingredients ->
if (!(allergen in foundAllergens)) {
unmatchedAllergens = true
if (potentialAllergens[allergen]!!.size == 1) {
foundIngredients.addAll(ingredients)
foundAllergens[allergen] = ingredients.first()
} else {
potentialAllergens[allergen]!!.removeAll(foundIngredients)
}
}
}
}
println("Ingredients: ${foundAllergens.toSortedMap().values.joinTo(StringBuffer(""), ",").toString()}")
}
| [
{
"class_path": "mboos__advent-of-code__4477bb3/AllergensKt.class",
"javap": "Compiled from \"allergens.kt\"\npublic final class AllergensKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestat... |
mboos__advent-of-code__4477bb3/2020/day/13/bus.kt | /**
* Solution to https://adventofcode.com/2020/day/13
*/
import java.io.File
fun gcf(a: Long, b: Long): Long {
var tmp: Long
var aa = a
var bb = b
while (bb != 0L) {
tmp = aa % bb
aa = bb
bb = tmp
}
return aa
}
fun lcm(vals: List<Long>): Long {
return vals.reduce{a, b -> a*b/gcf(a,b)}
}
fun main(args: Array<String>) {
var input: String = args[0]
var raw: String = File(input).readText()
var secondLine: String = raw.split("\n")[1]
// Part 1
var desiredDepartureTime: Long = raw.split("\n")[0].toLong()
var waitTime = Long.MAX_VALUE
var bestRoute: Long = 0
for (routeLabel in secondLine.split(",")) {
if (routeLabel.equals("x")) {
continue
}
var routeNum = routeLabel.toLong()
var remainder = desiredDepartureTime % routeNum
var potentialWaitTime: Long
if (remainder > 0) {
potentialWaitTime = routeNum - remainder
} else {
potentialWaitTime = 0
}
if (potentialWaitTime < waitTime) {
waitTime = potentialWaitTime
bestRoute = routeNum
}
}
println("Product of route num and wait time: ${bestRoute * waitTime}")
// Part 2
var increment: Long
var startTime = 0L
while (true) {
var failedYet: Boolean = false
var goodNums: MutableList<Long> = ArrayList()
for ((index, routeName) in secondLine.split(",").withIndex()) {
if (routeName.equals("x")) {
continue
}
var routeNum = routeName.toInt()
if ((startTime + index) % routeNum != 0L) {
failedYet = true
} else {
goodNums.add(routeNum.toLong())
}
}
if (!failedYet) {
break
}
increment = lcm(goodNums)
startTime += increment
}
println("Earliest timestamp: ${startTime}")
}
| [
{
"class_path": "mboos__advent-of-code__4477bb3/BusKt.class",
"javap": "Compiled from \"bus.kt\"\npublic final class BusKt {\n public static final long gcf(long, long);\n Code:\n 0: lconst_0\n 1: lstore 4\n 3: lload_0\n 4: lstore 6\n 6: lload_2\n 7: lsto... |
kgw78__kotlin-design-patterns__24b8993/Strategy.kt | // Strategy Pattern Example
// ソートアルゴリズムのStrategyインターフェース
interface SortStrategy {
fun sort(numbers: IntArray): IntArray
}
// バブルソートアルゴリズム
class BubbleSortStrategy : SortStrategy {
override fun sort(numbers: IntArray): IntArray {
val sortedArray = numbers.clone()
val n = sortedArray.size
for (i in 0 until n) {
for (j in 0 until n - i - 1) {
if (sortedArray[j] > sortedArray[j + 1]) {
val temp = sortedArray[j]
sortedArray[j] = sortedArray[j + 1]
sortedArray[j + 1] = temp
}
}
}
return sortedArray
}
}
// クイックソートアルゴリズム
class QuickSortStrategy : SortStrategy {
override fun sort(numbers: IntArray): IntArray {
if (numbers.size <= 1) return numbers
val pivot = numbers[numbers.size / 2]
val equal = numbers.filter { it == pivot }.toIntArray()
val less = numbers.filter { it < pivot }.toIntArray()
val greater = numbers.filter { it > pivot }.toIntArray()
return sort(less) + equal + sort(greater)
}
}
// ソートを実行するコンテキストクラス
class SortContext(private val strategy: SortStrategy) {
fun executeSort(numbers: IntArray): IntArray {
return strategy.sort(numbers)
}
}
fun main() {
val numbers = intArrayOf(9, 3, 7, 1, 5)
// バブルソートを用いたソート
val bubbleSortStrategy = BubbleSortStrategy()
val bubbleSortContext = SortContext(bubbleSortStrategy)
val sortedWithBubbleSort = bubbleSortContext.executeSort(numbers)
println("バブルソートの結果: ${sortedWithBubbleSort.joinToString()}")
// クイックソートを用いたソート
val quickSortStrategy = QuickSortStrategy()
val quickSortContext = SortContext(quickSortStrategy)
val sortedWithQuickSort = quickSortContext.executeSort(numbers)
println("クイックソートの結果: ${sortedWithQuickSort.joinToString()}")
}
| [
{
"class_path": "kgw78__kotlin-design-patterns__24b8993/StrategyKt.class",
"javap": "Compiled from \"Strategy.kt\"\npublic final class StrategyKt {\n public static final void main();\n Code:\n 0: iconst_5\n 1: newarray int\n 3: astore_1\n 4: aload_1\n 5: iconst_0\n ... |
Road-of-CODEr__stupid-week-2021__cae1df8/2021/03/07/jjeda/Sorting.kt |
// https://app.codility.com/programmers/lessons/6-sorting/distinct/
fun distinct(A: IntArray): Int {
return A.toSet().size
}
// https://app.codility.com/programmers/lessons/6-sorting/max_product_of_three/
fun maxProductOfThree(A: IntArray): Int {
val indexWithA = A.withIndex().sortedBy { it.value }
val length = A.size
val positiveMaxValue = indexWithA[length - 1].value * indexWithA[length - 2].value * indexWithA[length - 3].value
val negativeMaxValue = indexWithA[0].value * indexWithA[1].value * indexWithA[length - 1].value
return if (positiveMaxValue > negativeMaxValue) positiveMaxValue else negativeMaxValue
}
// https://app.codility.com/programmers/lessons/6-sorting/number_of_disc_intersections/
// TODO: Refactor this O(N^2) time complexity
fun numberOfDiscIntersections(A: IntArray): Int {
val sortedA = A.withIndex().sortedBy { it.index - it.value }
return sortedA.asSequence().mapIndexed { index, sortedValue ->
val rightEnd = if (sortedValue.index + sortedValue.value >= Int.MAX_VALUE) {
Int.MAX_VALUE
} else {
sortedValue.index + sortedValue.value
}
sortedA.subList(index + 1, A.size).count {
indexedValue ->
rightEnd >= indexedValue.index - indexedValue.value
}
}.reduce { acc, number ->
if (acc > 10000000) return -1
acc + number
}
}
// https://app.codility.com/programmers/lessons/6-sorting/triangle/
fun triangle(A: IntArray): Int {
val windowedA = A.sorted().reversed().windowed(3, 1)
windowedA.forEach {
if (it[0] < it[1] + it[2]) return 1
}
return 0
} | [
{
"class_path": "Road-of-CODEr__stupid-week-2021__cae1df8/SortingKt$maxProductOfThree$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class SortingKt$maxProductOfThree$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public SortingKt$maxProductOfThree$$inlined... |
Road-of-CODEr__stupid-week-2021__cae1df8/2021/02/28/jjeda/PrefixSums.kt | // https://app.codility.com/programmers/lessons/5-prefix_sums/count_div
fun countDiv(A: Int, B: Int, K: Int): Int {
val startNumber = (A..B).firstOrNull {
it % K ==0
} ?: return 0
return (B - startNumber) / K + 1
}
// https://app.codility.com/programmers/lessons/5-prefix_sums/genomic_range_query
/*
// O(N * M)
fun solution(S: String, P: IntArray, Q: IntArray): IntArray {
fun String.findMinValue(): Int {
if (this.contains('A')) return 1
if (this.contains('C')) return 2
if (this.contains('G')) return 3
return 4
}
return P.indices.map {
S.substring(P[it], Q[it] + 1).findMinValue()
}.toIntArray()
}
*/
// O(N + M)
fun genomicRangeQuery(S: String, P: IntArray, Q: IntArray): IntArray {
fun generateDeltaList(char: Char): IntArray {
val deltaArray = IntArray(S.length + 1)
(0..S.length).fold(0) { acc, index ->
deltaArray[index] = acc
if (index == S.length) {
return@fold 0
}
acc + if (S[index] == char) 1 else 0
}
return deltaArray
}
val deltaA = generateDeltaList('A')
val deltaC = generateDeltaList('C')
val deltaG = generateDeltaList('G')
fun String.findMinValue(start: Int, end: Int): Int {
if (start == end) {
return when (S[start]) {
'A' -> 1
'C' -> 2
'G' -> 3
else -> 4
}
}
if (deltaA[start] != deltaA[end]) return 1
if (deltaC[start] != deltaC[end]) return 2
if (deltaG[start] != deltaG[end]) return 3
return 4
}
return P.indices.map {
S.substring(P[it], Q[it] + 1).findMinValue(P[it], Q[it] + 1)
}.toIntArray()
}
// TODO: https://app.codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice
// https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars
fun passingCars(A: IntArray): Int {
val accumulateCount = IntArray(A.size)
A.foldIndexed(0) { index, acc, number ->
accumulateCount[index] = acc + number
acc + number
}
val totalCount = accumulateCount[A.size - 1]
var count = 0
accumulateCount.forEachIndexed { index, number ->
if (A[index] == 1) return@forEachIndexed
if (count + totalCount - number > 1000000000) return -1
count += totalCount - number
}
return count
} | [
{
"class_path": "Road-of-CODEr__stupid-week-2021__cae1df8/PrefixSumsKt.class",
"javap": "Compiled from \"PrefixSums.kt\"\npublic final class PrefixSumsKt {\n public static final int countDiv(int, int, int);\n Code:\n 0: new #8 // class kotlin/ranges/IntRange\n 3: d... |
rogerkeays__vimcash__f6a1c67/vimcash.kt | //usr/bin/env [ $0 -nt $0.jar ] && kotlinc -d $0.jar $0; [ $0.jar -nt $0 ] && kotlin -cp $0.jar VimcashKt $@; exit 0
import java.io.File
fun String.parseAmount(account: String): Double {
return substring(22, 34).toDouble() * if (indexOf(" $account ") > 34) -1 else 1
}
fun File.calculateBalance(account: String, currency: String): Double {
val filterRegex = Regex(".{15}\\| $currency [0-9. ]+[^ ]* $account .*")
return readLines()
.filter { it.matches(filterRegex) }
.map { it.parseAmount(account) }
.sum()
}
fun File.calculateBalances(account: String): Map<String, Double> {
val filterRegex = Regex(".{15}\\| ... [0-9. ]+[^ ]* $account .*")
val results = mutableMapOf<String, Double>()
readLines()
.filter { it.matches(filterRegex) }
.forEach {
val currency = it.slice(18..20)
val amount = it.parseAmount(account)
results.put(currency, results.get(currency)?.plus(amount) ?: amount)
}
return results
}
fun File.collectAccounts(): Set<String> {
return readLines()
.flatMap { it.substring(34, 52).split(' ') }
.toSortedSet()
}
fun File.reportBalances() {
collectAccounts()
.filter { it.matches(allCapsRegex) }
.associate { Pair(it, calculateBalances(it).filter { it.value.abs() > 0.005 }) }
.filter { it.value.size > 0 }
.forEach { println(it) }
}
val allCapsRegex = Regex("[0-9A-Z]+")
fun Double.abs(): Double = kotlin.math.abs(this)
| [
{
"class_path": "rogerkeays__vimcash__f6a1c67/VimcashKt.class",
"javap": "Compiled from \"vimcash.kt\"\npublic final class VimcashKt {\n private static final kotlin.text.Regex allCapsRegex;\n\n public static final double parseAmount(java.lang.String, java.lang.String);\n Code:\n 0: aload_0\n ... |
GitProger__Alferov-Lyceum-PTHS__cb1cd6d/client/logistics.kt | import java.io.InputStreamReader
import java.net.URL
import java.util.*
import kotlin.math.absoluteValue
import java.io.File
data class Kettle(val id: Int, val room: String, var boilTime: Long, var ml: Int)
var room = "1"
var ml = 200
private const val MILLIES_IN_DAY = 86_400_000
private val start = "http://192.168.43.217:1000/" //File("ip.txt").readLines()[0]
private fun query(query: String): List<String> {
val url = URL(start + query)
return InputStreamReader(url.openConnection().getInputStream()).readLines()
}
private fun ask() = query("ask.php").map { it.toKettle() }
fun update(id: Int, boilTime: Long, ml: Int): List<String> {
val query = "boil.php?id=$id&boil_time=$boilTime&ml=$ml"
return query(query)
}
fun add(room: String) = query("add.php?room=$room").first().toInt()
fun delete(id: Int) = query("remove.php?id=$id")
fun byId(id: Int) = query("by_id.php?id=$id").first().toKettle()
var graph: TreeMap<String, TreeMap<String, Int>>? = null
private fun getMap() {
if (graph == null) {
graph = TreeMap<String, TreeMap<String, Int>>()
val query = query("map.php")
query.forEach {
val (u, v, dist) = it.split(' ')
graph!![u] = graph!!.getOrDefault(u, TreeMap<String, Int>())
graph!![v] = graph!!.getOrDefault(v, TreeMap<String, Int>())
graph!![u]!![v] = dist.toInt()
graph!![v]!![u] = dist.toInt()
}
}
}
fun String.toKettle(): Kettle {
val (id, room, boilTime, ml) = split(' ')
return Kettle(id.toInt(), room, boilTime.toLong(), ml.toInt())
}
fun updateAllKettles() = ask()
fun nearKettles(currentRoom: String, ml: Int, currentTime: Long): List<Pair<Kettle, Int>> {
getMap()
val distance = TreeMap<String, Int>() //distance from currentRoom, calculated using Dijkstra algorithm
distance[currentRoom] = 0
val dijkstra = TreeSet<String> { s1, s2 ->
distance.getOrDefault(s1, Int.MAX_VALUE) - distance.getOrDefault(s2, Int.MAX_VALUE)
}
dijkstra.add(currentRoom)
while (dijkstra.isNotEmpty()) {
val cur = dijkstra.first() //nearest that's not processed yet
dijkstra.remove(cur)
for ((next, dist) in (graph!![cur] ?: TreeMap<String, Int>())) {
if (distance.getOrDefault(next, Int.MAX_VALUE) > distance[cur]!! + dist) {
dijkstra.remove(next)
distance[next] = distance[cur]!! + dist
dijkstra.add(next)
}
}
}
val candidates = ask().filter { it.ml >= ml }
.sortedWith(compareByDescending<Kettle> { it.boilTime.coerceAtMost(currentTime) }.thenBy { distance[it.room]!! })
var currentBestDistance = Int.MAX_VALUE
val optimums = mutableListOf<Pair<Kettle, Int>>()
for (kettle in candidates) {
if (currentBestDistance > distance.getOrDefault(kettle.room, Int.MAX_VALUE)) {
optimums.add(kettle to distance[kettle.room]!!)
currentBestDistance = distance[kettle.room]!!
}
}
return optimums.filter { (kettle, _) -> (kettle.boilTime - System.currentTimeMillis()).absoluteValue < MILLIES_IN_DAY }
}
fun boilKettle(id: Int, volume: Int) {
val boilingTime = (180L * 1000L * volume) / 1000L
update(id, System.currentTimeMillis() + boilingTime, volume)
}
fun drink(id: Int, volumeRemaining: Int) = update(id, byId(id).boilTime, volumeRemaining)
| [
{
"class_path": "GitProger__Alferov-Lyceum-PTHS__cb1cd6d/LogisticsKt$nearKettles$$inlined$thenBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class LogisticsKt$nearKettles$$inlined$thenBy$1<T> implements java.util.Comparator {\n final java.util.Comparator $this_thenBy;\n\n final java... |
Flight552__codewars__b9fb937/src/main/kotlin/PrimeSteps.kt | //The prime numbers are not regularly spaced.
// For example from 2 to 3 the step is 1. From 3 to 5
// the step is 2. From 7 to 11 it is 4.
// Between 2 and 50 we have the following pairs of 2-steps primes:
//
//3, 5 - 5, 7, - 11, 13, - 17, 19, - 29, 31, - 41, 43
//
//We will write a function step with parameters:
//
//g (integer >= 2) which indicates the step we are looking for,
//
//m (integer >= 2) which gives the start of the search (m inclusive),
//
//n (integer >= m) which gives the end of the search (n inclusive)
//
//In the example above step(2, 2, 50) will return [3, 5]
//which is the first pair between 2 and 50 with a 2-steps.
//
//So this function should return the first pair of the
//two prime numbers spaced with a step of g between the limits m,
// n if these g-steps prime numbers exist otherwise
// nil or null or None or Nothing or [] or "0, 0" or {0, 0} or 0 0 or "" (depending on the language).
//
//Examples:
//step(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7} or "5 7"
//
//step(2, 5, 5) --> nil or ... or [] in Ocaml or {0, 0} in C++
//
//step(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167}
//
//See more examples for your language in "TESTS"
//
//Remarks:
//([193, 197] is also such a 4-steps primes between 130
//and 200 but it's not the first pair).
//
//step(6, 100, 110) --> [101, 107] though there is a
//prime between 101 and 107 which is 103; the pair 101-103 is a 2-step.
//
//Notes:
//The idea of "step" is close to that of "gap" but it is
//not exactly the same. For those interested they can have
//a look at http://mathworld.wolfram.com/PrimeGaps.html.
//
//A "gap" is more restrictive: there must be no primes in
//between (101-107 is a "step" but not a "gap". Next kata will be about "gaps":-).
//
//For Go: nil slice is expected when there are no step between m and n.
//Example: step(2,4900,4919) --> nil
object PrimeSteps {
// if these g-steps prime numbers don't exist return []
fun step(g: Int, m: Long, n: Long): LongArray {
println("g = $g, m = $m, n = $n")
if (n < m || m < 2 || g < 2)
return LongArray(0)
var array = LongArray(2)
val listOfPrimes = mutableListOf<Long>()
var stepCounter = 0
var isPrime = true
if (m == 2L || m == 3L || m == 5L) {
array[0] = m
listOfPrimes.add(m)
}
for (i in m..n) {
if (i % 2 == 0L) {
stepCounter++
continue
}
for (p in 3 .. i / 2 step 2) {
if (i % p == 0L) {
isPrime = false
break
}
isPrime = true
}
if (isPrime && i != 5L) {
println(listOfPrimes)
listOfPrimes.add(i)
}
listOfPrimes.forEachIndexed { index, l ->
val differ = listOfPrimes[listOfPrimes.size - 1] - listOfPrimes[index]
if(differ == g.toLong()) {
array[0] = listOfPrimes[index]
array[1] = listOfPrimes[listOfPrimes.size - 1]
return array
}
}
}
return if (array[1] == 0L) {
return LongArray(0)
} else {
array
}
}
}
fun main(args: Array<String>) {
var array = PrimeSteps.step(2, 7, 13)
println(array.asList())
}
| [
{
"class_path": "Flight552__codewars__b9fb937/PrimeStepsKt.class",
"javap": "Compiled from \"PrimeSteps.kt\"\npublic final class PrimeStepsKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokesta... |
Flight552__codewars__b9fb937/src/main/kotlin/RangeExtraction.kt | //A format for expressing an ordered list of
//integers is to use a comma separated list of either
//
//individual integers
//or a range of integers denoted by the
//starting integer separated from the end integer in
//the range by a dash, '-'. The range includes all
//integers in the interval including both endpoints.
//It is not considered a range unless it spans at least
//3 numbers. For example "12,13,15-17"
//Complete the solution so that it takes a
//list of integers in increasing order and returns a
//correctly formatted string in the range format.
//
//Example:
//
//solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
// returns "-6,-3-1,3-5,7-11,14,15,17-20"
object RangeExtraction {
fun rangeExtraction(arr: IntArray): String {
var listOfRangedNumbers = mutableListOf<Int>()
var finalString = ""
var rangeString = ""
var isNext = false
arr.forEachIndexed { index, i ->
if (i <= 1) {
val nextIndex: Int = try {
arr[index + 1]
} catch (e: Exception) {
arr[index]
}
if (i == nextIndex - 1) {
isNext = true
listOfRangedNumbers.add(i)
} else {
if (isNext)
listOfRangedNumbers.add(i)
if (listOfRangedNumbers.size > 2) {
rangeString =
rangeString.plus("${listOfRangedNumbers[0]}-${listOfRangedNumbers[listOfRangedNumbers.size - 1]},")
finalString = finalString.plus(rangeString)
rangeString = ""
listOfRangedNumbers = mutableListOf()
} else {
listOfRangedNumbers.forEach {
finalString = finalString.plus("$it,")
}
listOfRangedNumbers = mutableListOf()
}
}
}
if (i > 1) {
val nextIndex: Int = try {
arr[index + 1]
} catch (e: Exception) {
0
}
if (i == nextIndex - 1) {
isNext = true
listOfRangedNumbers.add(i)
} else {
if (isNext)
listOfRangedNumbers.add(i)
if (listOfRangedNumbers.size > 2) {
rangeString =
rangeString.plus("${listOfRangedNumbers[0]}-${listOfRangedNumbers[listOfRangedNumbers.size - 1]},")
finalString = finalString.plus(rangeString)
rangeString = ""
listOfRangedNumbers = mutableListOf()
} else {
listOfRangedNumbers.forEach {
finalString = finalString.plus("$it,")
}
listOfRangedNumbers = mutableListOf()
}
}
}
if (!isNext) {
finalString = finalString.plus("$i,")
}
}
finalString = finalString.dropLast(1)
println(finalString)
return finalString
}
}
fun main(args: Array<String>) {
val array = intArrayOf(-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20)
RangeExtraction.rangeExtraction(array)
}
//best solution
fun rangeExtraction(
arr: IntArray
): String = arr.fold(emptyList<Pair<Int, Int>>())
{ rs, x ->
rs.lastOrNull().run {
if (this != null && x - second == 1)
rs.dropLast(1) + (first to x)
else rs + (x to x)
}
}.joinToString(",")
{ (x, y) ->
if (y - x > 1) "$x-$y" else (x..y).joinToString(",")
}
| [
{
"class_path": "Flight552__codewars__b9fb937/RangeExtraction.class",
"javap": "Compiled from \"RangeExtraction.kt\"\npublic final class RangeExtraction {\n public static final RangeExtraction INSTANCE;\n\n private RangeExtraction();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
ivan-moto__30-seconds-of-kotlin__772896c/src/main/List.kt | import java.util.Objects
import kotlin.math.max
fun <T> all(list: List<T>, predicate: (T) -> Boolean): Boolean =
list.all(predicate)
fun <T> allEqual(list: List<T>): Boolean =
if (list.isEmpty()) false else list.all { it == list[0] }
fun <T> any(list: List<T>, predicate: (T) -> Boolean): Boolean =
list.any(predicate)
fun <T> bifurcate(list: List<T>, filter: List<Boolean>): Pair<List<T>, List<T>> {
require(list.size == filter.size)
return list.zip(filter).partition { it.second }
.let { (list1, list2) -> list1.map { it.first } to list2.map { it.first } }
}
fun <T> bifurcateBy(list: List<T>, predicate: (T) -> Boolean): Pair<List<T>, List<T>> =
list.partition(predicate)
fun <T> chunk(list: List<T>, size: Int): List<List<T>> =
list.chunked(size)
fun <T> combinations(list: List<T>): List<List<T>> = TODO()
fun <T> compact(list: List<T?>): List<T> {
fun isTruthy(t: T?): Boolean = when(t) {
null -> false
is Boolean -> t
is Double -> !t.isNaN()
is Number -> t.toInt() != 0
is String -> !t.isEmpty()
is Array<*> -> t.size != 0
is Collection<*> -> !t.isEmpty()
else -> true
}
@Suppress("UNCHECKED_CAST")
return list.filter(::isTruthy) as List<T>
}
fun <T, K> countBy(list: List<T>, function: (T) -> K): Map<K, Int> =
list.groupingBy(function).eachCount()
fun <T> countOccurrences(list: List<T>, target: T, equals: (T, T) -> Boolean = Objects::equals): Int =
list.count { equals(target, it) }
fun <T> concat(first: List<T>, vararg others: List<T>): List<T> =
first.asSequence().plus(others.asSequence().flatten()).toList()
fun <T, U> corresponds(first: List<T>, second: List<U>, predicate: (T, U) -> Boolean): Boolean =
(first.size == second.size) && (first.zip(second).all { (t, u) -> predicate(t, u) })
fun <T, U> crossProduct(first: List<T>, second: List<U>): List<Pair<T, U>> =
first.flatMap { a -> second.map { b -> a to b } }
fun <T> cycle(list: List<T>): Sequence<T> =
generateSequence(if (list.isNotEmpty()) 0 else null) { (it + 1) % list.size }
.map { list[it] }
fun <T> difference(first: List<T>, second: List<T>): List<T> =
(first subtract second).toList()
fun <T, R> differenceBy(first: List<T>, second: List<T>, function: (T) -> R): List<T> =
with(second.toSet().map(function)) {
first.filterNot { contains(function(it)) }
}
fun <T> differenceWith(first: List<T>, second: List<T>, function: (T, T) -> Boolean): List<T> =
first.filter { a -> second.none { b -> function(a, b) } }
fun <T> distinct(list: List<T>): List<T> =
list.distinct()
fun <T> drop(list: List<T>, n: Int): List<T> =
list.drop(n)
fun <T> dropRight(list: List<T>, n: Int): List<T> =
list.dropLast(n)
fun <T> dropRightWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.dropLastWhile(predicate)
fun <T> dropWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.dropWhile(predicate)
fun <T> endsWith(list: List<T>, subList: List<T>): Boolean =
list.takeLast(subList.size) == subList
fun <T> everyNth(list: List<T>, nth: Int): List<T> =
list.windowed(nth, nth, partialWindows = false).map { it.last() }
fun <T> existsUnique(list: List<T>, predicate: (T) -> Boolean): Boolean {
var exists = false
for (t in list) {
if (predicate(t)) {
if (exists) {
return false
} else {
exists = true
}
}
}
return exists
}
fun <T> filterNonUnique(list: List<T>): List<T> =
list.distinct()
fun <T, K> filterNonUniqueBy(list: List<T>, function: (T) -> K): List<T> =
list.distinctBy(function)
fun <T> findLast(list: List<T>, predicate: (T) -> Boolean): T? =
list.findLast(predicate)
fun <T> findLastIndex(list: List<T>, predicate: (T) -> Boolean): Int =
list.indexOfLast(predicate)
fun <T> forEachRight(list: List<T>, action: (T) -> Unit): Unit =
list.reversed().forEach(action)
fun <T, K> groupBy(list: List<T>, function: (T) -> K): Map<K, List<T>> =
list.groupBy(function)
fun <T> hasDuplicates(list: List<T>): Boolean =
list.toSet().size != list.size
tailrec fun <T> hasSubList(list: List<T>, subList: List<T>): Boolean =
when {
subList.isEmpty() -> true
list.isEmpty() -> subList.isEmpty()
list.take(subList.size) == subList -> true
else -> hasSubList(list.drop(1), subList)
}
fun <T> head(list: List<T>): T =
list.first()
fun <T> indexOfAll(list: List<T>, target: T): List<Int> =
list.withIndex().filter { it.value == target }.map { it.index }
fun <T> initial(list: List<T>): List<T> =
list.dropLast(1)
fun <T> initialize2DList(width: Int, height: Int, value: T): List<List<T>> =
List(height) { List(width) { value } }
fun initializeListWithRange(start: Int, stop: Int, step: Int): List<Int> =
(start..stop step step).toList()
fun <T> initializeListWithValue(size: Int, value: T): List<T> =
List(size) { value }
fun <T> intersection(first: List<T>, second: List<T>): List<T> =
(first intersect second).toList()
fun <T, R> intersectionBy(first: List<T>, second: List<T>, function: (T) -> R): List<T> =
with(second.toSet().map(function)) {
first.filter { contains(function(it)) }
}
fun <T> intersectionWith(first: List<T>, second: List<T>, function: (T, T) -> Boolean): List<T> =
first.filter { a -> second.any { b -> function(a, b) } }
fun <T> intersperse(list: List<T>, element: T): List<T> =
List(list.size) { index -> listOf(list[index], element) }.flatten().dropLast(1)
fun <T> join(list: List<T>, separator: String = ", "): String =
list.joinToString(separator)
fun <T> last(list: List<T>): T =
list.last()
fun <T> longest(list: List<Collection<T>>): Collection<T>? =
list.maxBy { it.size }
fun <T, R> mapObject(list: List<T>, function: (T) -> R): Map<T, R> =
list.associateWith(function)
fun <T : Comparable<T>> maxN(list: List<T>, n: Int): List<T> =
list.sortedDescending().take(n)
fun <T : Comparable<T>> minN(list: List<T>, n: Int): List<T> =
list.sorted().take(n)
fun <T> none(list: List<T>, predicate: (T) -> Boolean): Boolean =
list.none(predicate)
fun <T> nthElement(list: List<T>, n: Int): T =
list[n]
fun <T> permutations(list: List<T>): List<List<T>> {
fun <T> List<T>.removeAtIndex(index: Int): List<T> = take(index) + drop(index + 1)
fun <T> List<T>.prepend(element: T): List<T> = listOf(element) + this
return when {
list.isEmpty() -> emptyList()
list.size == 1 -> listOf(list)
else -> list.foldIndexed(mutableListOf()) { index, acc, t ->
acc.apply {
addAll(permutations(list.removeAtIndex(index)).map { it.prepend(t) })
}
}
}
}
fun <T> partition(list: List<T>, predicate: (T) -> Boolean): Pair<List<T>, List<T>> =
list.partition(predicate)
fun <T> partitioningBy(list: List<T>, predicate: (T) -> Boolean): Map<Boolean, List<T>> =
list.groupBy(predicate)
fun <T, U, R> product(first: List<T>, second: List<U>, function: (T, U) -> R): List<R> =
first.flatMap { t -> second.map { u -> function(t, u) } }
fun <T> pull(list: List<T>, vararg elements: T): List<T> =
with(elements.toSet()) {
list.filterNot { contains(it) }
}
fun <T> pullAtIndex(list: List<T>, vararg indices: Int): List<T> =
with(indices.toSet()) {
list.filterIndexed { index, _ -> !contains(index) }
}
fun <T> pullAtValue(list: List<T>, vararg elements: T): List<T> =
with(elements.toSet()) {
list.filter { contains(it) }
}
fun <T, R> reduceSuccessive(list: List<T>, identity: R, function: (R, T) -> R): List<R> {
fun <T> List<T>.lastOrElse(t: T): T = lastOrNull() ?: t
return list.fold(emptyList()) { acc, t -> acc + function(acc.lastOrElse(identity), t) }
}
fun <T> reject(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.filterNot(predicate)
fun <T> remove(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.filter(predicate)
fun <T> rotateLeft(list: List<T>, n: Int): List<T> =
list.drop(n % list.size) + list.take(n % list.size)
fun <T> rotateRight(list: List<T>, n: Int): List<T> =
list.takeLast(n % list.size) + list.dropLast(n % list.size)
fun <T> sample(list: List<T>): T =
list.random()
fun <T> sampleSize(list: List<T>, n: Int): List<T> =
list.shuffled().take(n)
fun <T> segmentLength(list: List<T>, predicate: (T) -> Boolean): Int =
list.fold(0 to 0) { (longest, current), t -> if (predicate(t)) longest to current + 1 else max(longest, current) to 0 }.first
fun <T> shank(list: List<T>, start: Int = 0, deleteCount: Int = 0, vararg elements: T): List<T> =
list.slice(0 until start) + elements + list.drop(start + deleteCount)
fun <T> shuffle(list: List<T>): List<T> =
list.shuffled()
fun <T, R> slideBy(list: List<T>, classifier: (T) -> R): List<List<T>> {
tailrec fun slideBy_(list: List<T>, acc: MutableList<List<T>>): MutableList<List<T>> =
if (list.isEmpty())
acc
else
slideBy_(list.dropWhile { classifier(it) == classifier(list.first()) }, acc.apply { add(list.takeWhile { classifier(it) == classifier(list.first()) } )} )
return slideBy_(list, mutableListOf())
}
fun <T> segmentLength1(list: List<T>, predicate: (T) -> Boolean): Int =
list.windowed(max(list.size, 1), partialWindows = true)
.map { it.takeWhile(predicate).size }
.max() ?: 0
fun <T : Comparable<T>> sortOrder(list: List<T>): Int =
with(list.sorted()) {
when {
this == list -> 1
this.asReversed() == list -> -1
else -> 0
}
}
fun <T> span(list: List<T>, predicate: (T) -> Boolean): Pair<List<T>, List<T>> =
list.takeWhile(predicate) to list.dropWhile(predicate)
fun <T> splitAt(list: List<T>, predicate: (T) -> Boolean): Pair<List<T>, List<T>> =
list.takeWhile { !predicate(it) } to list.dropWhile { !predicate(it) }
fun <T> startsWith(list: List<T>, subList: List<T>): Boolean =
list.take(subList.size) == subList
fun <T> symmetricDifference(first: List<T>, second: List<T>): List<T> =
((first subtract second) + (second subtract first)).toList()
fun <T, R> symmetricDifferenceBy(first: List<T>, second: List<T>, function: (T) -> R): List<T> {
val mapFirst = first.toSet().map(function)
val mapSecond = second.toSet().map(function)
return first.filterNot { mapSecond.contains(function(it)) } + second.filterNot { mapFirst.contains(function(it)) }
}
fun <T> symmetricDifferenceWith(first: List<T>, second: List<T>, function: (T, T) -> Boolean): List<T> =
first.filter { a -> second.none { b -> function(a ,b) } } +
second.filter { b -> first.none { a -> function(a, b) } }
fun <T> tail(list: List<T>): List<T> =
list.drop(1)
fun <T> take(list: List<T>, n: Int): List<T> =
list.take(n)
fun <T> takeRight(list: List<T>, n: Int): List<T> =
list.takeLast(n)
fun <T> takeRightWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.takeLastWhile(predicate)
fun <T> takeWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
list.takeWhile(predicate)
fun <T> union(first: List<T>, second: List<T>): List<T> =
(first union second).toList()
fun <T, R> unionBy(first: List<T>, second: List<T>, function: (T) -> R): List<T> {
val mapFirst = first.toSet().map(function)
return (first.toSet() + second.toSet().filterNot { mapFirst.contains(function(it)) }).toList()
}
fun <T> unionWith(first: List<T>, second: List<T>, function: (T, T) -> Boolean): List<T> =
(first.filter { a -> second.any { b -> function(a, b) } } union
second.filter { b -> first.any { a -> function(a, b) } }).toList()
fun <T, U> unzip(list: List<Pair<T, U>>): Pair<List<T>, List<U>> =
list.unzip()
fun <T, U> zip(first: List<T>, second: List<U>): List<Pair<T, U>> =
first.zip(second)
fun <T, U> zipAll(first: List<T>, defaultT: T, second: List<U>, defaultU: U): List<Pair<T, U>> {
val firstIt = first.iterator()
val secondIt = second.iterator()
return object : Iterator<Pair<T, U>> {
override fun hasNext(): Boolean =
firstIt.hasNext() || secondIt.hasNext()
override fun next(): Pair<T, U> {
val t = if (firstIt.hasNext()) firstIt.next() else defaultT
val u = if (secondIt.hasNext()) secondIt.next() else defaultU
return t to u
}
}.asSequence().toList()
}
fun <K, V> zipKeysValues(keys: List<K>, values: List<V>): Map<K, V> =
keys.zip(values).toMap()
fun <T, U, R> zipWith(first: List<T>, second: List<U>, function: (T, U) -> R): List<R> =
first.zip(second).map { (t, u) -> function(t, u) }
fun <T> zipWithIndex(list: List<T>): List<Pair<Int, T>> =
list.withIndex().map { it.index to it.value }
fun <T> zipWithNext(list: List<T>): List<Pair<T, T>> =
list.zipWithNext()
| [
{
"class_path": "ivan-moto__30-seconds-of-kotlin__772896c/ListKt$zipAll$1.class",
"javap": "Compiled from \"List.kt\"\npublic final class ListKt$zipAll$1 implements java.util.Iterator<kotlin.Pair<? extends T, ? extends U>>, kotlin.jvm.internal.markers.KMappedMarker {\n final java.util.Iterator<T> $firstIt;... |
Prozen__AdventOfCode2018__b0e830f/day03/src/main/kotlin/Main.kt | import java.io.File
fun main() {
val strings = File(ClassLoader.getSystemResource("input.txt").file).readLines()
val field = Array(1000) { Array(1000) { 0 } }
strings.forEach {
val words = it.split(" ")
val start = words[2].dropLast(1).split(",").map { it.toInt() }
val size = words[3].split("x").map { it.toInt() }
(start[0] until start[0] + size[0]).forEach { x ->
(start[1] until start[1] + size[1]).forEach { y ->
field[x][y] += 1
}
}
}
println(field.sumBy { it.count { it > 1 } })
val map = strings.map {
val words = it.split(" ")
val start = words[2].dropLast(1).split(",").map { it.toInt() }
val size = words[3].split("x").map { it.toInt() }
words[0] to (Point(start[0], start[1]) to Point(start[0] + size[0], start[1] + size[1]))
}
println(map.first { pair ->
map.all {
pair.first == it.first ||
doNotOverlap(pair.second.first, pair.second.second, it.second.first, it.second.second)
}
}.first)
}
data class Point(val x: Int, val y: Int)
fun doNotOverlap(l1: Point, r1: Point, l2: Point, r2: Point) =
l1.x >= r2.x || l2.x >= r1.x || l1.y >= r2.y || l2.y >= r1.y | [
{
"class_path": "Prozen__AdventOfCode2018__b0e830f/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 // ... |
lasp91__DigitsRecognizer_using_Kotlin__4907cbb/src/DigitsRecognizer.kt | import java.io.File
import java.util.stream.IntStream
import java.util.concurrent.atomic.AtomicInteger
data class Observation (val label: String , val Pixels: IntArray)
typealias Distance = (IntArray, IntArray) -> Int
typealias Classifier = (IntArray) -> String
typealias Observations = Array<Observation>
fun observationData(csvData: String) : Observation
{
val columns = csvData.split(',')
val label = columns[0]
val pixels = columns.subList(1, columns.lastIndex).map(String::toInt)
return Observation(label, pixels.toIntArray())
}
fun reader(path: String) : Array<Observation>
{
val observations = File(path).useLines { lines ->
lines.drop(1).map(::observationData).toList().toTypedArray() }
return observations
}
val manhattanDistance = { pixels1: IntArray, pixels2: IntArray -> // Using zip and map
val dist = pixels1.zip(pixels2)
.map { p -> Math.abs(p.first - p.second) }
.sum()
dist
}
val manhattanDistanceImperative = fun(pixels1: IntArray, pixels2: IntArray) : Int
{
var dist = 0
for (i in 0 until pixels1.size)
dist += Math.abs(pixels1[i] - pixels2[i])
return dist
}
val euclideanDistance = { pixels1: IntArray, pixels2: IntArray ->
val dist = pixels1.zip(pixels2)
// .map { p -> Math.pow((p.first - p.second).toDouble(), 2.0) }
.map({ p -> val dist = (p.first - p.second); dist * dist })
.sum()
dist
}
val euclideanDistanceImperative = fun(pixels1: IntArray, pixels2: IntArray) : Int
{
var dist = 0
for (i in 0 until pixels1.size)
{
val dif = Math.abs(pixels1[i] - pixels2[i])
dist += dif * dif
}
return dist
}
fun classify(trainingSet: Array<Observation>, dist: Distance, pixels: IntArray) : String
{
val observation = trainingSet.minBy { (_, Pixels) -> dist(Pixels, pixels) }
return observation!!.label
}
fun evaluate(validationSet: Array<Observation>, classifier: (IntArray) -> String) : Unit
{
// val average = validationSet
// .map({ (label, Pixels) -> if (classifier(Pixels) == label) 1.0 else 0.0 })
// .average()
// println("Correct: $average")
//}
val count = validationSet.size
val sum = AtomicInteger(0)
IntStream.range(0, validationSet.size).parallel().forEach { i ->
if (classifier(validationSet[i].Pixels) == validationSet[i].label)
sum.addAndGet(1)
}
println("Correct: ${sum.toDouble() / count}")
}
//-----------------------------------------------------------------------------------------
fun main(args: Array<String>)
{
val trainingPath = "./Data/trainingsample.csv"
val trainingData = reader(trainingPath)
val validationPath = "./Data/validationsample.csv"
val validationData = reader(validationPath)
val manhattanClassifier = fun(pixels: IntArray) : String
{
return classify(trainingData, manhattanDistanceImperative, pixels)
}
val euclideanClassifier = fun(pixels: IntArray) : String
{
return classify(trainingData, euclideanDistanceImperative, pixels)
}
run {
val startTime = System.currentTimeMillis()
println(" Manhattan Kotlin")
evaluate(validationData, manhattanClassifier)
val endTime = System.currentTimeMillis()
val elapsedTime = (endTime - startTime) / 1000.0
println(">>> Elapsed time is: $elapsedTime sec")
}
run {
val startTime = System.currentTimeMillis()
println(" Euclidean Kotlin")
evaluate(validationData, euclideanClassifier)
val endTime = System.currentTimeMillis()
val elapsedTime = (endTime - startTime) / 1000.0
println(">>> Elapsed time is: $elapsedTime sec")
}
}
| [
{
"class_path": "lasp91__DigitsRecognizer_using_Kotlin__4907cbb/DigitsRecognizerKt.class",
"javap": "Compiled from \"DigitsRecognizer.kt\"\npublic final class DigitsRecognizerKt {\n private static final kotlin.jvm.functions.Function2<int[], int[], java.lang.Integer> manhattanDistance;\n\n private static f... |
Trilgon__LearningKotlin__8273ff6/src/main/kotlin/Main.kt | import java.util.*
fun main(args: Array<String>) {
val input: StringBuilder = StringBuilder("10.3 + -2")
val queueNumbers: Queue<Double> = LinkedList<Double>()
val queueActions: Queue<Char> = LinkedList<Char>()
println('\"' + input.toString() + '\"')
prepareIn(input, queueNumbers, queueActions)
calculateIn(queueNumbers, queueActions)
}
fun prepareIn(input: StringBuilder, queueNumbers: Queue<Double>, queueActions: Queue<Char>) {
var numDetected = false
var startIndex = 0
val trimmedIn = input.filter { !it.isWhitespace() }
for (i in 0..trimmedIn.lastIndex) {
when {
trimmedIn[i].isDigit() && !numDetected -> {
startIndex = i
numDetected = true
}
!trimmedIn[i].isDigit() && numDetected && trimmedIn[i] != '.' -> {
queueNumbers.add(trimmedIn.substring(startIndex, i).toDouble())
queueActions.add(trimmedIn[i])
numDetected = false
}
!trimmedIn[i].isDigit() && !numDetected && trimmedIn[i] == '-' -> {
startIndex = i
numDetected = true
}
}
}
if (numDetected) {
queueNumbers.add(trimmedIn.substring(startIndex..trimmedIn.lastIndex).toDouble())
}
println(queueNumbers)
println(queueActions)
}
fun calculateIn(queueNumbers: Queue<Double>, queueActions: Queue<Char>) {
var action: Char
var result = queueNumbers.poll()
var operand: Double
while (!queueNumbers.isEmpty()) {
operand = queueNumbers.poll()
action = queueActions.poll()
when (action) {
'-' -> result -= operand
'+' -> result += operand
'*' -> result *= operand
'/' -> result /= operand
'%' -> result = result % operand * -1.0
}
}
var pointNum = 8.3
println("pointNum = " + pointNum)
println(if(pointNum.compareTo(pointNum.toInt()) == 0) pointNum.toInt() else pointNum)
println("result = " + result)
println(if(result.compareTo(result.toInt()) == 0) result.toInt() else result)
}
| [
{
"class_path": "Trilgon__LearningKotlin__8273ff6/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 ... |
sukritishah15__DS-Algo-Point__1b6040f/Kotlin/DiameterBinaryTree.kt | /**
* Algorithm: Diameter of Binary Tree
* Language: Kotlin
* Input:
* Sample Binary Tree
* Output:
* Diameter of Binary Tree
* Time Complexity: O(n) as we are visiting every node once.
* Space Complexity: O(d) where d is the depth of the binary tree
*
* Sample Input:
* 8
* / \
* 3 10
* / \ \
* 1 6 14
* / \ /
* 4 7 13
*
* Sample Output:
* Diameter of Binary Tree: 6
*/
import kotlin.math.max
class BinaryTree(var value: Int) {
var leftChild: BinaryTree? = null
var rightChild: BinaryTree? = null
}
class DiameterBinaryTree {
private fun dfs(root: BinaryTree?): Pair<Int, Int> {
if (root == null) {
return Pair(0, 0)
}
val leftChild = dfs(root.leftChild)
val rightChild = dfs(root.rightChild)
val diameter = max(leftChild.first, max(rightChild.first, leftChild.second + rightChild.second))
return Pair(diameter, max(leftChild.second, rightChild.second) + 1)
}
fun diameterOfBinaryTree(root: BinaryTree?): Int {
return dfs(root).first
}
}
fun main() {
val tree = BinaryTree(8)
tree.leftChild = BinaryTree(3)
tree.rightChild = BinaryTree(10)
tree.leftChild?.leftChild = BinaryTree(1)
tree.leftChild?.rightChild = BinaryTree(6)
tree.leftChild?.rightChild?.leftChild = BinaryTree(4)
tree.leftChild?.rightChild?.rightChild = BinaryTree(7)
tree.rightChild?.rightChild = BinaryTree(14)
tree.rightChild?.rightChild?.leftChild = BinaryTree(13)
val diam = DiameterBinaryTree()
val diameter = diam.diameterOfBinaryTree(tree)
println("Diameter of Binary Tree: $diameter")
}
| [
{
"class_path": "sukritishah15__DS-Algo-Point__1b6040f/DiameterBinaryTreeKt.class",
"javap": "Compiled from \"DiameterBinaryTree.kt\"\npublic final class DiameterBinaryTreeKt {\n public static final void main();\n Code:\n 0: new #8 // class BinaryTree\n 3: dup\n ... |
sukritishah15__DS-Algo-Point__1b6040f/Kotlin/LongestCommonSubSequence.kt | /**
* Algorithm: Longest Common Sub-Sequence using Dynamic Programming
* Language: Kotlin
* Input:
* String1 and String2 -> Two Strings
* Output:
* Integer -> The longest common sub-sequence of String1 and String2
* Time Complexity: O(nStr1*nStr2)
* Space Complexity: O(nStr1*nStr2)
*
* Sample Input:
* Enter the first String:
* AGGTAB
* Enter the second String:
* GXTXAYB
*
* Sample Output:
* The length of longest common sub-sequence is:
*/
import kotlin.math.max
class LongestCommonSubSequence {
fun longestCommonSubSequence(str1: String, str2: String): Int {
val nStr1 = str1.length
val nStr2 = str2.length
val dp = Array(nStr1 + 1) { IntArray(nStr2 + 1) }
(1 until nStr1 + 1).forEach { i ->
(1 until (nStr2 + 1)).forEach { j ->
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1]
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[nStr1][nStr2]
}
}
fun main() {
println("Enter the first string: ")
val string1 = readLine()!!
println("Enter the second string: ")
val string2 = readLine()!!
val lcs = LongestCommonSubSequence()
println("The length of longest common sub-sequence is: ${lcs.longestCommonSubSequence(string1, string2)}")
} | [
{
"class_path": "sukritishah15__DS-Algo-Point__1b6040f/LongestCommonSubSequence.class",
"javap": "Compiled from \"LongestCommonSubSequence.kt\"\npublic final class LongestCommonSubSequence {\n public LongestCommonSubSequence();\n Code:\n 0: aload_0\n 1: invokespecial #8 // M... |
sukritishah15__DS-Algo-Point__1b6040f/Kotlin/MergeSort.kt | /**
* Algorithm: Merge Sorting
* Language: Kotlin
* Input:
* a) n: Size of Array
* b) arr: Integer Array of size n
* Output:
* a) Array before applying Merge Sorting
* b) Array after applying Merge Sorting
* Time Complexity: O(n * log n)
* Space Complexity: O(n)
*
* Sample Input:
* Enter the size of the integer array:
* 5
* Enter an integer array:
* 5 4 8 2 1
*
* Sample Output:
* Array before sorting is:
* 5 4 8 2 1
* Array after sorting is:
* 1 2 4 5 8
*/
import MergeSort.Companion.printIArray
import java.util.*
class MergeSort {
fun mergeSort(array: IntArray) {
val n = array.size
if (n < 2) return
val mid = n / 2
val left = IntArray(mid)
val right = IntArray(n - mid)
for (i in 0 until mid) left[i] = array[i]
for (i in mid until n) right[i - mid] = array[i]
mergeSort(left)
mergeSort(right)
merge(left, right, array)
}
private fun merge(left: IntArray, right: IntArray, array: IntArray) {
val nLeft = left.size
val nRight = right.size
var i = 0
var j = 0
var k = 0
while (i < nLeft && j < nRight) {
if (left[i] <= right[j]) {
array[k] = left[i]
k++
i++
} else {
array[k] = right[j]
k++
j++
}
}
while (i < nLeft) {
array[k] = left[i]
i++
k++
}
while (j < nRight) {
array[k] = right[j]
j++
k++
}
}
companion object {
fun printIArray(array: IntArray) {
println(array.joinToString(" "))
}
}
}
fun main() {
val scanner = Scanner(System.`in`)
println("Enter the size of the integer array: ")
val n = scanner.nextInt()
println("Enter an integer array: ")
val arr = IntArray(n)
arr.indices.forEach {
arr[it] = scanner.nextInt()
}
val merge = MergeSort()
println("Array before sorting is: ")
printIArray(arr)
merge.mergeSort(arr)
println("Array after sorting is: ")
printIArray(arr)
} | [
{
"class_path": "sukritishah15__DS-Algo-Point__1b6040f/MergeSort$Companion.class",
"javap": "Compiled from \"MergeSort.kt\"\npublic final class MergeSort$Companion {\n private MergeSort$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<ini... |
dlew__kotlin-riddler__55e9d2f/src/binary.kt | /**
* Proof for the Riddler problem from March 18, 2016
*
* http://fivethirtyeight.com/features/can-you-best-the-mysterious-man-in-the-trench-coat/
*/
fun main(args: Array<String>) {
findBestOutcome(1, 1000, 9)
}
fun findBestOutcome(lowerBound: Int, upperBound: Int, maxGuesses: Int, verbose: Boolean = false) {
var best = 0
var bestGuess = 0
for (guess in lowerBound..upperBound) {
val outcome = outcome(lowerBound, upperBound, maxGuesses, guess)
if (outcome > best) {
best = outcome
bestGuess = guess
}
if (verbose) {
println(String.format("Guessing %d yields an outcome of %d", guess, outcome))
}
}
println(String.format("Best outcome: guess %d", bestGuess))
}
/**
* A measure of how profitable a guess will be - the sum of all successful amounts it can get to
*/
fun outcome(lowerBound: Int, upperBound: Int, maxGuesses: Int, guess: Int): Int {
var outcome = 0
for (actual in lowerBound..upperBound) {
val result = binary(lowerBound, upperBound, guess, actual)
if (result <= maxGuesses) {
outcome += actual
}
}
return outcome
}
/**
* Counts how many times it takes to guess the amount of money.
*
* This is a non-standard binary search because it allows you to start
* on any number (but splits the halves after that).
*/
fun binary(lowerBound: Int, upperBound: Int, guess: Int, actual: Int): Int {
if (lowerBound > upperBound
|| guess < lowerBound || guess > upperBound
|| actual < lowerBound || actual > upperBound) {
throw IllegalArgumentException("You entered something wrong...")
}
var left: Int = lowerBound
var right: Int = upperBound
var iterations: Int = 0
var isFirst: Boolean = true
while (true) {
// On the first runthrough, don't calculate the midpoint; use the guess provided
val current = if (isFirst) guess else (left + right) / 2
isFirst = false
iterations += 1 // Each time we do this, it counts as a guess
if (current == actual) {
break;
} else if (current < actual) {
left = current + 1
} else if (current > actual) {
right = current - 1
}
}
return iterations
} | [
{
"class_path": "dlew__kotlin-riddler__55e9d2f/BinaryKt.class",
"javap": "Compiled from \"binary.kt\"\npublic final class BinaryKt {\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 ... |
algorithm-archivists__algorithm-archive__38c40e0/contents/thomas_algorithm/code/kotlin/thomas.kt | private fun thomas(a: DoubleArray, b: DoubleArray, c: DoubleArray, d: DoubleArray): DoubleArray {
val cPrime = c.clone()
val x = d.clone()
val size = a.size
cPrime[0] /= b[0]
x[0] /= b[0]
for (i in 1 until size) {
val scale = 1.0 / (b[i] - cPrime[i - 1] * a[i])
cPrime[i] *= scale
x[i] = (x[i] - a[i] * x[i - 1]) * scale
}
for (i in (size - 2) downTo 0) {
x[i] -= cPrime[i] * x[i + 1]
}
return x
}
fun main(args: Array<String>) {
val a = doubleArrayOf(0.0, 2.0, 3.0)
val b = doubleArrayOf(1.0, 3.0, 6.0)
val c = doubleArrayOf(4.0, 5.0, 0.0)
val x = doubleArrayOf(7.0, 5.0, 3.0)
val solution = thomas(a, b, c, x)
println("System:")
println("[%.1f, %.1f, %.1f][x] = [%.1f]".format(b[0], c[0], 0f, x[0]))
println("[%.1f, %.1f, %.1f][y] = [%.1f]".format(a[1], b[1], c[1], x[1]))
println("[%.1f, %.1f, %.1f][z] = [%.1f]\n".format(0f, a[2], b[2], x[2]))
println("Solution:")
for (i in solution.indices) {
println("[% .5f]".format(solution[i]))
}
}
| [
{
"class_path": "algorithm-archivists__algorithm-archive__38c40e0/ThomasKt.class",
"javap": "Compiled from \"thomas.kt\"\npublic final class ThomasKt {\n private static final double[] thomas(double[], double[], double[], double[]);\n Code:\n 0: aload_2\n 1: invokevirtual #10 ... |
victorYghor__Kotlin-Problems__0d30e37/Create-an-euphonious-word/src/main/kotlin/Main.kt | val vowels: List<Char> = listOf('a', 'e', 'i', 'o', 'u', 'y')
val consonants: List<Char> = listOf('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z')
fun fixClusterVowels(cluster: String): String {
val listOfVowels: MutableList<Char> = cluster.toMutableList()
val correctionI = listOfVowels.size / 2
for (i in 2 until(listOfVowels.lastIndex + correctionI) step 3) {
listOfVowels.add(i, consonants.random())
}
return listOfVowels.joinToString("")
}
fun fixClusterConsonants(cluster:String): String {
val listOfConsonants: MutableList<Char> = cluster.toMutableList()
val correctionI = listOfConsonants.size / 2
for (i in 2 until(listOfConsonants.lastIndex + correctionI) step 3) { // start in the index 2 because a vowel is put in the 3rd element if a put index 3 the word fit in the 4th and don't solve the problem
listOfConsonants.add(i, vowels.random())
}
return listOfConsonants.joinToString("")
}
fun findClusters(word: String): List<Int?> {
val clusterIndices: List<Int?>
for (i in word.indices) {
var quantV = 0
do {
if (vowels.contains(word[i + quantV]) && i + quantV + 1 <= word.lastIndex) {
++quantV
} else if (i + quantV == word.lastIndex && vowels.contains(word[i + quantV])) {
++quantV
}
} while (i + quantV <= word.lastIndex && vowels.contains(word[i + quantV]))
if (quantV >= 3) {
clusterIndices = listOf(i, i + quantV)
return clusterIndices
}
var quantC = 0
do {
if (consonants.contains(word[i + quantC]) && i + quantC + 1 <= word.lastIndex) {
++quantC
} else if (i + quantC == word.lastIndex && consonants.contains(word[i + quantC])) {
++quantC
}
} while (i + quantC <= word.lastIndex && consonants.contains(word[i + quantC]))
if (quantC >= 3) {
clusterIndices = listOf(i, i + quantC)
return clusterIndices
}
}
clusterIndices = listOf(null)
return clusterIndices
}
fun solveClusters(wordParam: String): String {
var word = wordParam
var indexCluster = findClusters(word)
while (indexCluster[0] != null) {
val cluster: String = word.substring(indexCluster[0] ?: 0, indexCluster[1] ?: 0)
if (vowels.contains(cluster[0])) {
val fixedCluster = fixClusterVowels(cluster)
word = word.replaceFirst(cluster, fixedCluster)
indexCluster = findClusters(word)
} else if (consonants.contains(cluster[0])) {
val fixedCluster = fixClusterConsonants(cluster)
word = word.replaceFirst(cluster, fixedCluster)
indexCluster = findClusters(word)
} else {
break
}
}
return word
}
fun main() {
val word = readln()
println(solveClusters(word))
println(solveClusters(word).length - word.length)
}
/*
val vowels: List<Char> = listOf('a', 'e', 'i', 'o', 'u', 'y')
val consonants: List<Char> = listOf('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n',
'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z')
fun findClusters(word: String):MutableList<Int?> {
val sizesOfClusters: MutableList<Int?> = mutableListOf()
var countV = 2
var countC = 2
var lastLetter: Char? = null
var nextToLetter: Char? = null
for (letter in word) {
if (vowels.contains(letter) && (if (lastLetter != null ) vowels.contains(lastLetter) else false) && vowels.contains(nextToLetter)) {
++countV
} else if (consonants.contains(letter) && (if (lastLetter != null ) consonants.contains(lastLetter) else false) && consonants.contains(nextToLetter)){
++countC
} else if (countV >= 3) {
sizesOfClusters.add(countV)
countV = 2
} else if (countC >= 3) {
sizesOfClusters.add(countC)
countC = 2
}
nextToLetter = lastLetter
lastLetter = letter
}
if (countV >= 3) {
sizesOfClusters.add(countV)
} else if (countC >= 3) {
sizesOfClusters.add(countC)
}
return sizesOfClusters
}
fun lettersToPut(clusters: MutableList<Int?>): Int {
if (clusters.size == 0) {
return 0
}
for (i in clusters.indices) {
if (clusters[i]!! % 2 == 0 ) {
clusters[i] = clusters[i]!! / 2 - 1
} else if (clusters[i]!! % 2 == 1) {
clusters[i] = clusters[i]!! / 2
}
}
var sum = 0
for (size in clusters){
sum += size!!
}
return sum
}
fun main() {
val word = readln()
println(lettersToPut(findClusters(word)))
}
*/
| [
{
"class_path": "victorYghor__Kotlin-Problems__0d30e37/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n private static final java.util.List<java.lang.Character> vowels;\n\n private static final java.util.List<java.lang.Character> consonants;\n\n public static final java.u... |
joshpierce__advent-of-code-22__fd5414c/src/Day07.kt | import java.io.File
// I'm not proud of this, but it works.
fun main() {
var lines: List<String> = File("Day07.txt").readLines()
var fileSystem: MutableList<Obj> = mutableListOf()
fileSystem.add(Obj("/", ObjectType.Directory, 0))
var currentObj: Obj = fileSystem[0]
for (i in 0..lines.size - 1) {
//println("Current Line: " + lines[i])
//currentObj.children.forEach { println("Object under " + currentObj.objName + " | " + it.objName + " | " +it.objType.toString() + " | " + it.parent!!.objName) }
var parts = lines[i].split(" ")
when (parts[0]) {
"$" -> {
when (parts[1]) {
"cd" -> {
when (parts[2]) {
"/" -> {
// Go to root
//println("Changing current obj to root")
currentObj = fileSystem[0]
}
".." -> {
//println("Changing current obj to parent " + currentObj.parent!!.objName)
currentObj = currentObj.parent!!
}
else -> {
var target = currentObj.children.filter { it.objName == parts[2] }.first()
//println("Changing current obj to " + target.objName)
currentObj = target
}
}
}
"ls" -> {
//println("Listing directory: " + currentObj.objName)
var nextCommandLine = lines.slice(i+1..lines.size - 1).indexOfFirst { it.split(" ")[0] == "$" } + i + 1
if (i == nextCommandLine) {
nextCommandLine = lines.size
}
//println("nextCommandLine is " + nextCommandLine.toString())
//println("i is " + i.toString())
for (idx in i+1..nextCommandLine - 1) {
var lsParts = lines[idx].split(" ")
when (lsParts[0]) {
"dir" -> {
if (currentObj.children.filter { it.objName == lsParts[1] && it.objType == ObjectType.Directory }.count() == 0) {
//println("Adding directory: " + lsParts[1] + " to " + currentObj.objName)
currentObj.children.add(Obj(lsParts[1], ObjectType.Directory, 0, currentObj))
}
}
else -> {
if (currentObj.children.filter { it.objName == lsParts[1] && it.objType == ObjectType.File }.count() == 0) {
//println("Adding file: " + lsParts[1] + " to " + currentObj.objName)
currentObj.children.add(Obj(lsParts[1], ObjectType.File, lsParts[0].toInt(), currentObj))
}
}
}
}
}
}
}
else -> {
// This is a file
print("")
}
}
}
println("------------")
printStructure(fileSystem[0], 0)
var sizes = getDirectoriesWithSizes(fileSystem[0])
sizes.sortByDescending { it.size }
sizes.forEach { println(it.path + " | " + it.size.toString()) }
println("Part 1 size: " + sizes.filter { it.size < 100000 }.sumOf { it.size }.toString())
var freeSpace = 70000000 - sizes[0].size
println("Total Free Space is " + freeSpace.toString())
var validSizes = sizes.filter { it.size + freeSpace > 30000000 }.toMutableList()
validSizes.sortBy { it.size }
validSizes.forEach {
println("Valid Size: " + it.path + " | " + it.size.toString())
}
println("Smallest Directory To Achieve Goal is " + validSizes[0].path.toString() + " | " + validSizes[0].size.toString())
}
fun printStructure(obj: Obj, level: Int) {
var indent = ""
for (i in 0..level) {
indent += " "
}
indent += "- "
if (obj.objType == ObjectType.Directory) {
println(indent + obj.objName)
} else {
println(indent + obj.objName + " | " + obj.objSize.toString())
}
obj.children.forEach {
printStructure(it, level + 1)
}
}
fun getDirectoriesWithSizes(obj: Obj): MutableList<DirectoryInfo> {
var directorySizes: MutableList<DirectoryInfo> = mutableListOf()
if (obj.objType == ObjectType.Directory) {
directorySizes.add(DirectoryInfo(obj.objName, 0))
}
obj.children.forEach {
if (it.objType == ObjectType.Directory) {
directorySizes.add(DirectoryInfo(it.objName, 0))
} else {
directorySizes[0].size += it.objSize
}
}
obj.children.forEach {
if (it.objType == ObjectType.Directory) {
var childSizes = getDirectoriesWithSizes(it)
directorySizes[0].size += childSizes[0].size
directorySizes.addAll(childSizes)
}
}
return directorySizes.filter { it.size > 0 }.toMutableList()
}
enum class ObjectType {
Directory,
File
}
class DirectoryInfo(path: String, size: Int) {
var path: String = path
var size: Int = size
}
class Obj(objName: String, objType: ObjectType, objSize: Int, parent: Obj? = null) {
var objName: String = objName
var objType: ObjectType = objType
var objSize: Int = objSize
var children: MutableList<Obj> = mutableListOf()
var parent: Obj? = parent
}
| [
{
"class_path": "joshpierce__advent-of-code-22__fd5414c/Day07Kt$main$$inlined$sortBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class Day07Kt$main$$inlined$sortBy$1<T> implements java.util.Comparator {\n public Day07Kt$main$$inlined$sortBy$1();\n Code:\n 0: aload_0\n ... |
joshpierce__advent-of-code-22__fd5414c/src/Day15.kt | import java.io.File
import kotlin.collections.fill
import java.math.BigInteger
// So... this returned a couple possible solutions for part 2, the first one that came out ended up being correct
// and it's 01:28a so I'm going to bed. Hopefully I'll find time tomorrow to come back to this to clean it up.
fun main() {
var validMin: Int = 0
var validMax: Int = 4000000
var rowCheck: Int = 2000000
var directions: List<String> = File("Day15.txt").readLines()
var sbpairs: MutableList<Pair<Pair<Int, Int>, Pair<Int, Int>>> = directions.map {
val parts = it.replace("Sensor at x=", "")
.replace(", y=", ",")
.replace(": closest beacon is at x=", ",")
.split(",")
Pair(Pair(parts[0].toInt(), parts[1].toInt()), Pair(parts[2].toInt(), parts[3].toInt()))
}.toMutableList()
// get all x and y values with the same euclidian distance to the beacon in a specified row
var points: MutableSet<Pair<Int, Int>> = mutableSetOf()
sbpairs.forEach {
var possPoints = getPoints(it.first, it.second, rowCheck)
var beacons = sbpairs.map { it.second }
possPoints.forEach {
if (!beacons.contains(it)) {
points.add(it)
}
}
}
println("Part 1 Answer: ${points.size}")
println()
var possPoints: MutableList<Pair<Int, Int>> = mutableListOf()
sbpairs.forEach {
//println("Getting Diamond For ${it.first.toString()} to ${it.second.toString()}")
possPoints.addAll(getDiamondOutsides(it.first, it.second))
}
// Don't run this for the large grid or you're going to have a bad time
// var innerPoints: MutableList<Pair<Int, Int>> = mutableListOf()
// sbpairs.forEach {
// innerPoints.addAll(getPoints(it.first, it.second, -1))
// }
// for (i in validMin..validMax) {
// for (j in validMin..validMax) {
// if (sbpairs.map { it.second }.contains(Pair(j, i))) {
// print("🟣")
// }
// else if (sbpairs.map { it.first }.contains(Pair(j, i))) {
// print("🟢")
// }
// else if (innerPoints.contains(Pair(j, i))) {
// print("⚫️")
// } else {
// print("🤪")
// }
// }
// println()
// }
// Sort the possible points by x and then y so that we can find duplicates
possPoints.sortWith(compareBy({ it.first }, { it.second }))
// Run through the list sequentially and tally up the duplicates
var dups: MutableList<Pair<Pair<Int, Int>, Int>> = mutableListOf()
var i: Int = 0
while (i <= possPoints.size - 1) {
if (possPoints[i].first >= validMin && possPoints[i].first <= validMax && possPoints[i].second >= validMin && possPoints[i].second <= validMax && i < possPoints.size - 1) {
if (possPoints[i] == possPoints[i+1]) {
var count = 1
while (possPoints[i] == possPoints[i+count]) {
count++
}
dups.add(Pair(possPoints[i], count))
i += (count - 1)
} else {
i++
}
} else {
i++
}
}
// Sort the duplicates by the number of duplicates to test the most likely locations first
dups.sortByDescending({ it.second })
// Get a map of our sensors and beacons and distances for testing
var beacons: List<SBPair> = sbpairs.map { SBPair(it.first, it.second, getDistance(it.first, it.second)) }
var distressLocation: Pair<Int, Int> = Pair(0, 0)
run dups@ {
dups.forEach { dup ->
//println("Testing For Distress Location @ ${dup.first.toString()} | ${dup.second} duplicates")
var isValid = true
beacons.forEach beacon@ { beacon ->
if (getDistance(dup.first, beacon.start) <= beacon.distance) {
isValid = false
return@beacon
}
}
if (isValid) {
//println("Found our distress location: ${dup.first.toString()}")
distressLocation = dup.first
return@dups
}
}
}
println("Part 2 Answer: | ${(BigInteger(distressLocation.first.toInt().toString()).multiply(BigInteger("4000000"))).plus(BigInteger(distressLocation.second.toInt().toString()))}")
}
class SBPair(start: Pair<Int, Int>, end: Pair<Int, Int>, distance: Int) {
var start: Pair<Int, Int> = start
var end: Pair<Int, Int> = end
var distance: Int = distance
}
enum class DiamondDirection {
DOWNLEFT, DOWNRIGHT, UPRIGHT, UPLEFT
}
fun getPointsAround(start: Pair<Int,Int>): MutableList<Pair<Int, Int>> {
val points: MutableList<Pair<Int, Int>> = mutableListOf()
points.add(Pair(start.first - 1, start.second))
points.add(Pair(start.first + 1, start.second))
points.add(Pair(start.first, start.second - 1))
points.add(Pair(start.first, start.second + 1))
return points
}
fun getDistance(start: Pair<Int, Int>, end: Pair<Int, Int>): Int {
val xDiff = start.first - end.first
val yDiff = start.second - end.second
return Math.abs(xDiff) + Math.abs(yDiff)
}
fun getDiamondOutsides(start: Pair<Int, Int>, end: Pair<Int, Int>): MutableList<Pair<Int, Int>> {
val points: MutableList<Pair<Int, Int>> = mutableListOf()
// Adding 1 to the distance to get the points just outside the diamond
val distance = getDistance(start, end) + 1
var iterator = Pair(0,distance)
do {
if (iterator.second != 0) points.add(Pair(start.first + iterator.first, start.second + iterator.second))
if (iterator.second != 0) points.add(Pair(start.first + iterator.first, start.second - iterator.second))
if (iterator.first != 0) points.add(Pair(start.first - iterator.first, start.second + iterator.second))
if (iterator.first != 0) points.add(Pair(start.first - iterator.first, start.second - iterator.second))
iterator = Pair(iterator.first + 1, iterator.second - 1)
} while (iterator.second != 0)
return points
}
fun getPoints(start: Pair<Int, Int>, end: Pair<Int, Int>, row: Int): List<Pair<Int, Int>> {
val points: MutableList<Pair<Int, Int>> = mutableListOf()
val distance = getDistance(start, end)
if (row != -1) {
for (i in (start.first-distance)..(start.first+distance)) {
var testXDiff = start.first - i
var testYDiff = start.second - row
if (Math.abs(testXDiff) + Math.abs(testYDiff) <= distance) {
points.add(Pair(i, row))
}
}
} else {
for (i in (start.first-distance)..(start.first+distance)) {
for (j in (start.second-distance)..(start.second+distance)) {
var testXDiff = start.first - i
var testYDiff = start.second - j
if (Math.abs(testXDiff) + Math.abs(testYDiff) <= distance) {
points.add(Pair(i, j))
}
}
}
}
return points
} | [
{
"class_path": "joshpierce__advent-of-code-22__fd5414c/Day15Kt.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15Kt {\n public static final void main();\n Code:\n 0: iconst_0\n 1: istore_0\n 2: ldc #7 // int 4000000\n 4: istore_1\n ... |
joshpierce__advent-of-code-22__fd5414c/src/Day13.kt | import java.io.File
fun main() {
var directions: List<String> = File("Day13.txt").readLines()
var pairs = directions.chunked(3).map { Pair(it[0], it[1])}
var validIndexes: MutableList<Int> = mutableListOf()
var allPackets: MutableList<Any> = mutableListOf()
pairs.forEachIndexed { idx, it ->
println("== Pair ${idx+1} ==")
var left = parseList(it.first.substring(1, it.first.length - 1))
allPackets.add(left)
var right = parseList(it.second.substring(1, it.second.length - 1))
allPackets.add(right)
println("- Compare ${left.toString()} vs ${right.toString()}")
if(compare(left, right, 0) == 1) {
validIndexes.add(idx+1)
}
println("")
}
//Part 1
println("Sum Of Valid Indexes Is: ${validIndexes.sum()}")
//Part 2
val comparator = Comparator { a: Any, b: Any ->
return@Comparator compare(a as MutableList<Any>, b as MutableList<Any>, 0)
}
allPackets.sortWith(comparator)
var pkt2Index: Int = 0
var pkt6Index: Int = 0
allPackets.reversed().forEachIndexed { idx, it ->
println("${idx+1} - ${it.toString()}")
if (it.toString() == "[[2]]") pkt2Index = idx + 1
if (it.toString() == "[[6]]") pkt6Index = idx + 1
}
println("The Decoder Key is ${pkt2Index * pkt6Index}")
}
fun compare(left: MutableList<Any>, right: MutableList<Any>, level: Int): Int {
left.forEachIndexed { idx, leftVal ->
if (right.size < idx + 1) {
println("Right (${right.toString()}) List Is Shorter (${right.size}) Than Left List, Stopping Checks - INVALID ❌❌❌")
return -1
}
println("${"".padStart(level*2)}- Compare ${leftVal} vs ${right[idx]}")
if (leftVal is Int && right[idx] is Int) {
// both Values are ints, make sure that left is <= right to continue
if (leftVal.toString().toInt() == right[idx].toString().toInt()) {
return@forEachIndexed
} else if (leftVal.toString().toInt() < right[idx].toString().toInt()) {
println("LeftVal: ${leftVal} is < than RightVal: ${right[idx]} - VALID ✅✅✅")
return 1
} else {
println("LeftVal: ${leftVal} is > than RightVal: ${right[idx]} - INVALID ❌❌❌")
return -1
}
} else {
var leftToCheck: MutableList<Any> = mutableListOf()
if (leftVal is Int) {
leftToCheck = mutableListOf(leftVal)
} else if (leftVal is MutableList<*>) {
leftToCheck = leftVal as MutableList<Any>
}
var rightToCheck: MutableList<Any> = mutableListOf()
if (right[idx] is Int) {
rightToCheck = mutableListOf(right[idx])
} else if (right[idx] is MutableList<*>) {
rightToCheck = right[idx] as MutableList<Any>
}
// The Right Side is a List, Convert the Left Side To A List and Compare
var innerCheck = compare(leftToCheck, rightToCheck, level + 1)
if (innerCheck == 0) {
return@forEachIndexed
} else {
return innerCheck
}
}
}
// According to the Rules we shouldn't get here as our ultimate check??
if(left.size < right.size) {
println("Left List Is Smaller Than Right List, But All Items Are The Same - VALID ✅✅✅")
return 1
} else {
return 0
}
}
fun parseList(str: String): MutableList<Any> {
//println("Parser Started for | ${str}")
var newList: MutableList<Any> = mutableListOf()
var idx: Int = 0
while (idx < str.length) {
//println("Idx ${idx.toString()} | Char ${str.get(idx).toString()}")
if (str.get(idx) == '[') {
var endBracketPos = getValidCloseBracket(str.substring(idx, str.length))
//println("Found Valid Close Bracket | Start ${idx} | End ${endBracketPos}")
newList.add(parseList(str.substring(idx+1, idx+endBracketPos)))
idx = idx+endBracketPos + 1
} else if (listOf(',',']').contains(str.get(idx))) {
idx++
}
else {
// println(str)
//grab addl characters
var tmpstr = str.get(idx).toString()
// println("tmpstr ${tmpstr}")
var tmpidx = idx
// println("tmpidx ${tmpidx}")
while (str.length > tmpidx+1 && !listOf('[',']',',').contains(str.get(tmpidx+1))) {
//println("NextChar: ${str.get(tmpidx+1)}")
tmpstr += str.get(tmpidx+1).toString()
tmpidx++
}
newList.add(tmpstr.toInt())
idx++
}
}
return newList
}
fun getValidCloseBracket(str: String): Int {
//println("Getting Close Bracket Position for ${str}")
var brackets: MutableList<Char> = mutableListOf()
str.toMutableList().forEachIndexed { idx, char ->
if (char == '[') {
brackets.add('[')
} else if (char == ']') {
if (brackets.last() == '[') brackets.removeLast()
if (brackets.size == 0) { return idx }
}
}
return -1
}
| [
{
"class_path": "joshpierce__advent-of-code-22__fd5414c/Day13Kt.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
joshpierce__advent-of-code-22__fd5414c/src/Day03.kt | import java.io.File
fun main() {
// read the lines from the file
var lines: List<String> = File("Day03.txt").readLines()
// sum up the total of all priorities
var total: Int = lines.map {
// Find the priority by intersecting the two lists of items to get the common item
// and then running our itemNumber function
var priority: Int = it.substring(0, it.length / 2).toCharArray().toList()
.intersect(it.substring(it.length / 2).toCharArray().toList())
.elementAt(0).itemNumber()
// Return the priority
return@map priority
}.toMutableList().sum()
// Solution to Part 1
println("The total is: " + total.toString())
// Create an Int Array for the total number of groups of elves
val groups = IntArray((lines.size / 3)) { it }
// Sum up the total of the matching items across each group
val sum = groups.map {
// Figure out the base index for the group
val base = it * 3
// Find the priority by intersecting all three lists of items from the elves
return@map lines[base].toCharArray().toList()
.intersect(lines[base + 1].toCharArray().toList())
.intersect(lines[base + 2].toCharArray().toList())
.elementAt(0).itemNumber()
}.sum()
// Solution to Part 2
println("The total of the badge priorities is: " + sum.toString())
}
// This extension function finds the index of the Character inside the alphabet
fun Char.itemNumber(): Int {
val items = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
return items.indexOf(this) + 1
} | [
{
"class_path": "joshpierce__advent-of-code-22__fd5414c/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: aconst_null\n 1: astore_0\n 2: new #8 // class java/io/File\n 5: d... |
joshpierce__advent-of-code-22__fd5414c/src/Day02.kt | import java.io.File
fun main() {
// read the lines from the file
var lines: List<String> = File("Day02.txt").readLines()
// setup a new list of Games so we can calculate the outcome of each
var games: MutableList<Game> = lines.map {
var parts = it.split(" ")
return@map Game(parts[0].translateRPS(), parts[1].translateRPS())
}.toMutableList()
// calculate the outcome of each game, and sum the scores
println("The sum of the score of all games is: " + games.sumOf { it.score() }.toString())
// setup a new list of Games so we can calculate the outcome of each based on the new rules in part 2
var gamesNew: MutableList<Game> = lines.map {
var parts = it.split(" ")
var oppPick = parts[0].translateRPS()
var myPick: String
// Calculate a Loss
if (parts[1] == "X") {
myPick = when (oppPick) {
"Rock" -> "Scissors"
"Paper" -> "Rock"
"Scissors" -> "Paper"
else -> throw Exception ("Invalid Opponent Pick")
}
}
// Calculate a Draw
else if (parts[1] == "Y") {
myPick = oppPick
}
// Calculate a Win
else {
myPick = when (oppPick) {
"Rock" -> "Paper"
"Paper" -> "Scissors"
"Scissors" -> "Rock"
else -> throw Exception ("Invalid Opponent Pick")
}
}
return@map Game(parts[0].translateRPS(), myPick)
}.toMutableList()
// calculate the outcome of each game, and sum the scores
println("The sum of the score of all games with the new rules is: " + gamesNew.sumOf { it.score() }.toString())
}
class Game(oppPick: String, yourPick: String) {
var oppPick: String = oppPick
var yourPick: String = yourPick
}
fun Game.score(): Int {
var currScore: Int = when (this.yourPick) {
"Rock" -> 1
"Paper" -> 2
"Scissors" -> 3
else -> throw Exception("Invalid RPS")
}
if (this.oppPick == this.yourPick) {
currScore += 3
} else if (this.oppPick == "Rock" && this.yourPick == "Paper" ||
this.oppPick == "Paper" && this.yourPick == "Scissors" ||
this.oppPick == "Scissors" && this.yourPick == "Rock") {
currScore += 6
} else {
currScore += 0
}
return currScore
}
fun String.translateRPS(): String {
return when (this) {
"A", "X" -> "Rock"
"B", "Y" -> "Paper"
"C", "Z" -> "Scissors"
else -> throw Exception("Invalid RPS")
}
} | [
{
"class_path": "joshpierce__advent-of-code-22__fd5414c/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 ... |
joshpierce__advent-of-code-22__fd5414c/src/Day08.kt | import java.io.File
fun main() {
var lines: List<String> = File("Day08.txt").readLines()
// Setup our Forest List of Lists
var forest = lines.map { it.chunked(1) }
// Variable for Tracking Tree Score in Part Two
var maxTreeScore = 0
// Prints out your forest for you to see
//forest.forEach { it.forEach { print(it+" ") }; println() }
// Iterate Our Forest Rows
var visibleForest = forest.mapIndexed { idx, row ->
// Iterate Our Forest Columns
row.mapIndexed row@ { idx2, tree ->
// Get All Trees Above, Below, Left, and Right of Current Tree
var treesLeft = forest[idx].subList(0, idx2).reversed()
var treesRight = forest[idx].subList(idx2+1, forest[idx].size)
var treesAbove = forest.subList(0, idx).map { it[idx2] }.reversed()
var treesBelow = forest.subList(idx+1, forest.size).map { it[idx2] }
// For Part Two, we need to know how many trees are visible from each tree
var visibleTreesLeft = treesLeft.takeWhileInclusive { it < tree }.count()
var visibleTreesRight = treesRight.takeWhileInclusive { it < tree }.count()
var visibleTreesAbove = treesAbove.takeWhileInclusive { it < tree }.count()
var visibleTreesBelow = treesBelow.takeWhileInclusive { it < tree }.count()
//println("Tree: $idx, $idx2 -> $visibleTreesLeft, $visibleTreesRight, $visibleTreesAbove, $visibleTreesBelow")
// For Part Two Calculate The Tree Score and see if it's the new Max Tree Score
var treeScore = visibleTreesLeft * visibleTreesRight * visibleTreesAbove * visibleTreesBelow
if (treeScore > maxTreeScore) {
//println("Tree: $idx, $idx2 -> $treeScore [Current Max Tree Score]")
maxTreeScore = treeScore
} else {
//println("Tree: $idx, $idx2 -> $treeScore")
}
// If this is an edge tree, it's visible
if (idx == 0 || idx2 == 0 || idx == forest.size - 1 || idx2 == row.size - 1) {
//println("Edge: $idx, $idx2")
return@row 1
} else {
// If this is not an edge tree, check if it's visible from one of the edges
if (tree > treesLeft.sortedDescending()[0] ||
tree > treesRight.sortedDescending()[0] ||
tree > treesAbove.sortedDescending()[0] ||
tree > treesBelow.sortedDescending()[0])
{
//println("Not Edge: $idx, $idx2 -> Visible")
return@row 1
} else {
//println("Not Edge: $idx, $idx2 -> Not Visible")
return@row 0
}
}
}
}
// Print out the Visible Forest
//visibleForest.forEach { it.forEach { print(it.toString() + " ") }; println() }
// Display the Total Visible Trees and Max Tree Score
println("Total Visible Trees: " + visibleForest.map { it.sum() }.sum().toString())
println("Max Tree Score: " + maxTreeScore.toString())
}
// Added this function which I found here: https://stackoverflow.com/questions/56058246/takewhile-which-includes-the-actual-value-matching-the-predicate-takewhileinclu
// The existing TakeWhile in Kotlin doesn't include the value that matches the predicate, which is what we need for this problem.
fun <T> List<T>.takeWhileInclusive(predicate: (T) -> Boolean) = sequence {
with(iterator()) {
while (hasNext()) {
val next = next()
yield(next)
if (!predicate(next)) break
}
}
}
| [
{
"class_path": "joshpierce__advent-of-code-22__fd5414c/Day08Kt.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
ArtyomKopan__Formal_Languages__7aa1075/Практика 1/Coding/src/main/kotlin/Main.kt | import java.nio.file.Files
import java.nio.file.Path
fun coding(grammar: List<String>): Map<String, Int> {
val codes = mutableMapOf(
":" to 1,
"(" to 2,
")" to 3,
"." to 4,
"*" to 5,
";" to 6,
"," to 7,
"#" to 8,
"[" to 9,
"]" to 10,
"Eofgram" to 1000
)
var terminalNumber = 51
var nonterminalNumber = 11
var semanticNumber = 101
// кодируем нетерминалы
for (command in grammar) {
if (command == "Eofgram")
break
val nonterm = command.split(" : ")[0]
if (nonterminalNumber <= 50)
codes[nonterm] = nonterminalNumber++
else
break
}
// кодируем терминалы и семантики
for (command in grammar) {
if ("Eofgram" in command)
break
// кодируем семантики
val semantics = command
.split(" ")
.filter { it.matches(Regex("\\$[a-z]+[0-9]*")) }
for (semantic in semantics) {
if (semanticNumber >= 1000) {
break
}
if (semantic !in codes.keys) {
codes[semantic] = semanticNumber++
}
}
// кодируем нетерминалы, обозначенные заглавными буквами
val nonterminals = command
.split(" ")
.filter { it.matches(Regex("[A-Z]+")) }
for (nonterminal in nonterminals) {
if (nonterminalNumber > 50) {
break
}
if (nonterminal !in codes.keys) {
codes[nonterminal] = nonterminalNumber++
}
}
// кодируем терминалы
val rightPartCommand = command.split(" : ")[1]
val terminals = rightPartCommand
.split(" ")
.filter {
it.matches(Regex("'.+'")) ||
it.matches(Regex("[a-z]+"))
}
for (terminal in terminals) {
if (terminalNumber > 100) {
break
}
if (terminal !in codes.keys) {
codes[terminal] = terminalNumber++
}
}
}
val trash = mutableListOf<String>()
for (k in codes) {
if ("Eofgram" in k.key && k.value != 1000)
trash.add(k.key)
}
codes.filterKeys { it == "" || " " in it || it in trash }
return codes
}
fun main() {
println("Введите путь к файлу с описанием грамматики: ")
val pathToInputFile = readlnOrNull() ?: "../expression.txt"
val grammarDescription = Files
.readString(Path.of(pathToInputFile))
.split(" .")
.map { it.trim() }
val codes = coding(grammarDescription)
codes.forEach { (t, u) -> println("$t $u") }
for (line in grammarDescription) {
if ("Eofgram" in line) {
println(1000)
break
}
var buffer = ""
val encodedLine = mutableListOf<Int>()
for (ch in line) {
if (buffer in codes.keys) {
encodedLine.add(codes[buffer] ?: -1)
buffer = ""
} else if (ch != ' ' && ch != '\n' && ch != '\t') {
buffer += ch
}
}
if (buffer in codes.keys) {
encodedLine.add(codes[buffer] ?: -1)
}
encodedLine.forEach { print("$it, ") }
println(codes["."])
}
} | [
{
"class_path": "ArtyomKopan__Formal_Languages__7aa1075/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n public static final java.util.Map<java.lang.String, java.lang.Integer> coding(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #... |
alexaugustobr__kotlin-exercises__c70e56d/src/main/kotlin/exs/FunWithVowels.kt |
val vowelList = listOf<Char>('a', 'e', 'i', 'o', 'u')
fun main(args: Array<String>) {
val vowel = readLine()!!
//val vowel = "aeiouaeiouaeiouaaeeiioouu"
println(longestSubsequence(vowel))
}
fun longestSubsequence(searchVowel: String): Int {
val chars = searchVowel.toCharArray()
val lastIndex = chars.size
var initialIndex = 0
var lastLongestSequence = 0;
while (initialIndex < lastIndex) {
var curretLongestSequence = 0
var currentVowelIndex = 0
for (index in initialIndex until lastIndex) {
if(isVowel(chars[index])) {
val isTheSameVowel = vowelList[currentVowelIndex] == chars[index]
val isNextSequence = currentVowelIndex < vowelList.size - 1
&& vowelList[currentVowelIndex+1] == chars[index]
if (isTheSameVowel) {
curretLongestSequence++
} else if (isNextSequence) {
currentVowelIndex++
curretLongestSequence++
}
}
}
initialIndex += 1
if (curretLongestSequence > lastLongestSequence) lastLongestSequence = curretLongestSequence
}
return lastLongestSequence
}
fun isVowel(c: Char): Boolean {
return vowelList.contains(c)
} | [
{
"class_path": "alexaugustobr__kotlin-exercises__c70e56d/FunWithVowelsKt.class",
"javap": "Compiled from \"FunWithVowels.kt\"\npublic final class FunWithVowelsKt {\n private static final java.util.List<java.lang.Character> vowelList;\n\n public static final java.util.List<java.lang.Character> getVowelLis... |
Scholar17__aoc-2022-in-kotlin__d3d79fb/src/Day04.kt | import java.io.File
fun main() {
fun parseInputCommaAndNewLine(input: String): List<String> {
return input.split(",", "\r\n")
}
fun parseInputDash(input: String): List<Int> {
return input.split("-").map { str ->
str.toInt()
}
}
val fileName =
"src/Day04_sample.txt"
// "src/Day04_quiz.txt"
val input = File(fileName).readText()
val parseComma = parseInputCommaAndNewLine(input)
val parseCommaList = parseComma.chunked(1)
val parseDashList = mutableListOf<List<Int>>()
for (aList in parseCommaList) {
for (element in aList) {
parseDashList.add(parseInputDash(element))
}
}
fun comparedList(input: List<Int>): List<Int> {
val pairValue = mutableListOf<Int>()
if (input.first() == input.last()) {
pairValue.add(input.first())
} else if (input.first() < input.last()) {
for (i in input.first() until input.last() + 1) {
pairValue.add(i)
}
}
return pairValue
}
val modifiedList = mutableListOf<List<Int>>()
for (aList in parseDashList) {
modifiedList.add(comparedList(aList))
}
fun checkContain(input: List<List<Int>>): Boolean {
var isContain = false
for (i in input.indices - 1) {
if (input[i].containsAll(input[i + 1])) {
isContain = true
} else if (input[i + 1].containsAll(input[i])) {
isContain = true
}
}
return isContain
}
fun checkOverlap(input: List<List<Int>>): Boolean {
var isOverlap = false
for (i in input.indices - 1) {
if (input[i].intersect(input[i + 1].toSet()).isNotEmpty()) {
isOverlap = true
}
}
return isOverlap
}
val compareListPart1 = modifiedList.chunked(2)
val compareListPart2 = modifiedList.chunked(2)
var part1Count = 0
var part2Count = 0
for (aList in compareListPart1) {
if (checkContain(aList)) {
part1Count++
}
}
for (aList in compareListPart2) {
if (checkOverlap(aList)) {
part2Count++
}
}
println(compareListPart1)
println(part1Count)
println(compareListPart2)
println(part2Count)
} | [
{
"class_path": "Scholar17__aoc-2022-in-kotlin__d3d79fb/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/Day04_sample.txt\n 2: astore_0\n 3: new #... |
Scholar17__aoc-2022-in-kotlin__d3d79fb/src/Day03_2021.kt | import java.io.File
fun main() {
fun parseInput(input: String): List<List<Int>> {
return input.split("\n").map { bit ->
bit.map {
it.digitToIntOrNull() ?: 0
}
}
}
val filename =
"src/Day03_sample_2021.txt"
// "src/Day03_quiz_2021.txt"
val textInput = File(filename).readText()
val nestedIntList = parseInput(textInput)
println(nestedIntList)
fun maxCounter(input: List<Int>): Int {
return input
.groupingBy { it }
.eachCount()
.maxBy { it.value }.key
}
fun maxCounterValue(input: List<Int>): Int {
return input
.groupingBy { it }
.eachCount()
.maxBy { it.value }.value
}
fun minCounter(input: List<Int>): Int {
return input
.groupingBy { it }
.eachCount()
.minBy { it.value }.key
}
val filterTotalResult = mutableListOf<List<Int>>()
for (i in 0 until nestedIntList.first().size - 1) {
//for each column to list
val columnList = nestedIntList.map { it[i] }
filterTotalResult.add(columnList)
println(columnList)
}
val gammaRate = mutableListOf<Int>()
val epsilonRate = mutableListOf<Int>()
val test = mutableListOf<Int>()
for (aList in filterTotalResult) {
gammaRate.add(maxCounter(aList))
epsilonRate.add(minCounter(aList))
test.add(maxCounterValue(aList))
}
println(test)
var gammaRateInString = ""
var epsilonRateInString = ""
for (s in gammaRate) {
gammaRateInString += s
}
for (s in epsilonRate) {
epsilonRateInString += s
}
println(gammaRateInString)
println(epsilonRateInString)
val gammaRateInInteger = gammaRateInString.toInt(2)
val epsilonRateInInteger = epsilonRateInString.toInt(2)
println(gammaRateInInteger)
println(epsilonRateInInteger)
val powerConsumption = gammaRateInInteger * epsilonRateInInteger
println(powerConsumption)
}
| [
{
"class_path": "Scholar17__aoc-2022-in-kotlin__d3d79fb/Day03_2021Kt$main$minCounter$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Collections.kt\"\npublic final class Day03_2021Kt$main$minCounter$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lang.Integer, java.lang.Integer> {... |
Scholar17__aoc-2022-in-kotlin__d3d79fb/src/Day03.kt | import java.io.File
import kotlin.math.absoluteValue
fun main() {
fun parseInput(input: String): List<String> {
return input.split("\r\n").map { value ->
value
}
}
val fileName =
// "src/Day03_sample.txt"
"src/Day03_quiz.txt"
val inputText = File(fileName).readText()
val inputList = parseInput(input = inputText)
println(inputList)
println()
val part1ChunkList = mutableListOf<List<String>>()
for (aList in inputList) {
part1ChunkList.add(aList.chunked(aList.length / 2))
}
var part2ChunkList: List<List<String>> = inputList.chunked(3)
println(part2ChunkList)
fun findCommonWord(inputList: List<String>): String {
val first = inputList.first().toCharArray()
val second = inputList.last().toCharArray()
var index = ""
for (aList in first) {
if (second.contains(aList)) {
index = aList.toString()
}
}
return index
}
fun findCommonWordPart2(inputList: List<String>): String {
println(inputList)
val result = inputList.map {
it.chunked(1)
}
var commonResult = ""
for (aList in result) {
for (element in aList) {
if (result.all {
it.contains(element)
})
commonResult = element
}
}
println("result")
println(result)
return commonResult
}
val commonResultList = mutableListOf<String>()
for (aList in part2ChunkList) {
commonResultList.add(findCommonWordPart2(aList))
}
println(commonResultList)
val resultList = mutableListOf<String>()
for (aList in part1ChunkList) {
resultList.add(findCommonWord(aList))
}
println()
// println(resultList)
fun findNumericPosition(input: String): Int {
val charArray = input.toCharArray()
var position = 0
for (aList in charArray) {
val temp = aList.code
val lowerMinus = 96 //for lower case
val upperMinus = 38 //for upper case
position = if ((temp <= 122) and (temp >= 97)) temp - lowerMinus else temp - upperMinus
}
return position
}
var sumNumberPart1 = 0
for (aList in resultList) {
sumNumberPart1 += findNumericPosition(aList)
}
println(sumNumberPart1)
var sumNumberPart2 = 0
for (aList in commonResultList) {
sumNumberPart2 += findNumericPosition(aList)
}
println(sumNumberPart2)
} | [
{
"class_path": "Scholar17__aoc-2022-in-kotlin__d3d79fb/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/Day03_quiz.txt\n 2: astore_0\n 3: new #10... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day15.kt | import kotlin.String
import kotlin.collections.List
object Day15 {
fun part1(input: List<String>): String {
val steps = input[0].split(",").map { it.trim() }
return steps.sumOf { hash(it) }.toString()
}
private fun hash(it: String): Int {
return it.toCharArray().fold(0) { acc, c -> ((acc + c.code) * 17) % 256 }
}
fun part2(input: List<String>): String {
val steps = input[0].split(",").map { it.trim() }
val boxes = mutableMapOf<Int, LinkedHashMap<String, Int>>()
steps.forEach {
if (it.contains("-")) {
val label = it.substring(0, it.length - 1)
val box = hash(label)
boxes.getOrPut(box) { linkedMapOf() }.remove(label)
} else {
val (label, focusLength) = it.split("=")
val box = hash(label)
boxes.getOrPut(box) { linkedMapOf() }[label] = focusLength.toInt()
}
}
return boxes.toList().sumOf { (boxNumber, lenses) ->
lenses.values.withIndex().sumOf { (idx, value) ->
(idx + 1) * value * (boxNumber + 1)
}
}.toString()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day15.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15 {\n public static final Day15 INSTANCE;\n\n private Day15();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day1.kt | import kotlin.String
import kotlin.collections.List
object Day1 {
fun part1(input: List<String>): String = input.sumOf(::findFirstAndLastDigit).toString()
private fun findFirstAndLastDigit(i: String): Int {
val digits = i.filter { it.isDigit() }
return (digits.take(1) + digits.takeLast(1)).toInt()
}
fun part2(input: List<String>): String = input.sumOf(::findFirstAndLastDigitV2).toString()
private fun findFirstAndLastDigitV2(i: String): Int {
val words = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
val newI = words.zip(words.indices)
.map { (word, index) -> word to word.first() + index.toString() + word.last() }
.fold(i) { acc, (word, replacement) -> acc.replace(word, replacement) }
return findFirstAndLastDigit(newI)
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day1.class",
"javap": "Compiled from \"Day1.kt\"\npublic final class Day1 {\n public static final Day1 INSTANCE;\n\n private Day1();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day20.kt | object Day20 {
enum class ModuleType {
BROADCASTER,
CONJUNCTION,
FLIP_FLOP
}
enum class PulseType {
HIGH,
LOW
}
data class Pulse(val type: PulseType, val sender: String)
data class Module(
val id: String,
val type: ModuleType,
val destinations: List<String>,
var on: Boolean,
val inputs: MutableSet<String> = mutableSetOf(),
val lastPulses: MutableMap<String, PulseType> = mutableMapOf()
) {
fun process(pulse: Pulse): List<Pair<String, Pulse>> {
lastPulses[pulse.sender] = pulse.type
return when (type) {
ModuleType.BROADCASTER -> destinations.map { it to pulse }
ModuleType.CONJUNCTION -> {
val typeToSend = if (inputs.map { lastPulses[it] ?: PulseType.LOW }.all { it == PulseType.HIGH }) {
PulseType.LOW
} else {
PulseType.HIGH
}
destinations.map { it to Pulse(typeToSend, id) }
}
ModuleType.FLIP_FLOP -> {
if (pulse.type == PulseType.HIGH) {
emptyList()
} else {
val typeToSend = if (on) {
PulseType.LOW
} else {
PulseType.HIGH
}
on = !on
destinations.map { it to Pulse(typeToSend, id) }
}
}
}
}
companion object {
fun parse(input: String): Module {
val (moduleIdAndType, destinations) = input.split(" -> ")
if (moduleIdAndType == "broadcaster") {
return Module(
"broadcaster",
ModuleType.BROADCASTER,
destinations.split(", "),
true
)
}
val type = moduleIdAndType.take(1)
val id = moduleIdAndType.drop(1)
return Module(
id,
when (type) {
"%" -> ModuleType.FLIP_FLOP
"&" -> ModuleType.CONJUNCTION
else -> throw IllegalArgumentException("Unknown module type: $type")
},
destinations.split(", "),
type == "&"
)
}
}
}
fun part1(input: List<String>): String {
val modules = input.map { Module.parse(it) }.associateBy { it.id }
modules.forEach { key, value ->
value.destinations.forEach { modules[it]?.inputs?.add(key) }
}
val presses = (1..1000).map { pushButton(modules) }.flatMap { it.values }.reduce { acc, map ->
(acc.toList() + map.toList())
.groupBy { it.first }
.mapValues { it.value.map { it.second }.sum() }
}
return presses.values.reduce(Long::times).toString()
}
private fun pushButton(modules: Map<String, Module>): Map<String, Map<PulseType, Long>> {
val initialModule = modules["broadcaster"]!!
val initialPulse = Pulse(PulseType.LOW, "broadcaster")
val queue = ArrayDeque<Pair<Module?, Pulse>>(listOf(initialModule to initialPulse))
val pulseTypeMap = mutableMapOf<String, MutableMap<PulseType, Long>>()
pulseTypeMap["broadcaster"] = mutableMapOf(PulseType.LOW to 1L)
while (queue.isNotEmpty()) {
val (module, pulse) = queue.removeFirst()
val destinations = module?.process(pulse) ?: emptyList()
destinations.forEach { (destination, pulse) ->
val moduleMap = pulseTypeMap.getOrPut(destination) { mutableMapOf() }
moduleMap[pulse.type] = moduleMap.getOrDefault(pulse.type, 0) + 1
}
queue.addAll(destinations.map { (destination, pulse) -> modules[destination] to pulse })
}
return pulseTypeMap
}
private fun numberOfButtonPushesUntilLowState(modules: Map<String, Module>, key: String): Long {
val initialModule = modules["broadcaster"]!!
val initialPulse = Pulse(PulseType.LOW, "broadcaster")
val queue = ArrayDeque<Pair<Module?, Pulse>>(listOf(initialModule to initialPulse))
var count = 1L
// We know the input to the target is a cond, so we can just find when the inputs to the cond are all high
val targetInput =
modules.values.find { it.destinations.contains(key) } ?: throw IllegalStateException("Invalid input: $key")
val inputsOfTargetInput = targetInput.inputs.toSet()
val countWhenHighPulse = mutableMapOf<String, Long>()
while (true) {
if (countWhenHighPulse.size == inputsOfTargetInput.size) {
return countWhenHighPulse.values.reduce(Long::times)
}
val (module, pulse) = queue.removeFirst()
val destinations = module?.process(pulse) ?: emptyList()
val destinationsToPulses = destinations.map { (destination, pulse) -> modules[destination] to pulse }
destinationsToPulses.forEach { (desination, pulse) ->
if ((desination?.id ?: "") == targetInput.id)
if (pulse.type == PulseType.HIGH && !countWhenHighPulse.containsKey(module?.id)) {
countWhenHighPulse[module!!.id] = count
}
}
queue.addAll(destinationsToPulses)
if (queue.isEmpty()) {
queue.add(initialModule to initialPulse)
count++
}
}
}
fun part2(input: List<String>): String {
val modules = input.map { Module.parse(it) }.associateBy { it.id }
return numberOfButtonPushesUntilLowState(modules, "rx").toString()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day20$Module.class",
"javap": "Compiled from \"Day20.kt\"\npublic final class Day20$Module {\n public static final Day20$Module$Companion Companion;\n\n private final java.lang.String id;\n\n private final Day20$ModuleType type;\n\n private final ja... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day3.kt | import kotlin.String
import kotlin.collections.List
object Day3 {
data class NumberPosition(
val number: Int,
val start: Int,
val end: Int,
val row: Int
)
data class Symbol(val symbol: Char, val coordinate: Coordinate)
data class Coordinate(val x: Int, val y: Int)
private val reservedSymbol = ".".first()
fun part1(input: List<String>): String {
val numbers = parseNumbers(input)
val specialCharacters = parseSpecialCharacters(input).associateBy { it.coordinate }
val partNumbers = numbers.filter {
val (_, start, end, row) = it
val up = row - 1
val down = row + 1
val left = start - 1
val right = end + 1
val coordinateCandidates = (left..right).flatMap { x ->
listOf(
Coordinate(x, up),
Coordinate(x, down)
)
} + listOf(Coordinate(left, row), Coordinate(right, row))
coordinateCandidates.any { specialCharacters.containsKey(it) }
}
return partNumbers.sumOf { it.number }.toString()
}
private fun parseNumbers(input: List<String>): List<NumberPosition> {
return input.zip(input.indices).flatMap { (line, rowIndex) ->
val charArray = line.toCharArray()
val withIndexes = charArray.zip(charArray.indices)
val deque = ArrayDeque(withIndexes)
var buffer = ""
var start = 0
var end = 0
val numbers = mutableListOf<NumberPosition>()
while (deque.isNotEmpty()) {
val (char, index) = deque.removeFirst()
if (char.isDigit()) {
end = index
buffer += char
} else {
if (buffer.isNotEmpty()) {
numbers.add(NumberPosition(buffer.toInt(), start, end, rowIndex))
}
buffer = ""
start = index + 1
end = index + 1
}
}
if (buffer.isNotEmpty()) {
numbers.add(NumberPosition(buffer.toInt(), start, end, rowIndex))
}
numbers
}
}
private fun parseSpecialCharacters(input: List<String>): List<Symbol> {
val validSymbols = input.map { it.toCharArray() }
.map { it.zip(it.indices) }
.map { it.filter { !it.first.isDigit() }.filter { it.first != reservedSymbol } }
return validSymbols.zip(validSymbols.indices)
.flatMap { (row, rowIndex) -> row.map { Symbol(it.first, Coordinate(it.second, rowIndex)) } }
}
fun part2(input: List<String>): String {
val numbers = parseNumbers(input)
val specialCharacters = parseSpecialCharacters(input)
val gears = specialCharacters.filter { it.symbol == '*' }.associateBy { it.coordinate }
return gears.map { adjacent(it.key, numbers) }
.filter { it.size == 2 }
.map { it.map { it.number }.reduce { a, b -> a * b } }
.sum().toString()
}
private fun adjacent(it: Coordinate, numbers: List<NumberPosition>): List<NumberPosition> {
val up = Coordinate(it.x, it.y - 1)
val down = Coordinate(it.x, it.y + 1)
val left = Coordinate(it.x - 1, it.y)
val right = Coordinate(it.x + 1, it.y)
val upLeft = Coordinate(it.x - 1, it.y - 1)
val upRight = Coordinate(it.x + 1, it.y - 1)
val downLeft = Coordinate(it.x - 1, it.y + 1)
val downRight = Coordinate(it.x + 1, it.y + 1)
val candidates = listOf(up, down, left, right, upLeft, upRight, downLeft, downRight)
return numbers.filter { num -> candidates.any { it.x <= num.end && it.x >= num.start && it.y == num.row } }
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day3$Coordinate.class",
"javap": "Compiled from \"Day3.kt\"\npublic final class Day3$Coordinate {\n private final int x;\n\n private final int y;\n\n public Day3$Coordinate(int, int);\n Code:\n 0: aload_0\n 1: invokespecial #9 ... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day10.kt | import kotlin.String
import kotlin.collections.List
object Day10 {
data class Coordinate(val x: Int, val y: Int)
data class Node(val coordinate: Coordinate, val pipe: String, val connections: List<Coordinate>)
fun part1(input: List<String>): String {
val graph = parse(input)
val nodesInLoop = findNodesInLoop(graph)
val graphWithJunkRemoved = graph.filterKeys { it in nodesInLoop }
return djikstras(graphWithJunkRemoved).values.max().toString()
}
private fun djikstras(graph: Map<Coordinate, Node>): Map<Coordinate, Int> {
val startNode = graph.values.find { it.pipe == "S" }!!
val dists = mutableMapOf<Coordinate, Int>()
val unvisited = mutableSetOf<Coordinate>()
for (node in graph.values) {
unvisited.add(node.coordinate)
}
dists[startNode.coordinate] = 0
while (unvisited.isNotEmpty()) {
val current = unvisited.minBy { dists[it] ?: Int.MAX_VALUE }
unvisited.remove(current)
for (connection in graph[current]?.connections ?: emptyList()) {
val alt = dists.getOrPut(current) { 0 } + 1
if (alt < (dists[connection] ?: Int.MAX_VALUE)) {
dists[connection] = alt
}
}
}
return dists
}
fun parse(input: List<String>): Map<Coordinate, Node> {
val split = input.map { it.split("").filter { it.isNotBlank() } }
val northDestinations = setOf("|", "7", "F", "S")
val southDestinations = setOf("|", "J", "L", "S")
val eastDestinations = setOf("-", "7", "J", "S")
val westDestinations = setOf("-", "F", "L", "S")
val nodes = split.mapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
val coordinate = Coordinate(x, y)
when (char) {
"|" -> {
val connections = listOf(
split.getOrNull(y - 1)?.getOrNull(x)
?.let { if (northDestinations.contains(it)) Coordinate(x, y - 1) else null },
split.getOrNull(y + 1)?.getOrNull(x)
?.let { if (southDestinations.contains(it)) Coordinate(x, y + 1) else null }
).filterNotNull()
Node(coordinate, char, connections)
}
"-" -> {
val connections = listOf(
split.getOrNull(y)?.getOrNull(x - 1)
?.let { if (westDestinations.contains(it)) Coordinate(x - 1, y) else null },
split.getOrNull(y)?.getOrNull(x + 1)
?.let { if (eastDestinations.contains(it)) Coordinate(x + 1, y) else null }
).filterNotNull()
Node(coordinate, char, connections)
}
"L" -> {
val connections = listOf(
split.getOrNull(y - 1)?.getOrNull(x)
?.let { if (northDestinations.contains(it)) Coordinate(x, y - 1) else null },
split.getOrNull(y)?.getOrNull(x + 1)
?.let { if (eastDestinations.contains(it)) Coordinate(x + 1, y) else null }
).filterNotNull()
Node(coordinate, char, connections)
}
"J" -> {
val connections = listOf(
split.getOrNull(y - 1)?.getOrNull(x)
?.let { if (northDestinations.contains(it)) Coordinate(x, y - 1) else null },
split.getOrNull(y)?.getOrNull(x - 1)
?.let { if (westDestinations.contains(it)) Coordinate(x - 1, y) else null }
).filterNotNull()
Node(coordinate, char, connections)
}
"7" -> {
val connections = listOf(
split.getOrNull(y + 1)?.getOrNull(x)
?.let { if (southDestinations.contains(it)) Coordinate(x, y + 1) else null },
split.getOrNull(y)?.getOrNull(x - 1)
?.let { if (westDestinations.contains(it)) Coordinate(x - 1, y) else null },
).filterNotNull()
Node(coordinate, char, connections)
}
"F" -> {
val connections = listOf(
split.getOrNull(y + 1)?.getOrNull(x)
?.let { if (southDestinations.contains(it)) Coordinate(x, y + 1) else null },
split.getOrNull(y)?.getOrNull(x + 1)
?.let { if (eastDestinations.contains(it)) Coordinate(x + 1, y) else null }
).filterNotNull()
Node(coordinate, char, connections)
}
"S" -> {
val connections = listOf(
split.getOrNull(y - 1)?.getOrNull(x)
?.let { if (northDestinations.contains(it)) Coordinate(x, y - 1) else null },
split.getOrNull(y + 1)?.getOrNull(x)
?.let { if (southDestinations.contains(it)) Coordinate(x, y + 1) else null },
split.getOrNull(y)?.getOrNull(x - 1)
?.let { if (westDestinations.contains(it)) Coordinate(x - 1, y) else null },
split.getOrNull(y)?.getOrNull(x + 1)
?.let { if (eastDestinations.contains(it)) Coordinate(x + 1, y) else null }
).filterNotNull()
Node(coordinate, char, connections)
}
else -> null
}
}
}.flatten()
return nodes.associateBy { it.coordinate }
}
fun part2(input: List<String>): String {
val graph = parse(input)
val nodesInLoop = findNodesInLoop(graph)
val inputWithJunkPipesRemoved = input.mapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
val coordinate = Coordinate(x, y)
if (char == '.' || coordinate !in nodesInLoop) {
'.'.toString()
} else {
char.toString()
}
}.joinToString("")
}
val graphWithJunkRemoved = graph.filterKeys { it in nodesInLoop }
val graphWithStartReplaced = graphWithJunkRemoved.map { (coordinate, node) ->
if (node.pipe == "S") {
coordinate to Node(coordinate, translate("S", node.connections), node.connections)
} else {
coordinate to node
}
}.toMap()
val dots = inputWithJunkPipesRemoved.mapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
val coordinate = Coordinate(x, y)
if (char == '.') {
coordinate
} else {
null
}
}
}.flatten().toSet()
return dots.count { isInPolygon(graphWithStartReplaced, it) }.toString()
}
private fun translate(s: String, connections: List<Coordinate>): String {
val sortedConnections = connections.sortedWith(compareBy({ it.x }, { it.y }))
val northSouth = (sortedConnections.first().x - sortedConnections.last().x) == 0
val eastWest = (sortedConnections.first().y - sortedConnections.last().y) == 0
val eastNorth =
sortedConnections.first().x > sortedConnections.last().x && sortedConnections.first().y < sortedConnections.last().y
val eastSouth =
sortedConnections.first().x > sortedConnections.last().x && sortedConnections.first().y > sortedConnections.last().y
val westSouth =
sortedConnections.first().x < sortedConnections.last().x && sortedConnections.first().y < sortedConnections.last().y
val westNorth =
sortedConnections.first().x < sortedConnections.last().x && sortedConnections.first().y > sortedConnections.last().y
return when {
eastWest -> "-"
northSouth -> "|"
eastNorth -> "L"
eastSouth -> "F"
westNorth -> "J"
westSouth -> "7"
else -> s
}
}
private fun findNodesInLoop(graph: Map<Coordinate, Node>): Set<Coordinate> {
val startNode = graph.values.find { it.pipe == "S" }!!
val processed = mutableSetOf<Coordinate>()
val unprocessed = ArrayDeque<Coordinate>()
unprocessed.add(startNode.coordinate)
while (unprocessed.isNotEmpty()) {
val current = unprocessed.removeFirst()
if (current in processed) {
continue
}
unprocessed.addAll(graph[current]?.connections ?: emptyList())
processed.add(current)
}
return processed
}
/**
* Modified ray cast algorithm to identify if a coordinate is within the loop.
*
* Instead of casting a simple ray any direction and seeing if it crosses an odd number of segments,
* we cast rays in each direction and see if they cross an odd number of segments. Additionally
* we collapse segments such as
* F--
* |
* --J
*
* into a single segment FJ
*/
private fun isInPolygon(graph: Map<Coordinate, Node>, it: Coordinate): Boolean {
return isInPolygonAbove(graph, it) && isInPolygonBelow(graph, it) && isInPolygonLeft(
graph,
it
) && isInPolygonRight(graph, it)
}
/**
* Modified ray cast algorithm to identify num segments right
*
* ------> ||| (true, 3)
* ------> || (false, 2)
*/
fun isInPolygonRight(graph: Map<Coordinate, Node>, coordinate: Coordinate): Boolean {
val intersectionsRight = graph.keys.filter { it.x > coordinate.x }.filter { it.y == coordinate.y }
val directSegments = intersectionsRight
.filter { graph[it]?.pipe == "|" }
val indirectSegmentRightPairs = setOf("FJ", "L7")
val indirectSegments = intersectionsRight
.filter { graph[it]?.pipe != "-" }
.zipWithNext().filter { (a, b) ->
(graph[a]?.pipe + graph[b]?.pipe) in indirectSegmentRightPairs
}
return (indirectSegments.size + directSegments.size) % 2 == 1
}
/**
* Modified ray cast algorithm to identify num segments left
*
* ||| <------ (true, 3)
* || <------ (false, 2)
*/
fun isInPolygonLeft(graph: Map<Coordinate, Node>, coordinate: Coordinate): Boolean {
val intersectionsLeft =
graph.keys.filter { it.x < coordinate.x }.filter { it.y == coordinate.y }.sortedByDescending { it.x }
val directSegments = intersectionsLeft
.filter { graph[it]?.pipe == "|" }
val indirectSegmentLeftPairs = setOf("JF", "7L")
val indirectSegments = intersectionsLeft
.filter { graph[it]?.pipe != "-" }
.zipWithNext().filter { (a, b) ->
(graph[a]?.pipe + graph[b]?.pipe) in indirectSegmentLeftPairs
}
return (indirectSegments.size + directSegments.size) % 2 == 1
}
/**
* Modified ray cast algorithm to identify num segments below
*
* |
* |
* v
* -
* -
* - (true, 3)
*
* |
* |
* v
* -
* - (false, 2)
*/
fun isInPolygonBelow(graph: Map<Coordinate, Node>, coordinate: Coordinate): Boolean {
val intersectionsBelow =
graph.keys.filter { it.y > coordinate.y }.filter { it.x == coordinate.x }.sortedBy { it.y }
val directSegments = intersectionsBelow
.filter { graph[it]?.pipe == "-" }
val indirectSegmentSouthPairs = setOf("FJ", "7L")
val indirectSegments = intersectionsBelow
.filter { graph[it]?.pipe != "|" }
.zipWithNext().filter { (a, b) ->
(graph[a]?.pipe + graph[b]?.pipe) in indirectSegmentSouthPairs
}
return (indirectSegments.size + directSegments.size) % 2 == 1
}
/**
* Modified ray cast algorithm to identify num segments above
*
* - (true, 3)
* -
* -
* ^
* |
* |
*
* - (false, 2)
* -
* ^
* |
* |
*/
fun isInPolygonAbove(graph: Map<Coordinate, Node>, coordinate: Coordinate): Boolean {
graph.keys.filter { it.y < coordinate.y }.filter { it.x < coordinate.x }
val intersectionsAbove =
graph.keys.filter { it.y < coordinate.y }.filter { it.x == coordinate.x }.sortedByDescending { it.y }
val directSegments = intersectionsAbove
.filter { graph[it]?.pipe == "-" }
val indirectSegmentNorthPairs = setOf("JF", "L7")
val indirectSegments = intersectionsAbove
.filter { graph[it]?.pipe != "|" }
.zipWithNext().filter { (a, b) ->
(graph[a]?.pipe + graph[b]?.pipe) in indirectSegmentNorthPairs
}
return (indirectSegments.size + directSegments.size) % 2 == 1
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day10$Node.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class Day10$Node {\n private final Day10$Coordinate coordinate;\n\n private final java.lang.String pipe;\n\n private final java.util.List<Day10$Coordinate> connections;\n\n public... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day17.kt | import java.util.*
import kotlin.String
import kotlin.collections.List
import kotlin.math.min
object Day17 {
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT
}
data class CurrentStepInformation(
val currentCoordinate: Coordinate,
val currentDirection: Direction,
val consecutiveDirectionSteps: Int,
val heatLoss: Int
) {
}
data class Coordinate(val x: Int, val y: Int)
fun part1(input: List<String>): String {
val endCoordinate = Coordinate(input[0].length - 1, input.size - 1)
return minimumHeatLoss(input, endCoordinate, maxConsecutiveSteps = 3).toString()
}
private fun minimumHeatLoss(
grid: List<String>,
endCoordinate: Coordinate,
maxConsecutiveSteps: Int,
minConsecutiveSteps: Int = 0
): Int {
val heap = PriorityQueue<CurrentStepInformation> { o1, o2 ->
o1.heatLoss.compareTo(o2.heatLoss)
}
heap.add(
CurrentStepInformation(
Coordinate(1, 0),
Direction.RIGHT,
1,
0
)
)
heap.add(
CurrentStepInformation(
Coordinate(0, 1),
Direction.DOWN,
1,
0
)
)
var minValue = Int.MAX_VALUE
val memo = mutableMapOf<CurrentStepInformation, Int>()
while (heap.isNotEmpty()) {
val currentStepInformation = heap.poll()
val currentCoordinate = currentStepInformation.currentCoordinate
val heatLoss =
grid[currentCoordinate.y][currentCoordinate.x].digitToInt()
val memoKey = currentStepInformation.copy(heatLoss = 0)
// If we have already been here with less heat loss, we can skip this
// Especially if we have already been here with the same heat loss but less consecutive steps, because
// if a path had more possibilites and a smaller heat loss it makes no sense to search the space
val tooExpensive =
(minConsecutiveSteps..memoKey.consecutiveDirectionSteps - 1).map {
memoKey.copy(
consecutiveDirectionSteps = it
)
}
.any {
memo.containsKey(it) && memo[it]!! <= currentStepInformation.heatLoss + heatLoss
} || (memo[memoKey] ?: Int.MAX_VALUE) <= currentStepInformation.heatLoss + heatLoss
if (tooExpensive) {
continue
}
memo.put(memoKey, currentStepInformation.heatLoss + heatLoss)
if (currentCoordinate == endCoordinate) {
if (currentStepInformation.consecutiveDirectionSteps < minConsecutiveSteps) {
continue
}
minValue = min(minValue, currentStepInformation.heatLoss + heatLoss)
continue
}
val nextCoordinates = listOf(
currentCoordinate.copy(x = currentCoordinate.x + 1) to Direction.RIGHT,
currentCoordinate.copy(y = currentCoordinate.y + 1) to Direction.DOWN,
currentCoordinate.copy(x = currentCoordinate.x - 1) to Direction.LEFT,
currentCoordinate.copy(y = currentCoordinate.y - 1) to Direction.UP
).filter { (_, direction) ->
// We cannot reverse directions
when (direction) {
Direction.UP -> currentStepInformation.currentDirection != Direction.DOWN
Direction.DOWN -> currentStepInformation.currentDirection != Direction.UP
Direction.LEFT -> currentStepInformation.currentDirection != Direction.RIGHT
Direction.RIGHT -> currentStepInformation.currentDirection != Direction.LEFT
}
}.map { (coordinate, direction) ->
CurrentStepInformation(
coordinate,
direction,
if (direction == currentStepInformation.currentDirection) currentStepInformation.consecutiveDirectionSteps + 1 else 1,
currentStepInformation.heatLoss + heatLoss
)
}.filter {
// We must move a minimum number of steps in the same direction
it.currentDirection == currentStepInformation.currentDirection || currentStepInformation.consecutiveDirectionSteps >= minConsecutiveSteps
}.filter {
// We cannot move in the same direction more than maxConsecutiveSteps
it.consecutiveDirectionSteps <= maxConsecutiveSteps
}.filter {
// We cannot move out of bounds
it.currentCoordinate.x >= 0 && it.currentCoordinate.y >= 0 && it.currentCoordinate.y < grid.size && it.currentCoordinate.x < grid[it.currentCoordinate.y].length
}
heap.addAll(nextCoordinates)
}
return minValue
}
fun part2(input: List<String>): String {
val endCoordinate = Coordinate(input[0].length - 1, input.size - 1)
return minimumHeatLoss(
input, endCoordinate, maxConsecutiveSteps = 10, minConsecutiveSteps = 4
).toString()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day17.class",
"javap": "Compiled from \"Day17.kt\"\npublic final class Day17 {\n public static final Day17 INSTANCE;\n\n private Day17();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day19.kt | import kotlin.String
import kotlin.collections.List
object Day19 {
private const val MIN_STATES = 1L
private const val MAX_STATES = 4000L
private const val ACCEPTED_STATE = "A"
private const val REJECTED_STATE = "R"
private const val START_STATE = "in"
data class Part(val ratings: Map<String, Int>) {
companion object {
fun parse(input: String): Part {
val ratings = input.drop(1).dropLast(1).split(",").map {
val (id, rating) = it.split("=")
id to rating.toInt()
}.toMap()
return Part(ratings)
}
}
fun score(): Int = ratings.values.sum()
}
data class Rule(val key: String, val op: String, val value: Int, val nextState: String) {
fun inverse(): Rule {
val inverseOp = when (op) {
"<" -> ">="
">" -> "<="
else -> throw IllegalArgumentException("Cannot inverse op $op")
}
return Rule(key, inverseOp, value, nextState)
}
}
data class Condition(val key: String, val op: String, val value: Int) {
fun toMinAndMax(): MinAndMax {
return when (op) {
"<" -> MinAndMax(MIN_STATES, value.toLong() - 1, key)
"<=" -> MinAndMax(MIN_STATES, value.toLong(), key)
">" -> MinAndMax(value.toLong() + 1, MAX_STATES, key)
">=" -> MinAndMax(value.toLong(), MAX_STATES, key)
else -> throw IllegalArgumentException("Cannot inverse op $op")
}
}
}
data class CompositeCondition(val conditions: List<Condition>, val nextState: String)
data class PathFinder(val jobs: Map<String, Job>) {
fun findPathsToRejectedState(): List<Path> {
val startJob = jobs[START_STATE]!!
val paths = mutableListOf<Path>()
paths.addAll(startJob.conditionsLeadingToRejectedState().map { Path(listOf(it)) })
val nextStates = ArrayDeque(
startJob.nonTerminalConditions()
.map { it to Path(listOf(it)) })
while (nextStates.isNotEmpty()) {
val (nextRule, runningPath) = nextStates.removeFirst()
val nextJob = jobs[nextRule.nextState]!!
val failureStates = nextJob.conditionsLeadingToRejectedState()
val failedPaths = failureStates.map { runningPath.with(it) }
paths.addAll(failedPaths)
val nonTerminalStates = nextJob.nonTerminalConditions()
nextStates.addAll(nonTerminalStates.map { it to runningPath.with(it) })
}
return paths
}
}
data class Path(val compositeConditions: List<CompositeCondition>) {
fun with(compositeCondition: CompositeCondition): Path {
return Path(compositeConditions + compositeCondition)
}
}
data class Job(
val id: String,
val rules: List<Pair<(Part) -> Boolean, String>>,
val endState: String,
val rawRules: List<Rule>
) {
fun evaluate(part: Part): String {
return rules.find { (rule, _) -> rule(part) }?.second ?: endState
}
fun conditionsLeadingToRejectedState(): List<CompositeCondition> {
val rejectedRules = mutableListOf<CompositeCondition>()
if (endState == REJECTED_STATE) {
val endStateCompositeCondition =
CompositeCondition(
rawRules.map { it.inverse() }.map { Condition(it.key, it.op, it.value) },
REJECTED_STATE
)
rejectedRules.add(endStateCompositeCondition)
}
rejectedRules.addAll(rawRules.withIndex().filter { (_, rule) -> rule.nextState == REJECTED_STATE }
.map { (idx, rule) ->
val inversedPreceedingRules =
rawRules.subList(0, idx).map { it.inverse() }.map { Condition(it.key, it.op, it.value) }
val thisRule = listOf(Condition(rule.key, rule.op, rule.value))
CompositeCondition(inversedPreceedingRules + thisRule, rule.nextState)
})
return rejectedRules
}
fun nonTerminalConditions(): List<CompositeCondition> {
val nonAcceptedNorRejectedConditions = mutableListOf<CompositeCondition>()
if (endState != ACCEPTED_STATE && endState != REJECTED_STATE) {
val endStateCompositeCondition =
CompositeCondition(
rawRules.map { it.inverse() }.map { Condition(it.key, it.op, it.value) },
endState
)
nonAcceptedNorRejectedConditions.add(endStateCompositeCondition)
}
nonAcceptedNorRejectedConditions.addAll(
rawRules.withIndex()
.filter { (_, rule) -> rule.nextState != REJECTED_STATE && rule.nextState != ACCEPTED_STATE }
.map { (idx, rule) ->
val inversedPreceedingRules =
rawRules.subList(0, idx).map { it.inverse() }.map { Condition(it.key, it.op, it.value) }
val thisRule = listOf(Condition(rule.key, rule.op, rule.value))
CompositeCondition(inversedPreceedingRules + thisRule, rule.nextState)
})
return nonAcceptedNorRejectedConditions
}
companion object {
fun parse(input: String): Job {
val curlyIndex = input.indexOf("{")
val id = input.substring(0, curlyIndex).trim()
val rawRules = input.substring(curlyIndex).drop(1).dropLast(1)
val lastComma = rawRules.lastIndexOf(",")
val endState = rawRules.substring(lastComma + 1).trim()
val ops = mapOf("<" to { part: Part, value: Int, key: String -> part.ratings[key]!! < value },
">" to { part: Part, value: Int, key: String -> part.ratings[key]!! > value })
val rules = rawRules.substring(0, lastComma).split(",").map {
val pattern = """(\w+)([<>])(\d+):(\w+)""".toRegex()
val matchResult = pattern.matchEntire(it.trim())!!
val (key, op, value, nextState) = matchResult.destructured
Rule(key, op, value.toInt(), nextState)
}
val rulesAsFunctions =
rules.map { { part: Part -> ops[it.op]!!(part, it.value, it.key) } to it.nextState }
return Job(id, rulesAsFunctions, endState, rules)
}
}
}
data class Workflow(val jobs: Map<String, Job>) {
fun isAccepted(part: Part): Boolean {
val startJob = jobs[START_STATE]!!
var state = startJob.evaluate(part)
while (state != ACCEPTED_STATE && state != REJECTED_STATE) {
val job = jobs[state]!!
state = job.evaluate(part)
}
return state == ACCEPTED_STATE
}
}
fun part1(input: List<String>): String {
val partitionIndex = input.withIndex().find { it.value.isEmpty() }!!.index
val jobs = input.subList(0, partitionIndex).map { Job.parse(it) }
val parts = input.subList(partitionIndex + 1, input.size).map { Part.parse(it) }
val workflow = Workflow(jobs.associateBy { it.id })
return parts.filter { workflow.isAccepted(it) }.sumOf { it.score() }.toString()
}
data class MinAndMax(val min: Long, val max: Long, val key: String) {
fun coerce(other: MinAndMax): MinAndMax {
return MinAndMax(min.coerceAtLeast(other.min), max.coerceAtMost(other.max), key)
}
fun length(): Long = max - min + 1
}
fun part2(input: List<String>): String {
val partitionIndex = input.withIndex().find { it.value.isEmpty() }!!.index
val jobs = input.subList(0, partitionIndex).map { Job.parse(it) }
val rejectedPaths = PathFinder(jobs.associateBy { it.id }).findPathsToRejectedState()
val minAndMaxes: List<Map<String, MinAndMax>> = rejectedPaths
.filter { it.compositeConditions.isNotEmpty() }
.map { path ->
path.compositeConditions.flatMap { it.conditions }
.map { it.toMinAndMax() }.groupBy { it.key }
.mapValues { (_, minAndMaxes) -> minAndMaxes.reduce { a, b -> a.coerce(b) } }
}
val possibleRejectedStates = minAndMaxes.map { minAndMax ->
listOf("x", "m", "a", "s").map { minAndMax[it] ?: MinAndMax(1, 4000, it) }
.map { it.length() }
.reduce { acc, num -> acc * num }
}.sum()
val possibleStates = 4000L * 4000L * 4000L * 4000L
val delta = possibleStates - possibleRejectedStates
return delta.toString()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day19$Workflow.class",
"javap": "Compiled from \"Day19.kt\"\npublic final class Day19$Workflow {\n private final java.util.Map<java.lang.String, Day19$Job> jobs;\n\n public Day19$Workflow(java.util.Map<java.lang.String, Day19$Job>);\n Code:\n ... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day7.kt | import kotlin.String
import kotlin.collections.List
object Day7 {
interface CardHand : Comparable<CardHand> {
val maxSimilarCards: Int
val bid: Long
val secondMaxSimilarCards: Int
val cards: CharArray
val cardValues: Map<Char, Int>
fun score(rank: Int): Long {
return bid * rank
}
override fun compareTo(other: CardHand): Int {
return compareBy<CardHand> { it.maxSimilarCards }
.thenBy { it.secondMaxSimilarCards }
.then { first, second ->
val thisCardValues = first.cards.map { cardValues[it] ?: 0 }
val otherCardValues = second.cards.map { cardValues[it] ?: 0 }
thisCardValues.zip(otherCardValues).map { it.first - it.second }.firstOrNull { it != 0 } ?: 0
}
.compare(this, other)
}
}
data class CamelCardHandWithJokers(override val cards: CharArray, override val bid: Long) : CardHand {
override val maxSimilarCards: Int
private val possibleCards: CharArray =
arrayOf('J', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A').toCharArray()
override val secondMaxSimilarCards: Int
override val cardValues = possibleCards.zip(possibleCards.indices).toMap()
init {
val numJokers = cards.count { it == 'J' }
val nonJokers = cards.filter { it != 'J' }.groupBy { it }.mapValues { it.value.size }
val values = nonJokers.values.sortedDescending()
val maxNonJokers = values.firstOrNull() ?: 0
val secondMaxNonJokers = values.drop(1).firstOrNull() ?: 0
maxSimilarCards = maxNonJokers + numJokers
secondMaxSimilarCards = secondMaxNonJokers
}
companion object {
fun parse(input: String): CamelCardHandWithJokers {
val (cards, bid) = input.split(" ")
return CamelCardHandWithJokers(cards.toCharArray(), bid.toLong())
}
}
}
data class CamelCardHand(override val cards: CharArray, override val bid: Long) : CardHand {
override val maxSimilarCards: Int
override val secondMaxSimilarCards: Int
private val possibleCards: CharArray =
arrayOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A').toCharArray()
override val cardValues = possibleCards.zip(possibleCards.indices).toMap()
init {
val grouped = cards.groupBy { it }.mapValues { it.value.size }
val values = grouped.values.sortedDescending()
maxSimilarCards = values.first()
secondMaxSimilarCards = values.drop(1).firstOrNull() ?: 0
}
companion object {
fun parse(input: String): CamelCardHand {
val (cards, bid) = input.split(" ")
return CamelCardHand(cards.toCharArray(), bid.toLong())
}
}
}
fun part1(input: List<String>): String {
val hands = input.map(CamelCardHand::parse)
return score(hands).toString()
}
fun part2(input: List<String>): String {
val hands = input.map(CamelCardHandWithJokers::parse)
return score(hands).toString()
}
private fun score(hands: List<CardHand>): Long {
val sortedHands = hands.sorted()
return sortedHands.zip(sortedHands.indices).sumOf { (hand, index) -> hand.score(index + 1) }
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day7$CardHand$DefaultImpls$compareTo$$inlined$thenBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class Day7$CardHand$DefaultImpls$compareTo$$inlined$thenBy$1<T> implements java.util.Comparator {\n final java.util.Comparator $this... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day13.kt | import kotlin.String
import kotlin.collections.List
object Day13 {
private const val NORMAL_MULTIPLIER = 100
private const val TRANSPOSED_MULTIPLIER = 1
fun part1(input: List<String>): String {
val grids = parseGrids(input)
return grids.sumOf { grid ->
// Transposed is actually columns
val transposedGrid = transpose(grid)
scoreExact(grid, NORMAL_MULTIPLIER) + scoreExact(transposedGrid, TRANSPOSED_MULTIPLIER)
}.toString()
}
private fun scoreExact(grid: List<String>, multiplier: Int): Int {
return findLinesOfExactness(grid).find { isMirror(it, grid) }?.let {
// Normal is rows, so rows above
val rowsAbove = it.first + 1
return rowsAbove * multiplier
} ?: 0
}
private fun isMirror(it: Pair<Int, Int>, grid: List<String>): Boolean {
val (a, b) = it
if (a < 0 || b >= grid.size) {
return true
}
return grid[a] == grid[b] && isMirror(a - 1 to b + 1, grid)
}
/**
* Return the rows in which there is a line of exactness
*/
private fun findLinesOfExactness(grid: List<String>): List<Pair<Int, Int>> {
return grid.withIndex().zipWithNext().filter { (a, b) -> a.value == b.value }
.map { (a, b) -> a.index to b.index }
}
fun transpose(grid: List<String>): List<String> {
val transposedGrid = List(grid[0].length) { CharArray(grid.size) }
for (i in grid.indices) {
for (j in grid[0].indices) {
transposedGrid[j][i] = grid[i][j]
}
}
return transposedGrid.map { it.joinToString("") }
}
private fun parseGrids(input: List<String>): List<List<String>> {
val emptyIndexes =
listOf(-1) + input.withIndex().filter { (_, b) -> b.isBlank() }.map { (i, _) -> i } + listOf(input.size)
return emptyIndexes.zipWithNext().map { (a, b) -> input.subList(a + 1, b) }
}
fun part2(input: List<String>): String {
val grids = parseGrids(input)
return grids.sumOf { grid ->
// Transposed is actually columns
val transposedGrid = transpose(grid)
scoreSmudged(grid, NORMAL_MULTIPLIER) + scoreSmudged(transposedGrid, TRANSPOSED_MULTIPLIER)
}.toString()
}
private fun scoreSmudged(grid: List<String>, multiplier: Int): Int {
val rowsOfMaybeExactness = findLinesOfExactness(grid) + findLinesOffByOne(grid)
return rowsOfMaybeExactness.find { isAlmostMirror(it, grid, 0) }?.let {
// Normal is rows, so rows above
val rowsAbove = it.first + 1
rowsAbove * multiplier
} ?: 0
}
private fun findLinesOffByOne(grid: List<String>): List<Pair<Int, Int>> {
return grid.withIndex().zipWithNext().filter { (a, b) -> isOffByOne(a.value, b.value) }
.map { (a, b) -> a.index to b.index }
}
private fun isAlmostMirror(it: Pair<Int, Int>, grid: List<String>, offByOneCount: Int): Boolean {
if (offByOneCount > 1) {
return false
}
val (a, b) = it
if (a < 0 || b >= grid.size) {
return offByOneCount == 1
}
val offByOne = isOffByOne(grid[a], grid[b])
val offByMoreThanOne = !offByOne && grid[a] != grid[b]
if (offByMoreThanOne) {
return false
}
val newCount = if (offByOne) {
offByOneCount + 1
} else {
offByOneCount
}
return isAlmostMirror(a - 1 to b + 1, grid, newCount)
}
private fun isOffByOne(a: String, b: String): Boolean {
return a.toCharArray().zip(b.toCharArray())
.count { (a, b) -> a != b } == 1
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day13.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13 {\n public static final Day13 INSTANCE;\n\n private static final int NORMAL_MULTIPLIER;\n\n private static final int TRANSPOSED_MULTIPLIER;\n\n private Day13();\n Code:\... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day23.kt | import kotlin.String
import kotlin.collections.List
import Day17.Coordinate
import java.util.*
import kotlin.math.max
object Day23 {
/**
* A more compact representation of a path than a list of coordinates.
*/
data class Segment(val steps: Int, val start: Coordinate, val end: Coordinate)
fun part1(input: List<String>): String {
val startIndex = input[0].indexOf(".")
val endIndex = input.last().indexOf(".")
val startCoordinate = Coordinate(startIndex, 0)
val endCoordinate = Coordinate(endIndex, input.size - 1)
return maxSteps(startCoordinate, startCoordinate, endCoordinate, input, 0).toString()
}
data class StepInformation(
val node: Segment,
val visited: Set<Segment>,
val steps: Int
)
private fun maxStepsExpanded(
start: Segment,
end: Segment,
nodes: Set<Segment>,
input: List<String>
): Int {
val queue = PriorityQueue<StepInformation> { a, b -> -a.steps.compareTo(b.steps) }
queue.add(StepInformation(start, setOf(start), start.steps))
val startMap = nodes.associate { it.start to it }
val endMap = nodes.associate { it.end to it }
val nodeBeforeExit = getNeighbors(end.start, input).map { it.first }.filter { it in endMap }
.map { endMap[it] }.filterNotNull().distinct().first()
var max = 0
var count = 0
val startMemo = mutableMapOf<Segment, List<Segment>>()
val endMemo = mutableMapOf<Segment, List<Segment>>()
while (queue.isNotEmpty()) {
count++
if (count % 1000000 == 0) {
println("Count: $count, queue size: ${queue.size}, current max: $max")
}
val stepInformation = queue.poll()
val node = stepInformation.node
val steps = stepInformation.steps
val visited = stepInformation.visited
if (node == end) {
max = max(steps, max)
continue
}
if (nodeBeforeExit in visited) {
continue
}
val startNeighbors = startMemo.getOrPut(node) {
getNeighbors(node.start, input).map { it.first }.filter { it in endMap }
.map { endMap[it]!! }
}.filter { it !in visited }
val endNeighbors = endMemo.getOrPut(node) {
getNeighbors(node.end, input).map { it.first }.filter { it in startMap }
.map { startMap[it]!! }
}.filter { it !in visited }
queue.addAll(
(startNeighbors + endNeighbors).distinct()
.map { StepInformation(it, visited + node, steps + it.steps) })
}
return max
}
private tailrec fun maxSteps(
previousCoordinate: Coordinate,
currentCoordinate: Coordinate,
endCoordinate: Coordinate,
input: List<String>,
currentSteps: Int
): Int {
if (currentCoordinate == endCoordinate) {
return currentSteps
}
val nextCoordinates = getNeighborsDirectionally(previousCoordinate, currentCoordinate, input)
val nextOpenSpace = nextCoordinates.find { it.second == '.' }
if (nextOpenSpace != null) {
return maxSteps(
currentCoordinate,
nextOpenSpace.first,
endCoordinate,
input,
currentSteps + 1
)
}
return nextCoordinates.maxOf { maxSteps(currentCoordinate, it.first, endCoordinate, input, currentSteps + 1) }
}
fun part2(input: List<String>): String {
val startIndex = input[0].indexOf(".")
val endIndex = input.last().indexOf(".")
val startCoordinate = Coordinate(startIndex, 0)
val endCoordinate = Coordinate(endIndex, input.size - 1)
val nodes = buildSegments(startCoordinate, endCoordinate, input, 0)
val start = nodes.find { it.start == startCoordinate }
return maxStepsExpanded(start!!, nodes.find { it.end == endCoordinate }!!, nodes, input).toString()
}
data class SegmentBuildingInformation(
val coordinate: Coordinate,
val previousCoordinate: Coordinate,
val steps: Int,
val runningSegment: Segment
)
private fun buildSegments(
startCoordinate: Coordinate,
endCoordinate: Coordinate,
input: List<String>,
length: Int
): Set<Segment> {
val queue = ArrayDeque<SegmentBuildingInformation>()
queue.add(
SegmentBuildingInformation(
startCoordinate,
startCoordinate,
length,
Segment(length, startCoordinate, startCoordinate)
)
)
val segments = mutableSetOf<Segment>()
while (queue.isNotEmpty()) {
val stepInformation = queue.poll()
val currentCoordinate = stepInformation.coordinate
val previousCoordinate = stepInformation.previousCoordinate
val length = stepInformation.steps
val runningNode = stepInformation.runningSegment
if (currentCoordinate == endCoordinate) {
val updatedNode = runningNode.copy(end = endCoordinate, steps = length)
if (updatedNode !in segments) {
segments.add(updatedNode)
}
}
val nextCoordinates = getNeighborsDirectionally(previousCoordinate, currentCoordinate, input)
val nextOpenSpace = nextCoordinates.find { it.second == '.' }
if (nextOpenSpace != null) {
val currentCharacter = input[currentCoordinate.y][currentCoordinate.x]
// We have to treat >, < etc as their own segment because otherwise we can lead to duplicate counting
if (currentCharacter != '.') {
val updatedNode = runningNode.copy(end = currentCoordinate, steps = length)
if (updatedNode !in segments) {
segments.add(updatedNode)
}
queue.addFirst(
SegmentBuildingInformation(
nextOpenSpace.first,
currentCoordinate,
1,
Segment(1, nextOpenSpace.first, nextOpenSpace.first)
)
)
} else {
queue.addFirst(SegmentBuildingInformation(nextOpenSpace.first, currentCoordinate, length + 1, runningNode))
}
} else {
val updatedNode = runningNode.copy(end = currentCoordinate, steps = length)
if (updatedNode !in segments) {
segments.add(updatedNode)
}
val neighbors = nextCoordinates.map {
SegmentBuildingInformation(
it.first,
currentCoordinate,
1,
Segment(1, it.first, it.first)
)
}
for (nextNeighbor in neighbors) {
queue.addFirst(nextNeighbor)
}
}
}
return segments
}
fun getNeighborsDirectionally(
previousCoordinate: Coordinate,
currentCoordinate: Coordinate,
input: List<String>
): List<Pair<Coordinate, Char>> {
val left = currentCoordinate.copy(x = currentCoordinate.x - 1)
val right = currentCoordinate.copy(x = currentCoordinate.x + 1)
val up = currentCoordinate.copy(y = currentCoordinate.y - 1)
val down = currentCoordinate.copy(y = currentCoordinate.y + 1)
val nextCoordinates = getNeighbors(currentCoordinate, input)
.filter { it.first != previousCoordinate }
.filter {
if (it.first == left) {
it.second != '>'
} else if (it.first == right) {
it.second != '<'
} else if (it.first == up) {
it.second != 'v'
} else if (it.first == down) {
it.second != '^'
} else {
throw Exception("Unknown direction")
}
}
return nextCoordinates
}
fun getNeighbors(currentCoordinate: Coordinate, input: List<String>): List<Pair<Coordinate, Char>> {
val left = currentCoordinate.copy(x = currentCoordinate.x - 1)
val right = currentCoordinate.copy(x = currentCoordinate.x + 1)
val up = currentCoordinate.copy(y = currentCoordinate.y - 1)
val down = currentCoordinate.copy(y = currentCoordinate.y + 1)
val nextCoordinates = listOf(
left,
right,
up,
down
).filter { it.x >= 0 && it.x < input[0].length && it.y >= 0 && it.y < input.size }
.map { it to input[it.y][it.x] }
.filter { it.second != '#' }
return nextCoordinates
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day23$StepInformation.class",
"javap": "Compiled from \"Day23.kt\"\npublic final class Day23$StepInformation {\n private final Day23$Segment node;\n\n private final java.util.Set<Day23$Segment> visited;\n\n private final int steps;\n\n public Day23$... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day8.kt | import kotlin.String
import kotlin.collections.List
object Day8 {
data class Node(var left: Node?, var right: Node?, val key: String)
data class DesertMap(val directions: CharArray, val root: Node?) {
companion object {
fun parse(input: List<String>): DesertMap {
val directions = input.first().toCharArray()
val nodes = parseNodes(input.drop(2))
val root = nodes.find { it.key == "AAA" }
return DesertMap(directions, root)
}
fun parsePart2(input: List<String>): List<DesertMap> {
val directions = input.first().toCharArray()
val nodes = parseNodes(input.drop(2))
val roots = nodes.filter { it.key.endsWith("A") }
return roots.map { DesertMap(directions, it) }
}
private fun parseNodes(input: List<String>): List<Node> {
val index = mutableMapOf<String, Node>()
val nodePattern = "(\\w+) = \\((\\w+), (\\w+)\\)".toRegex()
for (line in input) {
val (key, left, right) = nodePattern.matchEntire(line)!!.destructured
val leftNode = index.getOrPut(left) { Node(null, null, left) }
val rightNode = index.getOrPut(right) { Node(null, null, right) }
val keyNode = index.getOrPut(key) { Node(null, null, key) }
keyNode.left = leftNode
keyNode.right = rightNode
}
return index.values.toList()
}
}
}
fun part1(input: List<String>): String {
val desertMap = DesertMap.parse(input)
return followUntilExit(desertMap.directions, desertMap.root, 0).toString()
}
private tailrec fun followUntilExit(
directions: CharArray,
currentNode: Node?,
currentSteps: Long,
exitCondition: (Node) -> Boolean = { it.key == "ZZZ" }
): Long {
if (currentNode == null || exitCondition(currentNode)) {
return currentSteps
}
val nextNode = if (directions.first() == 'L') {
currentNode.left
} else {
currentNode.right
}
return followUntilExit(directions.rotate(1), nextNode, currentSteps + 1, exitCondition)
}
fun part2(input: List<String>): String {
val desertMaps = DesertMap.parsePart2(input)
return followUntilAllExit(desertMaps).toString()
}
private fun followUntilAllExit(desertMaps: List<DesertMap>): Long {
val requiredStepsUntilExit =
desertMaps.map { followUntilExit(it.directions, it.root, 0) { it.key.endsWith("Z") } }
return leastCommonMultiple(requiredStepsUntilExit)
}
private fun leastCommonMultiple(requiredStepsUntilExit: List<Long>): Long {
return requiredStepsUntilExit.reduce { a, b -> lcm(a, b) }
}
private fun lcm(a: Long, b: Long): Long {
return a * b / gcd(a, b)
}
private fun gcd(a: Long, b: Long): Long {
return if (b == 0L) a else gcd(b, a % b)
}
private fun CharArray.rotate(n: Int) =
let { sliceArray(n..<size) + sliceArray(0..<n) }
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day8$DesertMap$Companion.class",
"javap": "Compiled from \"Day8.kt\"\npublic final class Day8$DesertMap$Companion {\n private Day8$DesertMap$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Obj... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day2.kt | import kotlin.String
import kotlin.collections.List
object Day2 {
data class Cube(
val color: String,
val count: Int
)
data class Game(
val id: Int,
val cubePulls: List<List<Cube>>
) {
companion object {
fun parseGame(s: String): Game {
val (id, pulls) = s.split(":")
return Game(
id.trimStart(*"Game ".toCharArray()).toInt(),
pulls.split(";").map { cubeList ->
cubeList.split(",").map { cube ->
val (count, color) = cube.trimStart(' ').split(" ")
Cube(color, count.toInt())
}
}
)
}
}
}
fun part1(input: List<String>): String {
return sumOfGamesWithTarget(
input.map(Game::parseGame),
listOf(
Cube("red", 12), Cube("green", 13), Cube("blue", 14)
)
).toString()
}
private fun sumOfGamesWithTarget(input: List<Game>, targets: List<Cube>): Int {
val index = targets.associateBy { it.color }
return input.filter {
it.cubePulls.all {
it.all {
it.count <= index.getOrDefault(
it.color,
it
).count
}
}
}.sumOf { it.id }
}
fun part2(input: List<String>): String {
return sumOfPowersWithMinimums(input.map(Game::parseGame)).toString()
}
private fun sumOfPowersWithMinimums(games: List<Game>): Int {
return games.map {
val minimumCubesNeeded = it.cubePulls.flatten()
.groupBy { it.color }
.mapValues { it.value.maxBy { it.count } }
minimumCubesNeeded.map { it.value.count }.reduce { a, b -> a * b }
}.sum()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day2$Game.class",
"javap": "Compiled from \"Day2.kt\"\npublic final class Day2$Game {\n public static final Day2$Game$Companion Companion;\n\n private final int id;\n\n private final java.util.List<java.util.List<Day2$Cube>> cubePulls;\n\n public Da... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day5.kt | import java.lang.Long.min
import kotlin.String
import kotlin.collections.List
object Day5 {
data class Range(val start: Long, val end: Long)
data class RangeMapping(val destinationRangeStart: Long, val sourceRangeStart: Long, val rangeLength: Long) {
fun next(id: Long): Long {
return if (sourceRangeStart <= id && id <= sourceRangeStart + rangeLength) {
val offset = id - sourceRangeStart
destinationRangeStart + offset
} else {
id
}
}
fun next(range: Range): Range {
val offset = range.start - sourceRangeStart
return Range(destinationRangeStart + offset, destinationRangeStart + offset + range.end - range.start)
}
fun overlaps(id: Long): Boolean {
return sourceRangeStart <= id && id < sourceRangeStart + rangeLength
}
fun overlaps(range: Range): Boolean {
return sourceRangeStart <= range.start && range.end <= sourceRangeStart + rangeLength - 1
}
}
data class Mapping(
val category: String,
val rangeMappings: List<RangeMapping>
) {
fun fork(range: Range): List<Range> {
if (rangeMappings.any { it.overlaps(range) }) {
return listOf(range)
}
var start = range.start
val end = range.end
val ranges = mutableListOf<Range>()
while (start <= end) {
val closestWithoutGoingOver =
rangeMappings.filter { it.sourceRangeStart <= start && start < it.sourceRangeStart + it.rangeLength }
.minByOrNull { it.sourceRangeStart - range.start }
if (closestWithoutGoingOver != null) {
val newEnd =
min(end, closestWithoutGoingOver.sourceRangeStart + closestWithoutGoingOver.rangeLength - 1)
ranges.add(Range(start, newEnd))
start = newEnd + 1
} else {
val closestWithGoingOver =
rangeMappings.filter { it.sourceRangeStart + it.rangeLength > start }
.minByOrNull { it.sourceRangeStart - start }
if (closestWithGoingOver == null) {
ranges.add(Range(start, end))
start = end + 1
} else {
val newEnd = min(end, closestWithGoingOver.sourceRangeStart - 1)
ranges.add(Range(start, newEnd))
start = newEnd + 1
}
}
}
return ranges
}
companion object {
fun parseMappings(input: List<String>): List<Mapping> {
var remainingInput = input
val mappings = mutableListOf<Mapping>()
while (remainingInput.isNotEmpty()) {
val category = remainingInput.first().split(" ").first()
val ranges = remainingInput.drop(1).takeWhile { it.isNotEmpty() }.map {
val (destinationRangeStart, sourceRangeStart, rangeLength) = it.split(" ")
RangeMapping(
destinationRangeStart.toLong(),
sourceRangeStart.toLong(),
rangeLength.toLong()
)
}
mappings.add(Mapping(category, ranges))
remainingInput = remainingInput.drop(ranges.size + 2)
}
return mappings
}
}
}
fun part1(input: List<String>): String {
val seeds = input.first().replace("seeds: ", "")
.split(" ")
.map { it.toLong() }
val mappings = Mapping.parseMappings(input.drop(2))
val finalMappings = mappings.fold(seeds) { acc, mapping ->
acc.map { id ->
val range = mapping.rangeMappings.find { it.overlaps(id) }
range?.next(id) ?: id
}
}
return finalMappings.min().toString()
}
fun part2(input: List<String>): String {
val ranges = input.first().replace("seeds: ", "")
.split(" ")
.map { it.toLong() }
.chunked(2)
.map { Range(it.first(), it.first() + it.last()) }
val mappings = Mapping.parseMappings(input.drop(2))
val finalRanges = mappings.fold(ranges) { transformedRanges, mapping ->
transformedRanges.flatMap { range ->
val nextRanges = mapping.fork(range).map { forkedRange ->
val overlaps = mapping.rangeMappings.filter { it.overlaps(forkedRange) }
.minByOrNull { it.sourceRangeStart - forkedRange.start }
overlaps?.next(forkedRange) ?: forkedRange
}
nextRanges
}
}
return finalRanges.minBy { it.start }.start.toString()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day5.class",
"javap": "Compiled from \"Day5.kt\"\npublic final class Day5 {\n public static final Day5 INSTANCE;\n\n private Day5();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day16.kt | import kotlin.String
import kotlin.collections.List
public object Day16 {
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT
}
public fun part1(input: List<String>): String {
val startCoordinate = Day10.Coordinate(0, 0)
val startDirection = Direction.RIGHT
return energizeCount(startCoordinate, startDirection, input).toString()
}
private fun energizeCount(startCoordinate: Day10.Coordinate, startDirection: Direction, grid: List<String>): Int {
val seenCoordinates = mutableSetOf<Pair<Day10.Coordinate, Direction>>()
val queue = ArrayDeque<Pair<Day10.Coordinate, Direction>>()
queue.add(startCoordinate to startDirection)
while (queue.isNotEmpty()) {
val (currentCoordinate, currentDirection) = queue.removeFirst()
if (currentCoordinate.x < 0 || currentCoordinate.y < 0 || currentCoordinate.y >= grid.size || currentCoordinate.x >= grid[currentCoordinate.y].length) {
continue
}
if (seenCoordinates.contains(currentCoordinate to currentDirection)) {
continue
}
seenCoordinates.add(currentCoordinate to currentDirection)
val nextCoordinates = next(currentCoordinate, currentDirection, grid)
queue.addAll(nextCoordinates)
}
return seenCoordinates.map { (coordinate, _) -> coordinate }.distinct().count()
}
private fun next(
currentCoordinate: Day10.Coordinate,
direction: Direction,
grid: List<String>
): List<Pair<Day10.Coordinate, Direction>> {
val currentMarker = grid[currentCoordinate.y][currentCoordinate.x]
when (currentMarker) {
'|' -> {
if (direction == Direction.UP || direction == Direction.DOWN) {
val nextCoordinate = when (direction) {
Direction.UP -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1)
Direction.DOWN -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1)
else -> throw IllegalStateException("Should not happen")
}
// Keep going the same direction
return listOf(nextCoordinate to direction)
} else {
return listOf(
Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1) to Direction.UP,
Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1) to Direction.DOWN
)
}
}
'-' -> {
if (direction == Direction.LEFT || direction == Direction.RIGHT) {
val nextCoordinate = when (direction) {
Direction.LEFT -> Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y)
Direction.RIGHT -> Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y)
else -> throw IllegalStateException("Should not happen")
}
// Keep going the same direction
return listOf(nextCoordinate to direction)
} else {
return listOf(
Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y) to Direction.LEFT,
Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y) to Direction.RIGHT
)
}
}
'\\' -> {
val (nextCoordinate, nextDirection) = when (direction) {
Direction.RIGHT -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1) to Direction.DOWN
Direction.LEFT -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1) to Direction.UP
Direction.UP -> Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y) to Direction.LEFT
Direction.DOWN -> Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y) to Direction.RIGHT
}
return listOf(nextCoordinate to nextDirection)
}
'/' -> {
val (nextCoordinate, nextDirection) = when (direction) {
Direction.LEFT -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1) to Direction.DOWN
Direction.RIGHT -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1) to Direction.UP
Direction.DOWN -> Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y) to Direction.LEFT
Direction.UP -> Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y) to Direction.RIGHT
}
return listOf(nextCoordinate to nextDirection)
}
'.' -> {
val nextCoordinate = when (direction) {
Direction.UP -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1)
Direction.DOWN -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1)
Direction.LEFT -> Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y)
Direction.RIGHT -> Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y)
}
return listOf(nextCoordinate to direction)
}
else -> throw IllegalStateException("Should not happen")
}
}
public fun part2(input: List<String>): String {
val leftStarts = (0 until input.size).map { y ->
Day10.Coordinate(0, y) to Direction.RIGHT
}
val rightStarts = (0 until input.size).map { y ->
Day10.Coordinate(input[y].length - 1, y) to Direction.LEFT
}
val topStarts = (0 until input[0].length).map { x ->
Day10.Coordinate(x, 0) to Direction.DOWN
}
val bottomStarts = (0 until input[0].length).map { x ->
Day10.Coordinate(x, input.size - 1) to Direction.UP
}
val allStarts = leftStarts + rightStarts + topStarts + bottomStarts
return allStarts.maxOf { (coordinate, direction) ->
energizeCount(coordinate, direction, input)
}.toString()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day16$Direction.class",
"javap": "Compiled from \"Day16.kt\"\npublic final class Day16$Direction extends java.lang.Enum<Day16$Direction> {\n public static final Day16$Direction UP;\n\n public static final Day16$Direction DOWN;\n\n public static final... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day11.kt | import kotlin.String
import kotlin.collections.List
object Day11 {
fun part1(input: List<String>): String {
val pairs = generatePairs(input)
val emptyRows = generateEmptyRows(input)
val emptyColumns = generateEmptyColumns(input)
return pairs.sumOf { (a, b) ->
manhattanDistance(a, b) + crossingRows(a, b, emptyRows) + crossingColumns(a, b, emptyColumns)
}.toString()
}
private fun crossingColumns(a: Day10.Coordinate, b: Day10.Coordinate, emptyColumns: Set<Int>): Long {
return emptyColumns.count { a.x < it && b.x > it || a.x > it && b.x < it }.toLong()
}
private fun crossingRows(a: Day10.Coordinate, b: Day10.Coordinate, emptyRows: Set<Int>): Long {
return emptyRows.count { a.y < it && b.y > it || a.y > it && b.y < it }.toLong()
}
private fun manhattanDistance(a: Day10.Coordinate, b: Day10.Coordinate): Long {
return (Math.abs(a.x - b.x) + Math.abs(a.y - b.y)).toLong()
}
fun part2(input: List<String>): String {
val pairs = generatePairs(input)
val emptyRows = generateEmptyRows(input)
val emptyColumns = generateEmptyColumns(input)
return pairs.sumOf { (a, b) ->
manhattanDistance(a, b) + crossingRows(a, b, emptyRows) * 999_999L + crossingColumns(
a,
b,
emptyColumns
) * 999_999L
}.toString()
}
private fun generatePairs(input: List<String>): List<Pair<Day10.Coordinate, Day10.Coordinate>> {
val coordinates = input.mapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == '#') {
Day10.Coordinate(x, y)
} else {
null
}
}
}.flatten()
return coordinates.indices.flatMap { i ->
(i + 1..<coordinates.size).map { j ->
Pair(coordinates[i], coordinates[j])
}
}
}
private fun generateEmptyColumns(input: List<String>): Set<Int> {
return (0..<input[0].length).filter { col ->
input.all { it[col] == '.' }
}.toSet()
}
private fun generateEmptyRows(input: List<String>): Set<Int> {
return input.mapIndexedNotNull { y, line ->
if (line.all { it == '.' }) {
y
} else {
null
}
}.toSet()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day11.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class Day11 {\n public static final Day11 INSTANCE;\n\n private Day11();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day18.kt | import java.util.*
import kotlin.String
import kotlin.collections.List
object Day18 {
data class Segment(val coordinates: Set<Day17.Coordinate>) {
val minX = coordinates.minOf { it.x }
val maxX = coordinates.maxOf { it.x }
val minY = coordinates.minOf { it.y }
val maxY = coordinates.maxOf { it.y }
fun crosses(coordinate: Day17.Coordinate): Boolean {
return if (minX == maxX && minX == coordinate.x) {
coordinate.y in minY..maxY
} else if (minY == maxY && minY == coordinate.y) {
coordinate.x in minX..maxX
} else {
false
}
}
fun crosses(y: Int): Boolean {
return y in minY..maxY
}
fun length(): Int {
return if (minX == maxX) {
maxY - minY + 1
} else {
maxX - minX + 1
}
}
/**
* Returns true if the segment is vertical, false otherwise
*/
fun isVertical(): Boolean {
return minX == maxX
}
/**
* Returns true if the segment is horizontal, false otherwise
*/
fun isHorizontal(): Boolean {
return minY == maxY
}
override fun hashCode(): Int {
return Objects.hash(minX, maxX, minY, maxY)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Segment
if (coordinates != other.coordinates) return false
if (minX != other.minX) return false
if (maxX != other.maxX) return false
if (minY != other.minY) return false
if (maxY != other.maxY) return false
return true
}
}
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT
}
data class Instruction(val direction: Direction, val steps: Int, val colorCode: String) {
fun toTrueInstruction(): Instruction {
val directionCode = colorCode.last()
val hexSteps = colorCode.drop(1).dropLast(1)
val steps = hexSteps.toInt(16)
val direction = when (directionCode) {
'0' -> Direction.RIGHT
'1' -> Direction.DOWN
'2' -> Direction.LEFT
'3' -> Direction.UP
else -> throw IllegalStateException("Should not happen")
}
return Instruction(direction, steps, colorCode)
}
companion object {
fun parse(input: String): Instruction {
val pattern = "([U|L|D|R]) ([0-9]+) \\((#[a-z0-9]+)\\)".toRegex()
val (rawDirection, rawSteps, rawColorCode) = pattern.matchEntire(input)!!.destructured
val direction = when (rawDirection) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> throw IllegalStateException("Should not happen")
}
val steps = rawSteps.toInt()
return Instruction(direction, steps, rawColorCode)
}
}
}
fun part1(input: List<String>): String {
val instructions = input.map { Instruction.parse(it) }
return cubicMetersEnclosed(instructions).toString()
}
fun cubicMetersEnclosed(instructions: List<Instruction>): Long {
val segments = dig(instructions)
val minY = segments.minOf { it.minY }
val maxY = segments.maxOf { it.maxY }
val minX = segments.minOf { it.minX }
val maxX = segments.maxOf { it.maxX }
val delta = maxY - minY
var current = 0
var mySegments = segments.sortedWith(compareBy({ it.minY }, { it.maxY }))
val enclosedCoordinates = (minY..maxY).sumOf { y ->
val startCoordinate = Day17.Coordinate(minX, y)
val endCoordinate = Day17.Coordinate(maxX, y)
val ret = rayCast(startCoordinate, endCoordinate, mySegments)
current += 1
if (current % 1000000 == 0) {
mySegments = mySegments.filter { it.maxY >= y }
println("Progress: ${String.format("%.2f", current.toDouble() / delta * 100)}%")
}
ret
}
val segmentSizes = segments.sumOf { it.length() }
val duplicateSegments =
segments.flatMap { it.coordinates.toList() }.groupBy { it }.filter { it.value.size > 1 }.keys.size
return (enclosedCoordinates + segmentSizes - duplicateSegments)
}
private fun rayCast(
startCoordinate: Day17.Coordinate,
endCoordinate: Day17.Coordinate,
segments: List<Segment>
): Long {
var segmentsEncountered = 0
var cellsWithinPolygon = 0L
val runningSegmentsCrossed = mutableSetOf<Segment>()
var currentX = startCoordinate.x
val segmentsCrossedByRay = segments
.takeWhile { it.minY <= endCoordinate.y }
.filter { it.crosses(startCoordinate.y) }
while (currentX <= endCoordinate.x) {
val currentCoordinate = Day17.Coordinate(currentX, startCoordinate.y)
val segmentCrosses = segmentsCrossedByRay.filter { it.crosses(currentCoordinate) }
val sizeBefore = runningSegmentsCrossed.size
runningSegmentsCrossed.addAll(segmentCrosses)
val sizeAfter = runningSegmentsCrossed.size
val touchedAnotherSegment = sizeAfter > sizeBefore
if (segmentCrosses.isNotEmpty()) {
// Advance the current position to the max x value of the segment we crossed
currentX = segmentCrosses.maxOf { it.maxX }
// This is an odd edge case
// where there are overlapping segments that are connected
// but we encountered the last one
if (!touchedAnotherSegment) {
currentX += 1
}
} else {
if (isSingleOrSnakeShaped(runningSegmentsCrossed)) {
segmentsEncountered += 1
}
runningSegmentsCrossed.clear()
val nextSegmentToBeCrossed = segmentsCrossedByRay
.minOfOrNull { if (it.minX > currentX) it.minX else Int.MAX_VALUE }
val nextX = nextSegmentToBeCrossed ?: (endCoordinate.x + 1)
// If the number of segments encountered is odd, then we are within the polygon
val isWithinPolygon = segmentsEncountered % 2 == 1
if (isWithinPolygon) {
val lengthOfEmptySpace = nextX - currentX
cellsWithinPolygon += lengthOfEmptySpace
}
// Advance the current position to the next segment crossing since all of
// these are filled or ignored
currentX = nextX
}
}
return cellsWithinPolygon
}
/**
* An annoying case in which we can run into
* is when we have a single segment or a snake shaped segment
*
* #
* #
* #
* # # #
* #
* #
* #
*
* This counts as one segment
*/
private fun isSingleOrSnakeShaped(crossedSegments: Set<Segment>): Boolean {
if (crossedSegments.isEmpty()) {
return false
}
if (crossedSegments.size == 1) {
return true
}
if (crossedSegments.size == 2) {
return false
}
val verticalSegments = crossedSegments.count { it.isVertical() }
val horizontalSegments = crossedSegments.count { it.isHorizontal() }
return if (verticalSegments > horizontalSegments) {
// This means that the segments are vertical but share a same y coordinte, like
//
// #
// #
// #
// # # #
// #
// #
// #
val sorted = crossedSegments.sortedWith(
compareBy({ it.minX }, { it.maxX })
)
val start = sorted.first()
val end = sorted.last()
val ys = start.coordinates.map { it.y }.toList() + end.coordinates.map { it.y }.toList()
val grouped = ys.groupBy { it }
val ysThatAppearTwice = grouped.filter { it.value.size == 2 }.keys.first()
ysThatAppearTwice > ys.min() && ysThatAppearTwice < ys.max()
} else {
// This means that the segments are horizontal but share a same x coordinate, like
//
// # # # #
// #
// #
// #
// #
// #
// # # # #
val sorted = crossedSegments.sortedWith(compareBy({ it.minY }, { it.maxY }))
val start = sorted.first()
val end = sorted.last()
val xs = start.coordinates.map { it.x }.toList() + end.coordinates.map { it.x }.toList()
val grouped = xs.groupBy { it }
val xsThatAppearTwice = grouped.filter { it.value.size == 2 }.keys.first()
xsThatAppearTwice > xs.min() && xsThatAppearTwice < xs.max()
}
}
/**
* Take a list of instructions that take a starting point and a direction to "dig", which
* will then be represented as line segments
*/
fun dig(instructions: List<Instruction>): List<Segment> {
val currentCoordinate = Day17.Coordinate(0, 0)
return instructions.fold(currentCoordinate to emptyList<Segment>()) { (currentCoordinate, segments), instruction ->
val direction = instruction.direction
val steps = instruction.steps
val nextCoordinate = when (direction) {
Direction.UP -> Day17.Coordinate(currentCoordinate.x, currentCoordinate.y - steps)
Direction.DOWN -> Day17.Coordinate(currentCoordinate.x, currentCoordinate.y + steps)
Direction.LEFT -> Day17.Coordinate(currentCoordinate.x - steps, currentCoordinate.y)
Direction.RIGHT -> Day17.Coordinate(currentCoordinate.x + steps, currentCoordinate.y)
}
val segment = Segment(setOf(currentCoordinate, nextCoordinate))
nextCoordinate to (segments + listOf(segment))
}.second
}
fun part2(input: List<String>): String {
val instructions = input.map { Instruction.parse(it) }.map { it.toTrueInstruction() }
return cubicMetersEnclosed(instructions).toString()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day18$Direction.class",
"javap": "Compiled from \"Day18.kt\"\npublic final class Day18$Direction extends java.lang.Enum<Day18$Direction> {\n public static final Day18$Direction UP;\n\n public static final Day18$Direction DOWN;\n\n public static final... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day4.kt | import kotlin.String
import kotlin.collections.List
import kotlin.math.pow
object Day4 {
data class CardData(val cardIndex: Int, val winningNumberCount: Int) {
companion object {
fun parseCardData(input: String): CardData {
val (cardInformation, numberInformation) = input.split(":")
val cardIndex = cardInformation.trimStart(*"Card ".toCharArray()).toInt()
val (winningNumberInformation, cardNumberInformation) = numberInformation.split("|")
val winningNumbers = parseNumbers(winningNumberInformation)
val cardNumbers = parseNumbers(cardNumberInformation)
val winningNumberCount = cardNumbers.filter { winningNumbers.contains(it) }.count()
return CardData(cardIndex, winningNumberCount)
}
private fun parseNumbers(numbers: String): List<Int> {
return numbers.trimStart(*" ".toCharArray())
.trimEnd(*" ".toCharArray())
.split(" ")
.filter(String::isNotEmpty)
.map { it.toInt() }
}
}
fun score(): Int {
val exp = winningNumberCount - 1
return 2.0.pow(exp.toDouble()).toInt()
}
fun cardIndexesToCopy(): IntRange {
return (cardIndex + 1..cardIndex + winningNumberCount)
}
}
fun part1(input: List<String>): String = input.map(CardData::parseCardData).map(CardData::score).sum().toString()
fun part2(input: List<String>): String = findTotalCards(input.map(CardData::parseCardData)).toString()
private fun findTotalCards(cards: List<CardData>): Int {
val cardMultiplierCount = mutableMapOf<Int, Int>()
return cards.map {
val multiplier = (cardMultiplierCount[it.cardIndex] ?: 0) + 1
it.cardIndexesToCopy().forEach {
cardMultiplierCount.merge(it, multiplier) { a, b -> a + b }
}
multiplier
}.sum()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day4$CardData$Companion.class",
"javap": "Compiled from \"Day4.kt\"\npublic final class Day4$CardData$Companion {\n private Day4$CardData$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day14.kt | import Day13.transpose
import kotlin.String
import kotlin.collections.List
object Day14 {
private const val ROUNDED = 'O'
fun part1(input: List<String>): String {
val transposedDish = transpose(input)
return transposedDish.sumOf { row ->
val rolled = roll(row)
rolled.reversed().withIndex().filter { (_, char) -> char == ROUNDED }.sumOf { (idx, _) -> idx + 1 }
}.toString()
}
private fun roll(row: String): String {
if (row.isBlank()) {
return row
}
if (row[0] == ROUNDED) {
return row[0] + roll(row.substring(1))
}
val indexToSwap = row.withIndex().dropWhile { (_, char) -> char == '.' }.firstOrNull()
if (indexToSwap == null) {
return row
}
val (idx, _) = indexToSwap
return if (row[idx] == ROUNDED) {
ROUNDED.toString() + roll(row.substring(1, idx) + "." + row.substring(idx + 1))
} else {
row.substring(0, idx + 1) + roll(row.substring(idx + 1))
}
}
fun part2(input: List<String>): String {
val cycled = cycleUntil(transpose(input), 1_000_000_000)
return cycled
.sumOf { row ->
val rowSum =
row.reversed().withIndex().filter { (_, char) -> char == ROUNDED }.sumOf { (idx, _) -> idx + 1 }
rowSum
}
.toString()
}
private fun cycleUntil(grid: List<String>, targetCycles: Int): List<String> {
val seenMap = mutableMapOf<List<String>, Long>()
var cycles = 0L
var cycled = cycle(grid)
while (cycles < targetCycles) {
cycled = cycle(cycled)
cycles++
if (seenMap.containsKey(cycled)) {
val firstSeen = seenMap[cycled]!!
val cyclesSince = cycles - firstSeen
var remainingCycles = (targetCycles - cycles) % cyclesSince - 1
while (remainingCycles > 0) {
cycled = cycle(cycled)
remainingCycles--
}
break
} else {
seenMap[cycled] = cycles
}
}
return cycled
}
private fun cycle(grid: List<String>): List<String> {
val northRoll = grid.map { roll(it) }
val west = transpose(northRoll)
val westRoll = west.map { roll(it) }
val south = transpose(westRoll).map { it.reversed() }
val southRoll = south.map { roll(it) }
val east = transpose(southRoll.map { it.reversed() }).map { it.reversed() }
val eastRoll = east.map { roll(it) }
val backNorth = transpose(eastRoll.map { it.reversed() })
return backNorth
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day14.class",
"javap": "Compiled from \"Day14.kt\"\npublic final class Day14 {\n public static final Day14 INSTANCE;\n\n private static final char ROUNDED;\n\n private Day14();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day6.kt | import kotlin.String
import kotlin.collections.List
import kotlin.math.*
object Day6 {
fun part1(input: List<String>): String {
val parseNumbers: (String, String) -> List<Int> = { str: String, prefix: String ->
str.replace(prefix, "")
.trim()
.split("\\s+".toRegex())
.map { it.toInt() }
}
val times = parseNumbers(input.first(), "Time:")
val distances = parseNumbers(input.last(), "Distance:")
return times.zip(distances)
.map { (time, distance) ->
val (maxTime, minTime) = maxAndMinTimes(time.toLong(), distance.toLong())
maxTime - minTime + 1
}.reduce { a, b -> a * b }.toString()
}
fun part2(input: List<String>): String {
val parseNumber: (String, String) -> Long = { str: String, prefix: String ->
str.replace(prefix, "")
.trim()
.replace(" ", "")
.toLong()
}
val time = parseNumber(input.first(), "Time:")
val distance = parseNumber(input.last(), "Distance:")
val (maxTime, minTime) = maxAndMinTimes(time, distance)
// Add 1 to count the upper as inclusive
return (maxTime - minTime + 1).toString()
}
/**
* If we look at the equation for distance, we get:
* distance = holdTime * (time - holdTime)
* Turning this into a quadratic equation, we get:
* 0 = -holdTime^2 + time * holdTime - distance
*
* We can then use the quadratic formula to find the holdTime:
* holdTime = (-time +- sqrt(time^2 - 4 * -(distance + 1))) / -2
*
* Note, we set distance + 1 because we have to exceed the target distance
*/
private fun maxAndMinTimes(time: Long, distance: Long): Pair<Long, Long> {
val squareRoot = sqrt(time.toDouble().pow(2) - 4 * (distance + 1))
val upper = (-time - squareRoot) / -2
val lower = (-time + squareRoot) / -2
// We have to floor the upper because we cannot hold fractional seconds, and have to ceil the lower
return floor(upper).toLong() to ceil(lower).toLong()
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day6.class",
"javap": "Compiled from \"Day6.kt\"\npublic final class Day6 {\n public static final Day6 INSTANCE;\n\n private Day6();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n... |
cbrentharris__kotlin-kringle__f689f8b/src/main/kotlin/Day9.kt | import kotlin.String
import kotlin.collections.List
object Day9 {
fun part1(input: List<String>): String {
return parse(input)
.sumOf { extrapolate(it) { deltas, ret -> deltas.last() + ret } }.toString()
}
fun part2(input: List<String>): String {
return parse(input)
.sumOf { extrapolate(it) { deltas, ret -> deltas.first() - ret } }.toString()
}
private fun parse(input: List<String>): List<List<Long>> {
return input.map { it.split("\\s+".toRegex()).map { it.toLong() } }
}
private fun extrapolate(input: List<Long>, extrapolator: (List<Long>, Long) -> Long): Long {
val deltas = input.zipWithNext().map { (a, b) -> b - a }
if (deltas.all { it == 0L }) {
return extrapolator(input, 0)
}
return extrapolator(input, extrapolate(deltas, extrapolator))
}
}
| [
{
"class_path": "cbrentharris__kotlin-kringle__f689f8b/Day9.class",
"javap": "Compiled from \"Day9.kt\"\npublic final class Day9 {\n public static final Day9 INSTANCE;\n\n private Day9();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n... |
skarlman__AdventOfCode2022_kotlin__ef15752/src/Day03.kt | import java.io.File
// Problem:
// https://adventofcode.com/2022/day/3
// More solutions:
// https://www.competitivecoders.com/ProgrammingCompetitions/advent-of-code/advent-of-code/2022/day-3/
fun main() {
fun part1(input: List<String>): Int {
return input.map { row ->
val parts = row.chunked(row.length / 2)
for (c in parts[0]) {
if (parts[1].contains(c)) {
return@map if (c.code > 96) c.code - 96 else c.code - 64 + 26
}
}
return@map 0
}.sum()
}
fun part2(input: List<String>): Int {
return input.chunked(3).map {
for (c in it[0]) {
if (it[1].contains(c) && it[2].contains(c)){
return@map if (c.code > 96) c.code - 96 else c.code - 64 + 26
}
}
return@map 0
}.sum()
}
val input = readInput("Day03")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun readInput(name: String) = File("src", "$name.txt")
.readLines() | [
{
"class_path": "skarlman__AdventOfCode2022_kotlin__ef15752/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day03\n 2: invokestatic #12 // Method re... |
skarlman__AdventOfCode2022_kotlin__ef15752/src/Day02.kt | import java.io.File
// Problem:
// https://adventofcode.com/2022/day/2
// More solutions:
// https://www.competitivecoders.com/ProgrammingCompetitions/advent-of-code/advent-of-code/2022/day-2/
fun main() {
fun part1(input: List<String>): Int {
val scores = mapOf(
Pair("A", "X") to 1 + 3,
Pair("A", "Y") to 2 + 6,
Pair("A", "Z") to 3 + 0,
Pair("B", "X") to 1 + 0,
Pair("B", "Y") to 2 + 3,
Pair("B", "Z") to 3 + 6,
Pair("C", "X") to 1 + 6,
Pair("C", "Y") to 2 + 0,
Pair("C", "Z") to 3 + 3,
)
return input.map { row ->
row.split(" ")
.let {
scores.getValue(Pair(it[0], it[1]))
}
}.sum()
}
fun part2(input: List<String>): Int {
val scores = mapOf(
Pair("A", "X") to 3 + 0,
Pair("A", "Y") to 1 + 3,
Pair("A", "Z") to 2 + 6,
Pair("B", "X") to 1 + 0,
Pair("B", "Y") to 2 + 3,
Pair("B", "Z") to 3 + 6,
Pair("C", "X") to 2 + 0,
Pair("C", "Y") to 3 + 3,
Pair("C", "Z") to 1 + 6,
)
return input.map { row ->
row.split(" ")
.let {
scores.getValue(Pair(it[0], it[1]))
}
}.sum()
}
val input = readInput("Day02")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun readInput(name: String) = File("src", "$name.txt")
.readLines() | [
{
"class_path": "skarlman__AdventOfCode2022_kotlin__ef15752/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day02\n 2: invokestatic #12 // Method re... |
wenvelope__OnlineJudge__4a5b258/src/main/kotlin/QuickSort.kt | import java.util.*
fun main() {
val mutableList = arrayListOf(3,23,5435,2323,43,32,43)
println(mutableList)
println( mutableList.quickSort().let { mutableList })
}
/**
*快排
* 思想:分治
* 1.从大到小每一层都一分为二 分到不能再分为止
* 2.对于每一个小部分 都选定一个和标志位 使得标志位的左边都小于右边
*/
fun MutableList<Int>.quickSort() {
if (this.isEmpty()) {
return
}
val stack = Stack<Int>()
stack.push(0)
stack.push(this.size - 1)
while (stack.isNotEmpty()) {
val highIndex = stack.pop()
val lowIndex = stack.pop()
if (lowIndex < highIndex) {
val flagIndex = partition(mList = this, lowIndex = lowIndex, highIndex = highIndex)
stack.push(lowIndex)
stack.push(flagIndex - 1)
stack.push(flagIndex + 1)
stack.push(highIndex)
}
}
}
/**
* 选取一个标志位 让列表中的左边小于标志位右边大于标志位
*
* @return 标志位的索引
*/
fun partition(mList: MutableList<Int>, lowIndex: Int, highIndex: Int): Int {
val flag = mList[highIndex]
//最后一个小于flag的元素的位置 初始为lowIndex-1
var theLowIndex = lowIndex - 1
for (index in lowIndex until highIndex){
if (mList[index]<flag){
mList.swap(theLowIndex+1,index)
theLowIndex++
}
}
mList.swap(theLowIndex + 1, highIndex)
return theLowIndex + 1
}
/**
* 交换两个索引对应元素的位置
*/
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val temp = this[index1]
set(index = index1, element = this[index2])
set(index = index2, element = temp)
}
| [
{
"class_path": "wenvelope__OnlineJudge__4a5b258/QuickSortKt.class",
"javap": "Compiled from \"QuickSort.kt\"\npublic final class QuickSortKt {\n public static final void main();\n Code:\n 0: bipush 7\n 2: anewarray #8 // class java/lang/Integer\n 5: astore_... |
20Koen02__AdventOfCode__e260249/2021/08-kt/main.kt | import java.io.File
import kotlin.collections.listOf
typealias Entry = List<List<String>>
val DIGS =
listOf("abcdeg", "ab", "acdfg", "abcdf", "abef", "bcdef", "bcdefg", "abd", "abcdefg", "abcdef")
fun readLines(): List<Entry> {
return File("in.txt").bufferedReader().readLines().map { l ->
l.split(" | ").map { it.split(" ") }
}
}
fun String.permute(result: String = ""): List<String> =
if (isEmpty()) listOf(result)
else flatMapIndexed { i, c -> removeRange(i, i + 1).permute(result + c) }
fun partOne(entry: Entry): Int {
return entry[1].filter { x -> listOf(2, 3, 4, 7).contains(x.length) }.count()
}
fun getValidDigit(perm: String, dig: String): Int {
// Check if the digit is valid
var decoded = dig.map { perm[it - 'a'] }.sorted().joinToString("")
return DIGS.indexOf(decoded)
}
fun tryPerm(perm: String, entry: Entry): Boolean {
// Check if all signal patterns are valid digits
var invalid = entry[0].map { getValidDigit(perm, it) }.any { it == -1 }
return !invalid
}
fun partTwo(entry: Entry): Int {
// Find correct permutation
val perm = "abcdefg".permute().find { tryPerm(it, entry) }
// Concat each digit
return entry[1].map { getValidDigit(perm!!, it) }.joinToString(separator = "").toInt()
}
fun main() {
println("Running...\n")
val lines = readLines()
val partOne = lines.map { partOne(it) }.sum()
println("Day 8 part one: $partOne")
val partTwo = lines.map { partTwo(it) }.sum()
println("Day 8 part two: $partTwo")
}
| [
{
"class_path": "20Koen02__AdventOfCode__e260249/MainKt.class",
"javap": "Compiled from \"main.kt\"\npublic final class MainKt {\n private static final java.util.List<java.lang.String> DIGS;\n\n public static final java.util.List<java.lang.String> getDIGS();\n Code:\n 0: getstatic #12 ... |
ummen-sherry__adventofcode2023__c91c1b6/src/main/kotlin/Day1.kt | import java.io.File
private val numberRegex = Regex("""(\d|one|two|three|four|five|six|seven|eight|nine)""")
private val numberReverseRegex = Regex("""(\d|enin|thgie|neves|xis|evif|ruof|eerht|owt|eno)""")
private val validNumbers = mapOf(
"1" to 1,
"2" to 2,
"3" to 3,
"4" to 4,
"5" to 5,
"6" to 6,
"7" to 7,
"8" to 8,
"9" to 9,
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9
)
fun sumOfCalibrationValues(input: List<String>): Int {
return input.sumOf {
"${it.first { it.isDigit() }}${it.last { it.isDigit() }}".toInt()
}
}
fun readFile(fileName: String): List<String> {
val resourceFile: File = File("src/main/resources/$fileName") // Adjust the path accordingly
return resourceFile.bufferedReader().use { it.readLines() }
}
fun sumOfCalibrationValuesWithStringDigits(input: List<String>): Int {
return input.mapNotNull { line ->
validNumbers[numberRegex.find(line)?.value ?: ""]
?.let { firstDigit ->
validNumbers[numberReverseRegex.find(line.reversed())?.value?.reversed() ?: ""]
?.let { secondDigit ->
"$firstDigit$secondDigit".toInt()
}
}
}.sum()
}
fun main(args: Array<String>) {
println("Advent 2023 - Day1")
// Part 1
// val input = readFile("day-1-input1.txt")
// val sumOfCalibrationValues = sumOfCalibrationValues(input)
// println("Sum: $sumOfCalibrationValues")
// Part 2
val input = readFile("day-1-input2.txt")
val sumOfCalibrationValues = sumOfCalibrationValuesWithStringDigits(input)
println("Sum: $sumOfCalibrationValues")
}
| [
{
"class_path": "ummen-sherry__adventofcode2023__c91c1b6/Day1Kt.class",
"javap": "Compiled from \"Day1.kt\"\npublic final class Day1Kt {\n private static final kotlin.text.Regex numberRegex;\n\n private static final kotlin.text.Regex numberReverseRegex;\n\n private static final java.util.Map<java.lang.St... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.