如何确保两个随机数在javascript中不相同

问题描述 投票:1回答:4

我正在学习React和Javascript,我正在编写一个小应用程序,有40个不同颜色的正方形,每两秒颜色会随机改变,一切正常,但我有一个小问题。如何更改我的代码,以便如果两个数字相同,其中一个将重新生成?我试着这样使用

import React from 'react';
import ReactDom from 'react-dom';

const totalColor=40;
const Box=(props)=>{...}

class RandomColorApp extends React.Component{
    constructor(props){
        super(props);   
        const boxes = new Array(totalColor).fill().map(this.randomColor,this);
        this.state={boxes}

        setInterval(()=>{

           const randomIndex1=Math.floor(Math.random()*3)
           const randomIndex2=Math.floor(Math.random()*3)
           if(randomIndex1!==randomIndex2){
              console.log(randomIndex1,randomIndex2)
           }
        },1000);
    }

    randomColor(){...}
    render(){...}

}

RandomColorApp.defaultProps={colors:[...]}

ReactDom.render(<RandomColorApp/>,document.getElementById('app'));

但问题是,整个过程会在重新生成新数字之前延迟1秒,还有一种方法可以重构代码,所以我不必重复Math.floor(Math.random()* 3)如果我需要超过2个随机数,那就太多了,非常感谢你

下面是我的完整代码,以防它可以提供帮助

import React from 'react';
import ReactDom from 'react-dom';

const totalColor=4;
const Box=(props)=>{
    const style={
        width: '180px',
        height: '180px',
        display: 'inline-block',
        backgroundColor: props.color
    }
    return <div style={style}/>
}

class RandomColorApp extends React.Component{
    constructor(props){
        super(props);   
        const boxes = new Array(totalColor).fill().map(this.randomColor,this);
        this.state={boxes}
        setInterval(()=>{
            const boxes=this.state.boxes.slice();
            const randomIndex1= Math.floor(Math.random()*boxes.length);
            const randomIndex2= Math.floor(Math.random()*boxes.length);
            boxes[randomIndex1]=this.randomColor();
            boxes[randomIndex2]=this.randomColor();
            this.setState({boxes});
            //const randomIndex1=Math.floor(Math.random()*3)
            //const randomIndex2=Math.floor(Math.random()*3)
            //if(randomIndex1!==randomIndex2){
            //    console.log(randomIndex1,randomIndex2)
            //}
        },1000);    

    }

    randomColor(){
        let colorIndex=Math.floor(Math.random()*this.props.colors.length)
        return this.props.colors[colorIndex];
    }

    render(){
        const boxes=this.state.boxes.map((color,index)=>(
            <Box key={index} color={color}/>
        ))
        return(
            <div className='RandomColorApp'>
               {boxes}
            </div>
        );
    } 
}

RandomColorApp.defaultProps={...}

ReactDom.render(<RandomColorApp/>,document.getElementById('app'));
reactjs random setinterval
4个回答
2
投票

首先定义下面的函数,以在给定范围内生成一个不等于except值的随机数。

randomNumber  = (max, min, except) => {
    let num = Math.floor(Math.random() * (max - min +1)) + min;
    return (num === except) ? randomNumber(max, min, except) : num;
}

之后,在setInterval()方法中使用下面的代码

const randomIndex1 = randomNumber(0, totalColor, -1);
const randomIndex2 = randomNumber(0, totalColor, randomIndex1)

在这种情况下,randomIndex1永远不会等于randomIndex2


0
投票

要获取不同数字的列表,您可以使用数组并将其随机播放:

a=new Array(10).fill(1);
a=a.map((x,i)=>i);
a=a.sort(()=>{return 2*Math.random()-1});
for (let i=0;i<a.length;i++) console.log(a[i]);

-1
投票

好的,此函数将使用rangeMin,rangeMax和selectionCount,并返回包含该范围中的selectionCount唯一值的数组。它不会验证Min!= max等。这对于(rangeMax - rangeMin)的非大值是有效的,并且当selectionCount是(rangeMax - rangeMin)的非平凡部分时,它比随机选择和测试更有效。 )。

var getSelections = function( rangeMin, rangeMax, selectionCount ) {
// make array containing all values possible
var arr=Array.from({length: (rangeMax-rangeMin)+1 }, (v, k) => k+rangeMin);
arr=arr.sort(()=>{return 2*Math.random()-1}); // shuffle the array
return arr.slice( 0, selectionCount );
}

var values = getSelections( 1, 40, 2 );
console.log( "2 values from 1-40" );
console.log( values );

var morevalues = getSelections( 1, 8, 5 );
console.log( "5 values from 1-8" );
console.log( morevalues );

-2
投票

//declare an array to add the numbers
let myArr = [];

//loop through the array to add up to 6 numbers ()
while (myArr.length < 6){

//assign random number to a variable
let random = Math.floor(Math.random()* 25) + 1;

//check if the number assigned to the variable exist in myArr[]
if(myArr.indexOf(random) > -1) {
    console.log('Matching number ' + random + ', getting a new one');
    //if number exist don't push the number and go back to the head of while loop
    continue;
}

//if number doesn't exist push it to end of myArr[]
myArr.push(random);
}

console.log(myArr);
© www.soinside.com 2019 - 2024. All rights reserved.