0

I've taken this piece of code out of my bigger project, basically I want to pick a random point within the array and remember that it's been picked (by setting its value to 1) and repeat it till the whole array is filled. What's wrong with this code? Why doesn't it fill every single field?

    //initialize
    int arraysizex = 5;
    int arraysizey = 5;
    int x = 0, y = 0;
    int filledcount = 0;
    int[][] array = new int[arraysizex][arraysizey];

    //fill
    for (int i = 0; i < arraysizex * arraysizey; i++) {
        do {
            x = (int) (Math.random() * arraysizex);
            y = (int) (Math.random() * arraysizey);
            if (array[x][y] == 0) {
                array[x][y] = 1;
            //do something
            }
        } while (array[x][y] == 0);
    }

    //display
    for (int i = 0; i < arraysizey; i++) {
        System.out.println();
        for (int j = 0; j < arraysizex; j++) {
            System.out.print(array[j][i]);
            if (array[j][i] == 1) {
                filledcount++;
            }
        }
    }
    System.out.print("\n" + filledcount+"\n");

1 Answer 1

1

In the 'worst case', if it picked x = 0, y = 0 every time, your code would apply the operation to only that pixel. It'd then try arraysizex * arraysizey times but skip due to the check for being zero.

Try

   int i = 0;
   while(i < arraysizex * arraysizey) {
        x = (int) (Math.random() * arraysizex);
        y = (int) (Math.random() * arraysizey);
        if (array[x][y] == 0) {
            array[x][y] = 1;
            i++;
            //do something
        }
    }

This guarantees that you did the operation arraysizex * arraysizey times, as it only increments when you do the operation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.