Skip to content

Instantly share code, notes, and snippets.

@duangsuse
Forked from CattenLinger/CustomBaseNumber.kt
Last active February 13, 2020 04:23
Show Gist options
  • Save duangsuse/2c2cf4c6822d92fe8802df23c50bdd8e to your computer and use it in GitHub Desktop.
Save duangsuse/2c2cf4c6822d92fe8802df23c50bdd8e to your computer and use it in GitHub Desktop.
CustomBaseNumberKt
import kotlin.math.abs
private val max = CustomBase.from(Long.MAX_VALUE)
private val maxLength = max.length
object CustomBase {
val radix = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toList().toCharArray()
val base = radix.size.toLong()
fun from(long: Long): String {
require(long > 0) {"Negative encoding is not supported: $long"}
val sb = StringBuilder()
var rest = long
while (rest != 0L) {
val digit = radix[ (rest % base).toInt() ]
sb.append(digit); rest /= base
}
return sb.reversed().toString()
}
fun fromRecursive(long: Long): String {
fun fromRec(rest: Long): StringBuilder
= if (rest < base) StringBuilder( radix[rest.toInt()].toString() )
else fromRec(rest / base).append(radix[ (rest % base).toInt() ])
return fromRec(long).toString()
}
fun fromFold(long: Long): String = generateSequence(long) { i -> (i / base).takeIf { it > 0 } }
.map { it % base }.fold(StringBuilder()) { sb, d -> sb.append(radix[d.toInt()]) }
.reversed().toString()
fun fromLengthed(long: Long, max: Int): String {
val limit = max.coerceAtMost(maxLength)
val str = from(long)
return str.takeIf { it.length >= limit } ?:
if (str.length == limit -1) "_$str"
else (limit - str.length).downTo(1).map(radix::get)
.joinToString("", transform = Char::toString) + str
}
fun to(str: String): Long {
var rest = 0L
for (c in str) {
val d = radix.indexOf(c)
rest = rest*base + d
}
return rest
}
fun toFold(str: String): Long = generateSequence(1L) { it * base/*k*/ }.zip(str.reversed().asSequence()) /*d*/
.sumBy { it.first * radix.indexOf(it.second) }
}
inline fun <T> Sequence<T>.sumBy(selector: (T) -> Long): Long {
var accumulator = 0L
forEach { accumulator += selector(it) }
return accumulator
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment