生成不重复的角2

生成不重复的角2

问题描述:

我是一个阵列,努力创造6组,并且不能有1任何重复数为60生成不重复的角2

我的代码,现在它是这样的:

jogar(){   
    if(this.random.length != 0){ 
     this.random=[]; 
     }else{ 
      for(var u=0; u<6; u++){ 
      this.y = Math.ceil(Math.random()*59+1); 
       for (var r of this.random){ 
        if(r != this.y){ 
         this.random.push(this.y); 
        }; 
       };                
      }; 
      this.random.sort(function(a, b){return a-b}); 
      return this.random; 
     };         
}; 

它应该检查数组是否有多于0个元素,如果它确实会清空它。 如果它是空的,它会组装阵列... ,它不应该重复数... 这个工作到我插入重复检查点..:

   for(var r of this.random) 
       if(r != this.y){ 
        this.random.push(this.y); 
       }; 

这家伙让我代码停止工作。

搜索后我读了一些关于Fisher-Yates Shuffle技术的内容,但它似乎不适用于我。

我正在使用角2,与Ionic 2框架。

这里有人已经想出了这件事吗?

+0

哪里可以解决这个问题? – sebaferreras

+0

是的,但不使用你的方法,我会发布我的答案。 – GustavoA

这是我现在的代码如下。加工!

jogar(){  
    this.final = []; 
    this.numeros = []; 
    for(var i=0;this.final.length<6;i++){ 
     this.final = this.numberSelect.map(Number).concat(this.numeros);   
     var novoNumero=Math.floor((Math.random()*59)+1);    
     var verificacao=this.confereSeArrayContemItem(this.final,novoNumero);  
     if(verificacao!==1){ 
      this.numeros.push(novoNumero);     
     }else{ 
      i--; 
     } 
     this.final.sort(function(a,b){return a-b});  
    } 
    console.log(this.final.sort(function(a,b){return a-b})); 
} 

confereSeArrayContemItem(array, item){ 
    var resultado = 0; 
    for(var i=0;i<array.length;i++){ 
     if(array[i]===item){ 
      resultado =1; 
     } 
    } 
    return resultado; 
} 

那句话是错误的,因为

for(var r of this.random) 
    if(r != this.y){ 
    this.random.push(this.y); 
}; 

将尝试在this.y数推到随机阵列,每个从随机排列的号码是从this.y许多不同的时间。

正如你可以在这个working plunker看到,你可以实现你在找什么用下面的代码:

import { Component } from '@angular/core'; 

@Component({...}) 
export class HomePage { 

    random: Array<number> = []; 


    public jogar(): Array<number> {   
    if(this.random.length != 0) { 
     this.random=[]; 
    } 

    while (this.random.length < 6) { // <- Use while instead of for 
     let randomNumber = this.getRandomNumber(); // Get a random number 
     if(!this.wasAlreadyAdded(randomNumber)) { 
     this.random.push(randomNumber); // Add it if it doesn't exist in the array 
     } 
    } 

    this.random.sort(function(a, b){return a-b}); 
    return this.random; 

    } 

    private getRandomNumber(): number { 
    return Math.ceil(Math.random()*59+1); 
    } 

    private wasAlreadyAdded(randomNumber: number): number { 
    return this.random.indexOf(randomNumber) !== -1; 
    } 

}