How to Base64 encode an IntArray in Kotlin - kotlin

How to base64 encode a buff of intArrayOf using Kotlin.
val vec = intArrayOf(1,2,3,4,5)
val data =?!
val base64Encoded = Base64.encodeToString(data, Base64.DEFAULT);

The 'ByteArray" representation of an IntArray can be calculated like this:
fun IntArray.toByteArray(): ByteArray {
val result = ByteArray(this.size * 4)
for ((idx, value) in this.withIndex()) {
result[idx + 3] = (value and 0xFF).toByte()
result[idx + 2] = ((value ushr 8) and 0xFF).toByte()
result[idx + 1] = ((value ushr 16) and 0xFF).toByte()
result[idx] = ((value ushr 24) and 0xFF).toByte()
}
return result
}
This result can then be Base64 encoded like mentioned in the question:
val vec = intArrayOf(1,2,3,4,5)
val data = vec.toByteArray()
val base64Encoded = Base64.encodeToString(data, Base64.DEFAULT);

Related

Divide list into two list

Is there a simple way to divide list of Double into two lists of pairs in Kotlin?
In such way:
[x1, y1, x2, y2, x3, y3] => [(x1, x2), (x2, x3), (x3, x1)], [(y1, y2), (y2, y3), (y3, y1)]
I tried to use filterIndexed and zipWithNext
val x = filterIndexed { index, _ -> index % 2 == 0 }.zipWithNext()
val y = filterIndexed { index, _ -> index % 2 == 1 }.zipWithNext()
But the result is:
[x1, y1, x2, y2, x3, y3] => [(x1, x2), (x2, x3)], [(y1, y2), (y2, y3)]
If I understand correctly, the problem with the zipWithNext that you are using is that it doesn't "wrap around", i.e. output the final (x3, x1) or (y3, y1) pair, containing the last and first elements of the list.
You can fix this by simply declaring your own version of zipWithNext that does do this.
You can either do something like this:
fun <T> Iterable<T>.zipWithNextAndWrapAround(): List<Pair<T, T>> {
val zippedWithNext = zipWithNext()
if (zippedWithNext.isEmpty()) return zippedWithNext
return zippedWithNext + (zippedWithNext.last().second to zippedWithNext.first().first)
}
Or copy and paste over the original source code of zipWithNext and slightly modify it:
fun <T> Iterable<T>.zipWithNextAndWrapAround(): List<Pair<T, T>> {
val iterator = iterator()
if (!iterator.hasNext()) return emptyList()
val result = mutableListOf<Pair<T, T>>()
var current = iterator.next()
// remember what the first element was
val first = current
while (iterator.hasNext()) {
val next = iterator.next()
result.add(current to next)
current = next
}
// at last, add this pair
result.add(current to first)
return result
}
Usage:
val x = list.filterIndexed { index, _ -> index % 2 == 0 }.zipWithNextAndWrapAround()
val y = list.filterIndexed { index, _ -> index % 2 == 1 }.zipWithNextAndWrapAround()
Note that this is looping through the list twice. You can avoid that by writing your own version of partition called partitionIndexed.
The code could be something like:
inline fun <T> Iterable<T>.partitionIndexed(predicate: (Int, T) -> Boolean): Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
forEachIndexed { index, element ->
if (predicate(index, element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
// usage:
val (x, y) = list.partitionIndexed { index, _ ->
index % 2 == 0
}.let { (a, b) ->
a.zipWithNextAndWrapAround() to b.zipWithNextAndWrapAround()
}
You could do something like this:
val lst = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val intermediate = lst.chunked(2).map { it[0] to it[1] }.let { it + it[0] }
val x = intermediate.map { it.first }.zipWithNext()
val y = intermediate.map { it.second }.zipWithNext()
println(x) //[(1, 3), (3, 5), (5, 7), (7, 1)]
println(y) //[(2, 4), (4, 6), (6, 8), (8, 2)]
val input = listOf("x1", "y1", "x2", "y2", "x3", "y3")
val result = list
.withIndex()
.groupBy { it.index % 2 }
.map { entry -> entry.value.map { it.value } }
.map { (it + it[0]).zipWithNext() }
println(result)
Output:
[[(x1, x2), (x2, x3), (x3, x1)], [(y1, y2), (y2, y3), (y3, y1)]]

Two sum in kotlin

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
I am adding piece of code.
fun main() {
// val nums = intArrayOf(2, 7, 11, 15)
// val target = 9
val nums = intArrayOf(3, 2, 4)
val target = 6
// val nums = intArrayOf(3, 3)
// val target = 6
twoSum(nums, target).forEach {
print(" $it")
}
}
fun twoSum(nums: IntArray, target: Int): IntArray {
val map = mutableMapOf<Int, Int>()
nums.forEachIndexed { index, i ->
map[i]?.let {
return intArrayOf(it, index)
}
map[target - i] = index
}
return intArrayOf()
}
My youtube link is described that I am debugging the code. My question is how
map[i]?.let {
return intArrayOf(it, index)
}
is going inside the 1st and 2nd iteration of return statment and it not going in 3rd iteration. Can anyone help me on this. Thanks

Kotlin Calculating with BigDecimal vs Double

I have 2 Functions. One uses BigInteger and BigDecimal. I want to calculate sin(z) using the Taylor series:
Here is my code:
fun sinus(z: BigDecimal, upperBound: Int = 100): BigDecimal = calcSin(z, upperBound)
fun cosinus(z: BigDecimal, upperBound: Int = 100): BigDecimal = calcSin(z, upperBound, false)
fun calcSin(z: BigDecimal, upperBound: Int = 100, isSin: Boolean = true): BigDecimal {
var erg: BigDecimal = BigDecimal.ZERO
for (n in 0..upperBound) {
// val zaehler = (-1.0).pow(n).toBigDecimal() * z.pow(2 * n + (if (isSin) 1 else 0))
// val nenner = fac(2 * n + (if (isSin) 1 else 0)).toBigDecimal()
val zaehler = (-1.0).pow(n).toBigDecimal() * z.pow(2 * n + 1)
val nenner = fac(2 * n + 1).toBigDecimal()
erg += (zaehler / nenner)
}
return erg
}
fun calcSin(z: Double, upperBound: Int = 100): Double {
var res = 0.0
for (n in 0..upperBound) {
val zaehler = (-1.0).pow(n) * z.pow(2 * n + 1)
val nenner = fac(2 * n + 1, true)
res += (zaehler / nenner)
}
return res
}
fun fac(n: Int): BigInteger = if (n == 0 || n == 1) BigInteger.ONE else n.toBigInteger() * fac(n - 1)
fun fac(n: Int, dummy: Boolean): Double = if (n == 0 || n == 1) 1.0 else n.toDouble() * fac(n - 1, dummy)
According to Google, Sin(1) is
0.8414709848
The Output of the following is however:
println("Sinus 1: ${sinus(1.0.toBigDecimal())}")
println("Sinus 1: ${sinus(1.0.toBigDecimal()).toDouble()}")
println("Sinus 1: ${sinus(1.0.toBigDecimal(), 1000)}")
println("Sinus 1: ${calcSin(1.0)}")
Output:
Sinus 1: 0.8414373208078281027995610599000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Sinus 1: 0.8414373208078281
Sinus 1: 0.8414373208078281027995610599000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Sinus 1: 0.8414709848078965
Wha am I missing? Why does the Double-Variant gives the correct value, while The BigDecimal doesn't? Even with 1000 Iterations.
The commented out code was meant for calculation Cos as well, but wanted to figure out that Problem first, so i made both Functions look the same
In the BigDecimal variant, try replacing erg += (zaehler / nenner) with erg += (zaehler.divide(nenner, 20, RoundingMode.HALF_EVEN))
I suspect that the defaults for scaling the division results (as described here https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html) are not what you want.
BTW - I assume that performance is not part of the exercise, otherwise your implementation of factorial is a low hanging fruit.

Kotlin filter String by List of indices

How do I filter a List of indices out of a String? Thanks.
val s = "abcdef"
val indices = listOf(1, 2, 3, 4)
val filtered = s.filterIndexed {i, _ -> i != /* ??? */ }
// outcome: filtered = "af"

Avoiding explicit record typing

Suppose I have the following functions for operating over an idealized stream:
fun Stream s = { pos = 0, row = 1, col = 0, str = s }
fun len { str, pos = _, row = _, col = _ } = String.size str
fun poke off { str, pos, row: int, col: int } =
let val n = pos + off in
if n >= 0 andalso n <= (String.size str) then SOME (String.sub(str, n)) else NONE
end
This works/compiles, but it's unfortunate to have to litter my function definitions with information I don't care about. row/col are ignored poke and len. However, while the wildcard can be used with len, it can't be with poke. Is there a way to restructure these functions so that less explicit typing needs to be put in, while still being able to pattern match/destructure?
If you give your type a name (such as stream), you can refer to it more briefly:
type stream = { pos : int, row : int, col : int, str : string }
fun Stream s = { pos = 0, row = 1, col = 0, str = s }
fun len ({ str, ... } : stream) = String.size str
fun poke off ({ str, pos, ... } : stream) =
let val n = pos + off in
if n >= 0 andalso n <= String.size str
then SOME (String.sub (str, n))
else NONE
end
Or, more-or-less equivalently:
datatype stream = STREAM of { pos : int, row : int, col : int, str : string }
fun Stream s = STREAM { pos = 0, row = 1, col = 0, str = s }
fun len (STREAM { str, ... }) = String.size str
fun poke off (STREAM { str, pos, ... }) =
let val n = pos + off in
if n >= 0 andalso n <= String.size str
then SOME (String.sub (str, n))
else NONE
end