#moving an element through 2d array

3 messages · Page 1 of 1 (latest)

drifting owl
#
#define SIZE 9

void idk(void) {

    // Initialising array
    int random_array[SIZE][SIZE] = {};
    for (int i = 0; i < SIZE; i ++) {
        for (int j = 0; j < SIZE; j ++) {

            random_array[i][j] = 0;

        }
    }

    random_array[3][4] = 1

    for (int i = 0; i < SIZE; i ++) {
        for (int j = 0; j < SIZE; j ++) {

            // This will always be true due to the nature of 
            // whats inside 
            // Thus bringing 1 to the end of row before crashing as 
            // invalid array index will be accessed
            if (random_array[i][j] == 1) {
                
                random_array[i][j] = 0;
                random_array[i][j + 1] = 1;
            }

        }
    }

}
  1. If there are any elements == 1 in the array I need to move them across the row one by one
    I've already got if statements to make sure these don't go out of bounds, the above is just a rough example
  2. If there are two or more elements == 1 in the 2d array I need them to move in order, from left to right

The code on top won't do this one by one:
(every time func is called, all elements == 1 should move to the right by one space)
The only 'solution' I can think of is reversing the way in which the rows loop:

for (int j = 8; j >= 0; j --) {

}

but this won't be true to the second condition, it will move the elements in order of: right to left

I've been racking my brains but can't come up with a solution
anyone have any ideas?

summer vaporBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

summer vaporBOT
#

This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.