Checking if array is symmetric

别等时光非礼了梦想. 提交于 2019-12-06 06:04:16

Complex code makes for more mistakes. Thus, simplify it. Also, look for inequalities rather than equalities; it's easier to check for one mistake than for everything to be correct.

// A = array, n = size of array, i = looking at now
private static boolean symmHelper(int[] A, int n, int i) {

    if (i > n/2)     // If we're more than halfway without returning false yet, we win
        return true;

    else if (A[i] != A[n-1-i])    // If these two don't match, we lose
        return false;

    else    // If neither of those are the case, try again
        return symmHelper(A, n, i+1);
}

If I remember my O() notation right, I think this should be O(n+1). There are other tweaks you can make to this to remove the +1, but it'll make the code run slower overall.

if(A[i] == A[n-1-i] && i < n/2 )

That line right there is the problem. Because you're using an even number > 2 of values, when it gets to this line it skips over it because at that point i = n/2, rather than being less than it. So the function skips that and continues on to return false. Change it to this and you should be fine:

if(A[i] == A[n-1-i] && i <= n/2 )

This check is useless:

if((i == n-1-i) && (A[i] == A[n-1-i] ))
    return true;   

Of course if the two indices are the same the values there will match.

Also you need to split this if in two:

if(A[i] == A[n-1-i] && i < n/2 )
    return symmHelper(A, n, i+1);

And return true if i >= n/2.

Otherwise what happens is that after i > n/2 (which means you already know your array is symmetrical), you do not go into that if and thus return false, which is wrong.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input = new Scanner(System.in);

    int N;
    int i;
    boolean sym = true;

    N=input.nextInt();
    int [] numbers = new int [N];

    for (i=0; i<N; i++){
        numbers[i]= input.nextInt();
    }
    for(i=0;i<N;i++){
        if(numbers[i]!= numbers[N-1-i]){
        sym=false;}
    }

   if(sym==true){
       System.out.println("The array is a symetrical array");
   }
   else{
       System.out.println("The array is NOT a symetrical array");
   }
}

}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input = new Scanner(System.in);

    int N;
    int i;


    N=input.nextInt();
    int [] numbers = new int [N];

    for (i=0; i<N; i++){
        numbers[i]= input.nextInt();
    }
    i=0;
    while (i<N/2&& numbers[i] == numbers [N-1-i]){i++;
    }

   if(i==N/2){
       System.out.println("The array is a symetrical array");
   }
   else{
       System.out.println("The array is NOT a symetrical array");
   }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!