要求是确定呈现字符串的最有效方法,例如,"#1a2b3c"
从"1a2b3c"
集合中随机选择
"abcdef0123456789"
或者
["a", "b", "c", "d", "e", "f", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
为了比较结果的一致性,字符串.length
应该是精确7
的,如上例所示。
确定过程结果时间的迭代次数应10000
如以下代码中使用的那样。
我们可以从两个前瞻性的例子和基准开始调查。方法的基准应包含在答复的文本中。请注意,如果可以使用更准确的基准,或者可以改进问题的文本,请在评论中提出建议。相关:能熟练使用 Javascript 的人可以简单地向我解释一下这里发生了什么。
function randColor() {
return '#' + (function co(lor) {
return (lor += [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'][Math.floor(Math.random() * 16)]) &&
(lor.length == 6) ? lor : co(lor);
})('');
}
console.time("random string recursion");
for (let i = 0; i < 10000; i++) {
randColor()
}
console.timeEnd("random string recursion");
console.time("random string regexp");
for (let i = 0; i < 10000; i++) {
"xxxxxx".replace(/x/g, function() {
return "abcdef0123456789".charAt(Math.floor(Math.random() * 16))
});
}
console.timeEnd("random string regexp");
什么是最有效的,其中效率被定义为“速度”和“存储”所需的最少资源量,以实现返回具有的.length
字符串N
?
速度和存储的效率是否会随着N
增加而降低?