Skip to content

Commit

Permalink
Add Kotlin version
Browse files Browse the repository at this point in the history
  • Loading branch information
imGurpreetSK authored and ocram committed Oct 2, 2018
1 parent 2fcc0e0 commit a16cde2
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions Kotlin/ShortURL.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* ShortURL (https://github.com/delight-im/ShortURL)
* Copyright (c) delight.im (https://www.delight.im/)
* Licensed under the MIT License (https://opensource.org/licenses/MIT)
*/

/**
* ShortURL: Bijective conversion between natural numbers (IDs) and short strings
*
* ShortURL.encode() takes an ID and turns it into a short string
* ShortURL.decode() takes a short string and turns it into an ID
*
* Features:
* + large alphabet (51 chars) and thus very short resulting strings
* + proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u')
* + unambiguous (removed 'I', 'l', '1', 'O' and '0')
*
* Example output:
* 123456789 <=> pgK8p
*/
object ShortURL {

private val ALPHABET = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_"
private val BASE = ALPHABET.length

fun encode(num: Int): String {
var number = num
val stringBuilder = StringBuilder()
while (number > 0) {
stringBuilder.insert(0, ALPHABET[number % BASE])
number /= BASE
}

return stringBuilder.toString()
}

fun decode(string: String): Int {
var number = 0
for (i in 0 until string.length) {
number = number * BASE + ALPHABET.indexOf(string[i])
}

return number
}

}

0 comments on commit a16cde2

Please sign in to comment.