![](/img/trans.png)
[英]How can I generate a cryptographically secure pseudo-random number in Javascript?
[英]How do I generate pseudo random array?
我需要从字母 A、H、O、J 和数字 0-9 生成数组。 我想按照 AHOJ 的顺序将字母生成到新数组中。 单个字符可以出现在新数组中的其他位置,但始终以 AHOJ 顺序出现,并且它们不需要相互跟随。 新数组的剩余索引将用数字填充。 示例 - A123H85O2J3、AHOJ9854273、012AH851OJ3 等。 AHOJ 的顺序不能在新数组中随机化。 我有这段代码,但可能完全错误。 它仅在满足等于 7 的条件时按预期工作。
let letters = ['A','H','O','J'];
let newArray =new Array(11);
let lastIndex = 10;
for (let i = 0; i < letters.length; i++) {
newIndex = Math.floor(Math.random() * lastIndex);
console.log(newIndex);
if (newIndex == 7) {
for (let j = 0; j < letters.length; j++) {
newArray.splice(j + 7,1,letters[j]);
}
for ( let k = 0; k < 7; k++) {
newArray.splice(k,1,Math.floor(Math.random() * 10).toString());
}
break;
}
else if (newIndex > 7) {
lastIndex = Math.floor(Math.random() * 6);
newArray.splice(lastIndex,1,letters[i]);
}
else {
newArray.splice(newIndex,1,letters[i]);
}
console.log(letters[i]);
}
console.log(newArray);
它可以简化为一个循环:
let letters = ['A','H','O','J']; for (let l = 5; l < 12; l++) // for random indexes from 4 to 11 { let position = Math.floor(Math.random() * l); let digit = Math.floor(Math.random() * 10); letters.splice(position, 0, digit); } console.log( letters.join(''), letters.length );
for (let i = 0; i < 100; i += 1) { console.log(generate('AHOJ', 11)) } function generate(word, length) { // create array [0, 1, 2, ..., length - 1] const indexes = [...Array(length).keys()] // get unique random indexes for each character of the word const reserved = [...word].map(() => { // random index of indexes array const index = Math.floor(Math.random() * indexes.length) // remove the number at index from indexes array const res = indexes.splice(index, 1) // return removed number return res[0] }) const result = [] for (let i = 0, w = 0; i < length; i += 1) { // if index is reserved, push a letter from word if (reserved.includes(i)) { result.push(word[w]) w += 1 // push random digit otherwise } else { result.push(Math.floor(Math.random() * 9)) } } return result.join('') }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.