0
点赞
收藏
分享

微信扫一扫

猜数游戏获取随机数的三种方法

米小格儿 2022-01-31 阅读 32

随机数

规则:随机出四位数,且四位数的值不相等且里面不包含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]){
             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;   
    }    
}

方法三

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}`);
举报

相关推荐

0 条评论