随机数
规则:随机出四位数,且四位数的值不相等且里面不包含0这个数字
猜数游戏
:点击跳转
方法一
const re = require('readline-sync');
let max = 9,min = 1;
let temp = [] ;//随机数
for(let i=0;i<4;i++){
temp[i] = parseInt(Math.random()*(max-min+1)+min);
for(let j=0;j<i;j++){
while(temp[i]==temp[j]|| temp[i]==0){ //挨着挨着比较判断是否重复数组和下标,或者里面的数字不能为0
j=0;
temp[i] = parseInt(Math.random()*(max-min+1)+min);
}
}
}
方法二
const re = require('readline-sync');
let max = 9,min = 1;
let temp = [] ;//随机数
let first,last; //查重,first为前往后查找,last为从后往前找
for(let i=0;i<10;i++){
let str = parseInt(Math.random()*(max-min+1)+min); //装随机数的字符串
temp.push(str); //temp为存放的四位随机数
for(let i=0;i<temp.length;){
// console.log(arr[i]);
first = temp.indexOf(temp[i]);
// console.log(temp);
last = temp.lastIndexOf(temp[i]);
// console.log(index);
if(first != last){
temp.splice(last,1);
}
else{
i++;
}
}
str = '';
if(temp.length==4){ //判断数组长度为四则跳出
break;
}
}
方法三
const re = require('readline-sync');
let max = 9999,min = 1000;
let state = true; //定义一个循环控制
let bb = [], aa; //aa为把随机数转换成字符串,bb为把字符串转换成数组
while (state) {
let str = Math.floor(Math.random() * (max - min + 1) + min);
aa = str.toString();
bb = aa.split("");
console.log(bb);
for (let i = 0; i < 4;) {
first = bb.indexOf(bb[i]);
console.log(first);
last = bb.lastIndexOf(bb[i]);
console.log(last);
if (first == last && bb[i] != 0) { //当满足每个值不相等且都不为0的时候查重完跳出。
i++;
} else {
break;
}
console.log(bb);
if (i > 3) { //判断是否查重完
state = false;
break;
}
}
str = "";
}
console.log(`输出${bb}`);
方法四
const rs = require('readline-sync');
//1、电脑生成一个4位数
//存储电脑生成的数据
let pcNum = [];
//存储随机数
let ranNum = "";
while (pcNum.length < 4) {
ranNum = parseInt(Math.random() * 9) + 1;
pcNum.includes(ranNum) ? "" : pcNum.push(ranNum);
}