$8.3

how to check is array symmetrical or not?

Ask a question+
4

for exapmle this Array

const arr = [55, 1, 'a', NaN, -0, 48, 0, NaN, 'a', 1, 55];
add comment

2 Answers

5
const equal = (a, b) => (a === b && a === 0) ? true : Object.is(a, b);
const simetricArr = (_arr) => {
    for(let i = 0; i <= _arr.length / 2; i++) {
        if (!equal(arr[i], arr[arr.length - i -1])) {
            return false;
        }
    }
    return true;
}
console.log(simetricArr(arr));
add comment
0

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.

Azniv Saroyan 150
add comment

Your Answer