GustavoA GustavoA - 1 year ago 38
TypeScript Question

Generating an array without repeats in angular 2

I'm, trying to create an array of six, and it must not have any repeating numbers from 1 to 60.

My code right now its like this:

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


It should check if the array has more then 0 elements, if it does it'll empty it.
if it's empty it'll assemble the array...
And it should not repeat numbers...
This works up to the point that I insert the repeating checker..:

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


This guy makes my code stop working.

After searching I read something about the Fisher-Yates Shuffle technique, but it doesn't seems to work for me.

I'm using angular 2, with the Ionic 2 framework.

Does someone here have come up with this already?

Answer Source

This is what my code looks now. Working!

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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download