javascript - 如何生成两次随机字符串
问题描述
function generate() {
const notations = [" U", " D", " R", " L", " F", " B"];
const switches= ["", "\'", "2"];
let array = [];
let last = '';
let random = 0;
for (let i = 0; i < 20; i++) {
do {
random = Math.floor(Math.random() * notations.length);
} while (last == notations[random])
last = notations[random];
let Item = notations[random] + switches[parseInt(Math.random()*switches.length)];
array.push(Item);
}
let scrambles = "";
for(i=0; i< 20; i++) {
scrambles += array[i];
}
document.getElementById("div").innerHTML = scrambles;
}
所以我有生成随机字符串的函数,所以输出将类似于R U' B2 R2 L F L2 B U2 B U F' L' B2 R' L D2 U' L2 R
我想生成两次随机字母,所以输出将类似于
R U' B2 R2 L F L2 B U2 B U F' L' B2 R' L D2 U' L2 R
B R' U' F' D L U2 F' R' B D U F R' L' F U2 D L R
我找到了一个解决方案,它是通过复制这样的代码
function generate() {
const notations = [" U", " D", " R", " L", " F", " B"];
const switches= ["", "\'", "2"];
let array = [];
let last = '';
let random = 0;
for (let i = 0; i < 20; i++) {
do {
random = Math.floor(Math.random() * notations.length);
} while (last == notations[random])
last = notations[random];
let Item = notations[random] + switches[parseInt(Math.random()*switches.length)];
array.push(Item);
}
let scrambles = "";
for(i=0; i< 20; i++) {
scrambles += array[i];
}
const notations2 = new Array(" U", " D", " R", " L", " F", " B");
const switches2= ["", "\'", "2"];
let array2 = [];
const last2 = '';
const random2 = 0;
for (let i = 0; i < 20; i++) {
do {
random2 = Math.floor(Math.random() * notations2.length);
} while (last == notations2[random2])
last2 = notations2[random2];
let Item2 = notations2[random2] + switches2[parseInt(Math.random()*switches2.length)];
array.push(Item2);
}
let scrambles2 = "";
for(i=0; i< 20; i++) {
scrambles2 += array[i];
}
document.getElementById("div").innerHTML = scrambles + "<br>" + scrambles2;
}
但它效率不高,有没有更快更有效的方法来做到这一点?
解决方案
您已经将代码包装在一个函数中,因此只需调用它两次(或任意多次)。
正如其他人已经建议的那样,只需返回您的scrambles
字符串generate()
,然后您就可以执行以下操作:
function generateNTimes(n) {
const scrambles = [];
for (let i = 0; i < n; i++) {
scrambles.push(generate());
}
document.getElementById("div").innerHTML = scrambles.join('<br>');
}
推荐阅读
- python - Python:提供一个字符串,打开包含文件夹名称中字符串的文件夹,然后打开/读取该文件夹中的文件
- verilog - SystemVerilog 总是@序列
- javascript - 将 CSS 代码更改为特定的 javascript 代码文件
- javascript - Formik OnSubmit 没有被触发
- javascript - 如何通过选择特定的单选按钮组来重置许多单选按钮组
- ios - 覆盖单元格中的触摸后,Swift CollectionView didSelectItemAt 不再工作
- javascript - 我在我的页面上包含了 footer.php 文件,但是引导程序正在改变我的页脚我如何在没有冲突的情况下包含我的页脚 bootstrap.css
- android - ConstraintLayout内TextView的动态点
- javascript - How can I seperate data in a single form into JSON array?
- ada - 如何为记录类型定义“+”