Non-decimal radices/Convert: Difference between revisions

Added Kotlin
(→‎JS ES6: Normalised output sequence of unfoldr, simplified test)
(Added Kotlin)
Line 1,780:
255
10
 
=={{header|Kotlin}}==
An approach from first principles rather than using Java library functions:
{{trans|FreeBASIC}}
<lang scala>// version 1.0.6
 
fun min(x: Int, y: Int) = if (x < y) x else y
 
fun convertToBase(n: Int, b: Int): String {
if (n < 2 || b < 2 || b == 10 || b > 36) return n.toString() // leave as decimal
val sb = StringBuilder()
var digit: Int
var nn = n
while (nn > 0) {
digit = nn % b
if (digit < 10) sb.append(digit)
else sb.append((digit + 87).toChar())
nn /= b
}
return sb.reverse().toString()
}
 
fun convertToDecimal(s: String, b: Int): Int {
if (b !in 2..36) throw IllegalArgumentException("Base must be between 2 and 36")
if (b == 10) return s.toInt()
val t = s.toLowerCase()
var result = 0
var digit: Int
var multiplier = 1
for (i in t.length - 1 downTo 0) {
digit = -1
if (t[i] >= '0' && t[i] <= min(57, 47 + b).toChar())
digit = t[i].toInt() - 48
else if (b > 10 && t[i] >= 'a' && t[i] <= min(122, 87 + b).toChar())
digit = t[i].toInt() - 87
if (digit == -1) throw IllegalArgumentException("Invalid digit present")
if (digit > 0) result += multiplier * digit
multiplier *= b
}
return result
}
 
fun main(args: Array<String>) {
for (b in 2..36) {
val s = convertToBase(36, b)
val f = "%2d".format(b)
println("36 base $f = ${s.padEnd(6)} -> base $f = ${convertToDecimal(s, b)}")
}
}</lang>
 
{{out}}
<pre>
36 base 2 = 100100 -> base 2 = 36
36 base 3 = 1100 -> base 3 = 36
36 base 4 = 210 -> base 4 = 36
36 base 5 = 121 -> base 5 = 36
36 base 6 = 100 -> base 6 = 36
36 base 7 = 51 -> base 7 = 36
36 base 8 = 44 -> base 8 = 36
36 base 9 = 40 -> base 9 = 36
36 base 10 = 36 -> base 10 = 36
36 base 11 = 33 -> base 11 = 36
36 base 12 = 30 -> base 12 = 36
36 base 13 = 2a -> base 13 = 36
36 base 14 = 28 -> base 14 = 36
36 base 15 = 26 -> base 15 = 36
36 base 16 = 24 -> base 16 = 36
36 base 17 = 22 -> base 17 = 36
36 base 18 = 20 -> base 18 = 36
36 base 19 = 1h -> base 19 = 36
36 base 20 = 1g -> base 20 = 36
36 base 21 = 1f -> base 21 = 36
36 base 22 = 1e -> base 22 = 36
36 base 23 = 1d -> base 23 = 36
36 base 24 = 1c -> base 24 = 36
36 base 25 = 1b -> base 25 = 36
36 base 26 = 1a -> base 26 = 36
36 base 27 = 19 -> base 27 = 36
36 base 28 = 18 -> base 28 = 36
36 base 29 = 17 -> base 29 = 36
36 base 30 = 16 -> base 30 = 36
36 base 31 = 15 -> base 31 = 36
36 base 32 = 14 -> base 32 = 36
36 base 33 = 13 -> base 33 = 36
36 base 34 = 12 -> base 34 = 36
36 base 35 = 11 -> base 35 = 36
36 base 36 = 10 -> base 36 = 36
</pre>
 
=={{header|LFE}}==
9,488

edits