0

I am working on an assignment in which I must fill a two dimensional array row by row. If the row's index value is even (0, 2, 4, etc..) the row must fill from right to left. If the row's index value is uneven (1, 3, 5, etc...), then it must fill from left to right. What condition should I put in my if statement in order for the filling of rows to alternate in this way?

Thanks!

Gabbie
  • 31
  • 1
  • 9

3 Answers3

3

You need to use the modulo or remainder operation. Suppose i is an uneven number, therefore i%2 will evaluate to 1. For even numbers i%2 will result in 0. As pointed out in the comment, use the condition if (row_index % 2 == 0) {*do right to left thing*} else {do right to left thing}.

2

As the user with the weird name that i have no idea how to reference (sorry, feel free to edit your name in here) pointed out, i%2==0 should solve the problem.

The % (modulo) operator returns the remainder of the integer division, so if the row number is even you can divide it by 2 and have no remainder (i%2==0)

int[][] toBeFilled = new int[width][height];
for(int i=0;i<width;i++) {
    if(i%2==0)
        //Fill toBeFilled[i] from Right to Left
    else
        //Fill toBeFilled[i] from from Left to Right
}
7H3_H4CK3R
  • 133
  • 8
0

Here's a code sample that may help. Note that this is C# (I'm not sitting in front of a Java compiler right now) so there are some very minor syntax differences but it should still be pretty readable.

    private static int[][] BuildArrays()
    {
        Random random = new Random();

        // Whatever size you want
        int[][] array = new int[random.Next(1, 100)][];

        for (int i = 0; i < array.Length; i++)
        {
            // Make an array of whatever size you want
            array[i] = new int[random.Next(1, 50)];

            // % is the modulo operator
            // Basically, this means "remainder when the index is divided by 2"
            // By definition, even numbers are evenly divisible by 2 and odd numbers aren't
            if (i % 2 == 0)
            {
                // Even - we fill right to left
                for (int j = array[i].Length - 1; j >= 0; j--)
                {
                    // Enter whatever you want
                    array[i][j] = random.Next();
                }
            }
            else
            {
                // Odd - we fill left to right
                for (int j = 0; j < array[i].Length; j++)
                {
                    array[i][j] = random.Next();
                }
            }
        }

        return array;
    }