Create a random list of unique rows, javascript columns

How do I generate (and print separately) a list of unique columns, row pairs in javascript? I have two variables, the number of columns and several rows. I want each pair to appear once, and there cannot be 0s in it. Say I had 3 rows and 3 columns, I would like:

1,2
3,1
2,3
1.3
1,1
2.1
3.2
2.2
3.3

Everything is random. How should I do it?

+3
source share
5 answers

Not my algorithm though

<script type="text/javascript">

        var array = Array();

        var i,j;

        for(i=1; i <= 3; i++){
            for(j=1; j<=3; j++){    
                array.push(j+', '+i);
            }
        }
        var newarr = shuffle(array);
        console.log(newarr);
        document.write(newarr);

    function shuffle(array)
    { //v1.0
        for(var j, x, i = array.length; i; j = parseInt(Math.random() * i), x = array[--i], array[i] = array[j], array[j] = x);
        return array;
    };
</script>
+1
source

You must generate an array of all possible coordinate pairs, use the shuffle algorithm to place them in random order, then print them out.

+1

:

var answer = (function(width,height) {
  var result = [];
  for (var i = 1; i <= width; i++) {
    for (var j = 1; j <= height; j++) {
      result.push([i, j]);
    }
  }
  return result.sort(function(a, b) {
    return 0.5 - Math.random();
  });
}(3,3)); // enter width/height here, 1-indexed

Edit: Forgot the print request:

for( var k = 0, len = answer.length; k < len; k++ ){
  console.log( answer[k] ); // or your preferred definition of "print"
}
+1
source
Array.prototype.shuffle= function(force){
    var i, temp, L= this.length,
    A= force? this: this.concat();
    while(--L){
        i= Math.floor(Math.random()*L);
        temp= A[i];
        A[i]= A[L];
        A[L]= temp;
    }
    return A;
}

The purpose of the (optional) parameter is to shuffle the array itself. By default, the array is not shuffled, but a shuffled copy is returned.

0
source

This should work:

// New Array
a = [];
// 3 rows, 3 columns
c = 3;
r = 3;
// fill array with every unique possibility
for( var i = 1; i <= r; i++ ) {
  for( var j = 1; j <= c; j++ ) {
    a[a.length] = "" + i + "," + j;
  }
}
// random pick into another array
result = [];
a_len = a.length;
for( var i = 0; i < a_len; i++ ) {
  result[result.length] = a.splice(Math.floor(Math.random()*a.length), 1)[0];
}

If you just want to print the results instead of just printing them in the array instead of "result [result.length]".

0
source

Source: https://habr.com/ru/post/1795399/


All Articles