我是JavaScript的新手,想要编写代码,它会显示0-6范围内的三个随机数。问题是,我还希望这三个数字是顺序的,例如 - 1,2,3或3,4,5等等。这是我的代码:
var location1 = 0;
var location2 = 0;
var location3 = 0;
function place_ship(){
var location1 = Math.floor(Match.random() *6);
if (location1 == 0){
var location2 = 1;
var location2 = 2;
}
else if(location1 == 6){
var location2 = 5;
var location2 = 4;
}
else{
while (var location2 != (location2 != location1 && (location2 = location1 - 1 || location2 = location1 + 1))){
var location2 = Math.floor(Math.random() *6;
}
while((location3 != location1 && location3 != location2) && (((location3 = location2 - 1 || location3 = location2 + 1)) || ((location3 = location1 + 1 || location3 = location1 - 1)))){
var location3 = Math.floor(Math.random() *6;
}
}
}
document.write(location1 + location2 + location3);
答案 0 :(得分:1)
您可以将船舶的长度和范围作为随机数的因子。结果是船的起始位置。
var shipLength = 3,
range = 6,
random = Math.floor(Math.random() * (range - shipLength + 2));
console.log(random);
答案 1 :(得分:1)
难道你不能对三个随机数进行排序吗?
alert([0,0,0].map(num=>Math.floor(Math.random()*6)).sort());
那将输出像:
1,4,6
4,5,5
如果你真的想要一个序列,你可以生成两个并将中间的一个放到中间:
var num=[0,0,0].map(num=>Math.floor(Math.random()*6)).sort();
num[1]=(num[2]-num[0])/2+num[0];
num将是
[1, 1.5, 3]
这是顺序的...
如果你想要一个距离为1的序列,你可以这样做:
[0,0,0].map(function(el,i){return this+i;},Math.floor(Math.random()*5));
结果:
[1,2,3]
[4,5,6]
[2,3,4]
答案 2 :(得分:0)
您只能随机化第一个数字,然后递增它以获得接下来的两个数字。
答案 3 :(得分:0)
您只需生成一个随机数,然后获取其后的两个数字。随机数实际上应该不大于4,这样你仍然可以显示跟随它的两个数字,永远不会超过6。
// Get the random number. Because of Math.floor, the number
// will never be 5. 4 will be the max.
var rnd = Math.floor(Math.random() * 5);
// Get the other two numbers and make a string out of them and show the result
console.log([rnd, rnd+1, rnd+2].join(","));