我在这里整理了问题的 jsfiddle:https://jsfiddle.net/sd1x3am3/5/
基本上,我构建了一个名为 $.generateSerial
的扩展,它有 3 个参数。第一个参数是公式,第二个参数是允许的字符,第三个参数是不包含在返回值中的序列。基本上,该扩展允许您生成一个唯一的随机序列,该序列不是第三个参数中的序列,也不是每次 $.
在 output
变量中返回的序列。 generateSerialfor
循环中被调用。
出于某种原因,当i = 146
时,$.generateSerial
在循环内返回""
,但应该有更多值返回,因此它不应返回 ""
。
公式为XXXX-XXXX-XXXX-XXXX
,允许的字符为:ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
,这意味着这些字符中的任何一个都可以替换任何X
个字符。但返回的结果应该超过 145/146 个,这还不包括 公式
中的currSerials
数组中的内容。应该可以生成更多的连续剧。
但我不明白为什么它没有生成所有可能的序列并停止......
$.extend({
generateSerial: function(formula, chrs, checks) {
var formula = formula && formula != "" ? formula : 'XXXXX-XXXXX-XXXXX-XXXXX-XXXXX', // Default Formula to use, should change to what's most commonly used!
chrs = chrs && chrs != "" ? chrs : "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", // Default characters to randomize, if not defined!
len = (formula.match(/X/ig) || []).length,
oStatic = formula.match(/[^X]+/ig) || [],
indices = [],
lenChecks = checks.length || 0,
rand;
// Let's first find out if it's possible to create another random serial from params
// Should put the formula below through a stress test here to be sure it works!
var possible = (len * chrs.length) - lenChecks;
// return empty string if not possible!
if (possible <= 0)
return '';
var currIndex = 0;
// Getting all indices here of all strings that are not X or x
for (var o = 0; o < oStatic.length; o++) {
currIndex = formula.indexOf(oStatic[o], currIndex);
indices.push(currIndex);
currIndex = currIndex + oStatic[o].length; // set the position to start at for next loop! incrementing...
}
do {
rand = Array(len).join().split(',').map(function() {
return chrs.charAt(Math.floor(Math.random() * chrs.length));
}).join('');
// Rebuild with indices, if exists!
if (indices && indices.length > 0) {
for (var x = 0; x < indices.length; x++)
rand = rand.insert(indices[x], oStatic[x]);
}
} while (checks && $.inArray(rand, checks) !== -1);
return rand;
}
});
有人可以帮我解决这个问题吗?扩展中我的 possible
变量是否有问题?是不是不对?
甚至在没有 currSerials
数组的情况下尝试过,它最初是空的,只生成 576 个序列,然后它说它无法再生成。您可以在这里看到它:https://jsfiddle.net/sd1x3am3/8/
var currSerials = [];
for (var i = 0; i < 2000; i++) {
var output = $.generateSerial('XXXX-XXXX-XXXX-XXXX', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', currSerials);
$(".serials").append($("<p />").text((i+1) + '. ' + output));
if (output != "")
currSerials.push(output);
else
{
alert('Can not generate anymore serials, stopped at ' + i + '.');
break;
}
}
最佳答案
从讨论中,我发现您并不追求排列,因此您应该使用以下内容来查找 total possible items ,
var possible=Math.pow(chrs.length,len) - lenChecks
关于javascript - 内置 jQuery 扩展,但不允许最大返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36526467/