2017-12-17 33 views
1

나는 React와 Javascript를 배우고 있으며, 다른 색상과 40 개의 사각형을 가진 작은 응용 프로그램을 작성하고 있으며 매 2 초마다 2 개의 색상이 무작위로 바뀔 것입니다. 사소한 문제가 하나 있습니다. 두 개의 숫자가 같으면 다시 생성 될 수 있도록 코드를 어떻게 바꿀 수 있습니까? 내가 사용하려고하는 경우 등이두 개의 난수가 자바 스크립트에서 동일하지 않다는 것을 확인하는 방법

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')); 
+0

왜 생성자에서 setInterval을()를 추가 하시겠습니까? –

+0

내가 어디에 넣어 줄 것을 제안해야합니까? 답변을 얻은 후에 모든 것이 자동으로 실행되고 onSubmit 양식은 물론 onClick 함수도 제공됩니다. – Nhat

+0

알립니다. 답변을 추가했습니다. 희망을 당신의 질문을 해결할 것입니다. –

답변

0
도움을 줄 수있다 아래

을 verymuch 감사의 경우 너무 많은

고유 번호 목록을 얻으려면 배열을 사용하여 순서 섞기 :

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]);

+0

죄송합니다. 주제가 명확하지 않았습니다. 나는 40 가지 색상의 배열을 가지고 배열에서 2 개의 난수를 추출하려고합니다. 그러나 2 개의 난수는 달라야합니다. 혼란스러워서 미안하다. 나는 아직도 배우고있다. 배열의 길이로부터 두 개의 임의의 숫자를 얻을 수 있지만 언젠가 두 개의 임의의 숫자가 동일한 숫자를 생성합니다. – Nhat

2

첫번째는 except 값과 같지 않은 소정의 범위의 난수를 생성하는 함수 아래 정의한다. 이 경우 귀하의 setInterval을 코드 ​​아래에 그 사용 후

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

() 메소드

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

, randomIndex1randomIndex2

+1

내일 첫 번째 것을 확인해 보겠습니다. 많이 고마워. 또한 리팩토링하는 방법을 알고 있습니까? 같은 시간에 색상이 바뀌는 10-20 개의 임의 숫자를 원한다면 – Nhat

+0

min == max == 인 경우 어떻게됩니까? 이 경우 @JonMarkPerry가 무한 루프가됩니다. –

+0

그러나이 시나리오에서는 모든 시나리오에 대해 min! = max라고 가정합니다. –

-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);

+0

답변은 전적으로 코드로 구성되어서는 안되며 코드가하는 역할과 왜 문제가 해결되는지 설명하십시오. 자세한 내용은 [답변]을 읽어주십시오. –

-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);