如果javascript中的值相同,如何再次使用math.random获得不同的值

时间:2018-08-18 23:31:19

标签: javascript math random

我试图从以前的math.random值中获得一个不同的值,因此当数字写入文档时,如果它们相同,则math.random将生成另一个不相同的数字。可能需要继续生成直到值不同为止。

function rands() {
  return Math.floor(Math.random() * 20) + 1;
}

var rand1 = rands();
var rand2 = rands();
var rand3 = rands();
var rand4 = rands();
var rand = [];

function myFunction() {
  document.getElementById("random1").value = rand1;
  document.getElementById("random2").value = rand2;
  document.getElementById("random3").value = rand3;
  document.getElementById("random4").value = rand4;

  if(rand1 == rand2 || rand1==rand3 || rand1==rand4 || rand2 == rand3 || rand2 == rand4 || rand3==rand4){
  console.log("Duplicate");

    }
}

myFunction()

2 个答案:

答案 0 :(得分:4)

您可以重写#include <iostream> #include <cmath> #include <stdlib.h> #include <ctime> using namespace std; int get_n(); float** create_matrix(int &n, float** m); int main (int argc, char *argv[]) { int n; n=get_n(); float** m = new float*[n]; for ( int r = 0 ; r < n ; ++r ) { m[r] = new float[n]; } m=create_matrix(n, m); for ( int r = 0 ; r < n ; ++r ) { if ( NULL != m[r] ) { for ( int c = 0 ; c < n ; ++c ) { cout << m[r][c] <<"\t"; } cout << endl; delete [] m[r]; m[r] = NULL; } } m = NULL; return 0; } int get_n(){ int n; do { cout<<"Write N between 3 and 10: "; cin>>n; } while (n<11&&n>2); cout<<endl; return n; } float** create_matrix(int &n, float** m){ int maxi; srand(time(NULL)); cout<<"Insert max term: "; cin>>maxi; for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ float aux=0; aux=1+rand()%((1+maxi)-1); m[i][j]=aux; } } return m; } 函数以查找已使用的值:

rands

答案 1 :(得分:0)

如果要保证唯一性,可以从数组中拼接随机索引。发生冲突时,这将节省重复调用该函数的精力:

function rand_maker(length) {
    let arr = Array.from({length: length}, (_, i) => i+1)
    return () => {
        let index = Math.floor(Math.random() * arr.length)
        return arr.splice(index, 1)[0];
     }
}
let rands = rand_maker(20)
console.log(rands())
console.log(rands())
console.log(rands())
console.log(rands())

一旦您不能再在该范围内生成随机数,它将返回未定义的值。