LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   javaScript - multidimensional array (with some restrictions) (https://www.linuxquestions.org/questions/programming-9/javascript-multidimensional-array-with-some-restrictions-4175561874/)

sycamorex 12-19-2015 11:49 PM

javaScript - multidimensional array (with some restrictions)
 
Hi all,

I have created a multidimensional array in JavaScript and filled it with some random integers from 0 to 4.
That was an easy part:

Code:

a = new Array();

                                                                                                          // Array size                                                       
ms = [30, 20];

for (i=0;i<ms[1];i++) {
    a[i] = new Array();
    for (j=0;j<ms[0];j++) {
        a[i][j] = Math.floor(Math.random() * 5);
    }
}


console.log(a);

Now I've got the following questions. I'm not sure how to start:

a) limit the number of occurrences of certain number: I need to have only 4 instances of number 3 and 1 instance of number 2.
b) all instances of number 1 must be adjacent (creating a path in a maze)

It is going to be a randomly generated maze map with 0 - walls, 1 - paths, 2 - altars, 3 - doors,

Is it doable in a relatively simple way?

firstfire 12-20-2015 08:43 AM

Hi.

Maybe keep generating random numbers until all restrictions for a given cell are satisfied? Say, assign 1 only if there is already one adjacent 1 or check counter of 3's if 3 was generated. To avoid possible bias in distribution of numbers due to ordered filling of the array (row-by-row) one may also take indices from shuffled array of indices, something like (untested)
Code:

var _ = require('underscore'); // in Nodejs

var ms = [2, 5];
var idx = _.shuffle(_.range(ms[0]*ms[1])); // You may use for-loop to gen. array and random indexes+splice to pick numbers.
var i, j, n, nums;
var count_3=0, count_2=0;

for(var k=0, len=idx.length; k<len; k++) {
  i = Math.floor( idx[k]/ms[1] );
  j = idx[k] % ms[1];
  console.log("IDX", k, i, j);
  nums = _.shuffle([0, 1, 2, 3]);
  for(var l=0; l<4; i++) {
    n = nums[l];
    (n==3) && (count_3++);
    (n==2) && (count_2++);
    // check all restrictions for number `num` in cell (i, j) here, save to array and break if satisfied
    .....
  }
}


ntubski 12-20-2015 10:43 AM

Quote:

Originally Posted by sycamorex (Post 5466585)
It is going to be a randomly generated maze map with 0 - walls, 1 - paths, 2 - altars, 3 - doors,

Is it doable in a relatively simple way?

If you want a walkable maze, you can't just throw random numbers into an array. See for example http://pcg.wikidot.com/pcg-algorithm:dungeon-generation

sycamorex 12-20-2015 02:34 PM

Thank you guys for your input. In the meantime, I think I found a working example of what I need.

http://jsfiddle.net/bigbadwaffle/YeazH/


All times are GMT -5. The time now is 06:48 AM.