1

I made a command that selects a random position from a 2d array

int[][] nums= {{1,2,3},
            {2,3,4},
            {5,6,7}};

for(int i = 0; i < 5; i++) {
        int num = nums[rand.nextInt(4)][rand.nextInt(4)];
        System.out.println(num);
    }

How can I make sure that when int num selects a position for the first time, it will never be able to select it again? Making the 5 random numbers different from each other.

Hagelsnow
  • 45
  • 4
  • You could remove it from the array everytime it has been selected? – GamingFelix Nov 15 '21 at 14:21
  • 1
    BTW: `nums[rand.nextInt(4)]` could result in `nums[3]` which will cause an [ArrayIndexOutOfBoundsException](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) because your array with a length of 3 will not have any element with the index 3 (only 0, 1 and 2) – OH GOD SPIDERS Nov 15 '21 at 14:24
  • Although looking at this task I am very confused about what you're actually trying to do. Why do you need to keep it in an array inside an array? Why not just have one Array with all the number ( {1,2,3,4,5,6,7,8,9} ) ? And when you are doing this -> nums[rand.nextInt(4)][rand.nextInt(4)] you can easily get a null pointer. So you probably wanna think through this. – GamingFelix Nov 15 '21 at 14:24
  • @OHGODSPIDERS was writing the same comment just as you posted :D – GamingFelix Nov 15 '21 at 14:24

1 Answers1

1

If you need it to pick each of the numbers from your 2d table once, this will work. I created another list which describes available locations in the table. Then as we use them, removing them from the available locations list. Because you are using a 2d array I am using the point class.

required imports

import java.util.*;
import java.awt.*;
        Random rand = new Random();
        int[][] nums= {{1,2,3},
                    {4,5,6},
                    {7,8,9},
                    {10,11,12}};
        
        ArrayList<Point> availableLocations = new ArrayList<Point>();
        for(int i = 0;i<nums.length*nums[0].length ;i++) availableLocations.add( new Point(i%nums[0].length,i/nums[0].length ));
        
        for(int i = 0; i < 12; i++) {
            int randomIndex = rand.nextInt(availableLocations.size());
            Point location = availableLocations.get(randomIndex);
            
            int num = nums[location.y][location.x];
            System.out.println(num);
            
            availableLocations.remove(randomIndex);
        }

Ben C
  • 91
  • 5
  • how can I do this with a normal array as well? – Hagelsnow Nov 16 '21 at 00:30
  • You would have to replace "Point" with "Integer" and it would work on the same principal. The initialization of the availableIndexes would just be from 0 to the array size. – Ben C Nov 16 '21 at 01:16