Home > Enterprise >  How to shuffle 2D Array in JavaScript using random function and is it possible to populate 2D array
How to shuffle 2D Array in JavaScript using random function and is it possible to populate 2D array

Time:11-28

Lets say this is the array i want to shuffle randomly, what would be the most efficient way to do so? How could i populate this kind of array with three specific values (0, 0.5, 1) but in random order each time i start the program?

Can i use something like " a[i][j] = rand.nextDouble() " ?

Double a[][] = {{0, 1, 0.5, 0.5, 0.5}, {0, 1, 0, 1, 1}, {0.5, 1, 0.5, 0.5, 0}, {0, 0.5, 0, 0.5, 0}, {1, 1, 0.5, 1, 1}, {0, 0, 0, 0.5, 0.5}, {0, 0.5, 0, 0, 1}};

I tried generating this array witha[i][j] = (rand..nextDouble() * (1-0)) 0.5;but it turns out values like 1.2 and 0.3 etc, is there a way to increase random values by 0.5 only? so that they can be in range from 0-1?

Thank you!

CodePudding user response:

Generate an integer between 0 and 2 (inclusive) – 0 and 3 (exclusive), then divide by 2. This will give you 0.5 steps (1/2 = 0.5).

To initialize your array, create a function to return a random array of 5 values. Then call this method 5 times and assign it to each index of your top-level array.

CodePudding user response:

Rather than trying to generate a new random number you can add the required numbers into an array and generate a random index to choose the numbers.

import java.lang.Math;

class MainRun {
    public static void main(String[] args) {
        double arr[][] = new double[5][7];
        double num[] = { 0, 0.5, 1, 1.5 };

        for (int i = 0; i < 5; i  ) {
            for (int j = 0; j < 7; j  ) {
                int rand = (int) (Math.floor(Math.random() * 4));
                arr[i][j] = num[rand];
            }
        }
    }
}

Output :

0.0 0.0 0.0 0.5 1.5 0.5 0.0 
0.0 0.5 0.5 1.5 0.5 1.5 1.0
1.5 0.5 1.5 1.0 1.5 0.0 1.0
1.0 0.0 1.5 0.5 0.0 1.0 1.5 
0.5 1.5 0.0 1.5 0.5 0.0 0.0 

Printing the 2d Array ^

  • Related