Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

javascript - Convert a number to the shortest possible character string while retaining uniqueness

I have a number, say "123456", and I need to map it to a string, any string. The only constraint on the map functions are:

  • each number must map to a unique character string (this means the string can be arbitrarily long)
  • character string can only contain 0-9, a-z, A-Z

What map function would produce the shortest strings?

Solutions in JavaScript are preferred.

Note: Clearly the simplest solution is to use the original number, so make sure you solution does better than that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may want to use Base 36 or Base 62.

Base 36 would be the most compact for case-insensitive alphanumerical characters, but if you want to exploit case-sensitivity, Base 62 would be approximately 20% more compact.

For Base 36, you can easily use JavaScript's Number.toString(radix) method, as follows:

var n = 123456;
n.toString(36); // returns: "2n9c"

For Base 62, you may want to check this forum post. Basically you should be able to do the following:

Number.prototype.toBase = function (base) {
    var symbols = 
    "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
    var decimal = this;
    var conversion = "";

    if (base > symbols.length || base <= 1) {
        return false;
    }

    while (decimal >= 1) {
        conversion = symbols[(decimal - (base * Math.floor(decimal / base)))] + 
                     conversion;
        decimal = Math.floor(decimal / base);
    }

    return (base < 11) ? parseInt(conversion) : conversion;
}

var n = 123456;
n.toBase(62); // returns: "w7e"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...