从序列中为随机数查找值的简单算法?

时间:2015-03-21 05:01:35

标签: java javascript algorithm

我想为序列创建一个通用算法(我不在任何地方存储序列)..如果

1 = A

2 = B

3 = C

26 = Z

27 = AA

28 = AB

29 = AC

30 = AD

获取任意随机数值的代码应该是什么?例如333

2 个答案:

答案 0 :(得分:0)

这里有一个很好的例子HERE ..

function getCharCode(displayNumber){
    var ordA = 'A'.charCodeAt(0);
    var ordZ = 'Z'.charCodeAt(0);
    var len = ordZ - ordA + 1;

    var returnSequence = "";
    while(displayNumber >= 0) {
        returnSequence = String.fromCharCode(displayNumber % len + ordA) + returnSequence; // (displayNumber % 26 + 65) +""
        displayNumber = Math.floor(displayNumber / len) - 1; //(displayNumber / 26) - 1
    }
    return returnSequence;
}

或者我将其修改为..

function getCharCode(displayNumber){
    var returnSequence = "";
    while(displayNumber >= 0) {
        returnSequence = String.fromCharCode(displayNumber % 26 + 65) + returnSequence;
        displayNumber = Math.floor(displayNumber / 26) - 1;
    }
    return returnSequence;
}

答案 1 :(得分:0)

尝试

var arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")
, i = -1
, n = -1
, len = 0
, max = arr.length + arr.length * arr.length
, res = {};

do {
  if (n === arr.length -1) {
    n = -1;
    ++i;
  };
  if (len < arr.length * 2 - 1) {
    res[++len] = len < arr.length + 1 ? arr[++n] : res[1] + arr[++n];
  } else {
    res[++len] = arr[i] + arr[++n]
  };
} while (len < max);

console.log("333:" + res[333], res);