Search code examples
javascriptarraysrandomdouble

How to shuffle 2D Array in JavaScript using random function and is it possible to populate 2D array with 3 specific double values like 0 , 0.5 , 1


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!


Solution

  • 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 ^