Arrays 在角度2中生成无重复的阵列
我正在尝试创建一个6的数组,它不能有任何从1到60的重复数字 我的代码现在是这样的:Arrays 在角度2中生成无重复的阵列,arrays,angular,typescript,ionic2,Arrays,Angular,Typescript,Ionic2,我正在尝试创建一个6的数组,它不能有任何从1到60的重复数字 我的代码现在是这样的: 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
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;
};
};
这家伙让我的代码停止工作
搜索之后,我读了一些关于费舍尔·耶茨洗牌技术的文章,但它似乎对我不起作用
我用的是angular 2,离子2框架
这里有人已经想到这个了吗?那句话是错误的,因为
for(var r of this.random)
if(r != this.y){
this.random.push(this.y);
};
将尝试将this.y
数字推送到随机数组,每次随机数组中的数字与this.y
数字不同时
正如您在本文中所看到的,您可以通过以下代码实现所需的功能:
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;
}
}
从'@angular/core'导入{Component};
@组件({…})
导出类主页{
随机:数组=[];
public jogar():数组{
如果(this.random.length!=0){
这个.random=[];
}
而(this.random.length<6){/这就是我的代码现在的样子。正在工作
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;
}
jogar(){
this.final=[];
this.numeros=[];
对于(var i=0;this.final.lengthWhere)您能解决这个问题吗?是的,但不使用您的方法,我将发布我的答案。
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;
}