Doren Doren - 6 months ago 30
Java Question

Flip Array part

i want to flip a Array from 0 to index n, and all flipped Elements should get reversed.

if i Call Flip(A, 2)
my wish result is

true, false, true , true, false


(the Array part selcted from 0 to 2 backwards , and the value inverted)

public class test{

public static void main(String[] args) {
Boolean[] A = { false, true, false, true, false };

A = Flip(A, 4);

print(A);
}

public static Boolean[] Flip(Boolean[] A, int n) {
Boolean[] Atemp = A;

for (int i = 0; i <= n; i++) {
Atemp[i] = !A[n - i];
}

return Atemp;
}

public static void print(Boolean[] A) {
for (Boolean b : A)
System.out.println("" + b);

System.out.println();
}

}


but the result i get is

true,false,false,true,false


is ther an Error in my Code(most likely)
or is there a Java specific Fault involved.

Thanks for your Help

Answer

There are several problems with your code:

  1. it doesn't only flip the array, but as well reverses it. Guess that's just a mistake in the specification.
  2. your code attempts to reverse the array in-place, but isn't implemented incorrectly.
  3. your code has n as inclusive upper-bound, but the specification states it should be exclusive.

As for point 1: assuming that's really just an issue with the specification, we can simply ignore that point.

Point 3: just change the for-loop from

for (int i = 0; i <= n; i++)

to

for (int i = 0; i < n; i++)

to get the desired behavior.

Point 2:
Here we can take several approaches: actually implement in-place inversion:

public static Boolean[] Flip(Boolean[] A, int n) {
    for (int i = 0; i < n / 2.0; i++) {
        boolean tmp = A[i];
        A[i] = !A[n - i - 1];
        A[n - i - 1] = !tmp;
    }

    return A;
}

Or create a copy of the array and invert inside that copy:

public static Boolean[] Flip(Boolean[] A, int n) {
    Boolean[] Atemp = Arrays.copyOf(A , A.length);

    for (int i = 0; i < n; i++) {
        Atemp[i] = !A[n - i - 1];
    }

    return Atemp;
}

And there's no need to use Boolean[]. Just use the primitive type boolean[].

A hint for the future: this can actually be debugged either using a debugger, or if you prefer by simply altering the code to reverse a int[] instead of a boolean[]. Just use {1, 2, 3, 4, 5, ...} it becomes pretty obvious what happens to the single elements.