简体   繁体   English

测试数组是否彼此相反而不通过测试的方法

[英]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 我通过使用以下预定数组在这些if语句中运行它来对其进行测试

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]. [1,2,3]和[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. 请注意,当我知道反向数组不相等时,我将从方法中返回false Hence, at the end, if false isn't returned yet, the arrays have to be reversed equal, and thus, true is returned. 因此,最后,如果还没有返回false ,则必须将数组相等地反转,因此返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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