Custom radix columns (+special characters) [closed]

强颜欢笑 提交于 2019-12-10 12:37:45

问题


Currently I'm using this code to convert a number into an base36-string:

let number = 300293338
let base36 = String(number, radix: 36);
print(base36) // 4ysbtm

But I'm wondering how it's possible to generate my own alphabet with a kind of a Base10 to AnyBase conversion using Swift.

An example of the alphabet could be something like this:

["$", "%", "&", "/", "(", "9", "=", "?", "+", "#", "-", ".", ">", "<", "*", "!", ...]

It maybe could look like this:

let number = 300293338
let base36 = mycoolfunction(number)
print(base36) // "$%//+#="

回答1:


How about using the basic base 10 to any base conversion, modified for custom digits:

func numberToCustomRadix(_ number: Int, alphabet: String) -> String {
    let base = alphabet.count
    var number = number
    var result = ""
    repeat {
        let idx = alphabet.index(alphabet.startIndex, offsetBy: number % base)
        result = [alphabet[idx]] + result
        number /= base
    } while number > 0
    return result
}

numberToCustomRadix(3, alphabet: "012") // 10
numberToCustomRadix(4, alphabet: "abc") // bb
numberToCustomRadix(5, alphabet: "%#9") // #9

Note that the problem with a custom alphabet is the fact that it's hard to guarantee at compile time that the alphabet contains distinct characters. E.g. an "aaabbbccc" alphabet will generate all kind of conversion problems.




来源:https://stackoverflow.com/questions/48724055/custom-radix-columns-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!