Leticia Meyer
Leticia Meyer

Reputation: 167

Generate random list of unique rows, columns javascript

How would I generate (and print individually) a list of unique column,row pairs in javascript? I have two variables set, a number of columns and a number of rows. I only want each pair to appear once, and it can't have 0s in it. Say I had 3 rows and 3 columns, I would want:

1,2
3,1
2,3
1,3
1,1
2,1
3,2
2,2
3,3

All in a random order. How would I do this?

Upvotes: 3

Views: 1439

Answers (5)

Ken Redler
Ken Redler

Reputation: 23943

Here's one way:

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" requirement:

for( var k = 0, len = answer.length; k < len; k++ ){
  console.log( answer[k] ); // or your preferred definition of "print"
}

Upvotes: 1

YoriKv
YoriKv

Reputation: 851

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 having them in an array just do print instead of "result[result.length]".

Upvotes: 0

S L
S L

Reputation: 14328

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>

Upvotes: 1

kennebec
kennebec

Reputation: 104810

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.

Upvotes: 0

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30989

You should generate an array of all of the possible coordinate pairs, use a shuffling algorithm to put them into a random order, then print them out.

Upvotes: 1

Related Questions