[Solved] In a 2-dimensional array of integers, how can we place a new integer at a completly random spot in the 2-d array?


static void placeRandomly2D(int[][] arr, int limit) {
// generates value [0...limit) half-interval and places it into the 2D array arr
//    at random position; limit must be positive
    Random rand = new Random();
    int value = rand.nextInt(limit);
    int pos1 = rand.nextInt(arr.length);
    int pos2 = rand.nextInt(arr[pos1].length);
    arr[pos1][pos2] = value;
}

And, just in case, version for 1-dimensional array:

static void placeRandomly1D(int[] arr, int limit) {
// generates value [0...limit) half-interval and places it into the 1D array arr
//    at random position; limit must be positive
    Random rand = new Random();
    int value = rand.nextInt(limit);
    int pos = rand.nextInt(arr.length);
    arr[pos] = value;
}

3

solved In a 2-dimensional array of integers, how can we place a new integer at a completly random spot in the 2-d array?