简体   繁体   中英

Method to test if arrays are the reverse of each other not passing test

I'm supposed to make a method to test if two arrays have the same values in reverse order.

public static boolean areReversed (int [] t , int [] q)
{
  boolean identical = false;
  if(t.length != q.length){ identical = false;}
  else{
  for(int x = (t.length -1) , y = 0; -1 < x; x-- , y++)
  {
     if(t[y] == q[x])
     {
      identical = true;

     }

  }
}
  return identical; 

}

I test it by running it through these if statements with the following pre-determined arrays

int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    int[] b = {0, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    int[] c = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int[] d = {9, 8, 7, 6, 5, 4, 3, 2, 1};
    int[] e = {1, 2, 3, 4, 5, 4, 3, 2, 1};
    int[] f = {1, 2, 3, 4, 4, 3, 2, 1};
    int[] g = {1, 3, 5, 7, 9, 0, 2, 4, 6, 8};
    int[] h = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    int[] i = {1, 1, 3, 3, 5, 5, 7, 7, 9, 9};

    //test for areReversed, uncomment the next two lines to test your method
    if(areReversed(a, b) && !areReversed(a, g) && !areReversed(a, c)) System.out.println("Basic areReversed method test PASSED");
    else System.out.println("Basic areReversed method test FAILED");

My method doesn't pass the test, am I making an oversight somewhere in my code?

Yes, you are indexing to two arrays in the same order. You are essentially checking that they are equal, not that they are the reverse of each other.

Also, remember that a function can return at any point Think about this and think about how you could make your function more efficient in a case where the arrays look like this:

[1,2,3] and [4,2,4].

How many comparisons do you actually need to make before you can tell us the arrays are not the same.

This is what you should do:

public static boolean areReversed (int [] t , int [] q)
{
  if(t.length != q.length) return false;
  for(int x = (t.length -1) , y = 0; -1 < x; x-- , y++)
  {
     if(t[y] != q[x]) return false;
  }
  return true; 
}

Note that I'm returning false from the method as and when it is known that the reversed arrays are unequal. Hence, at the end, if false isn't returned yet, the arrays have to be reversed equal, and thus, true is returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM