Sunday, 24 December 2017

An isSym (even/odd Symmetric) array is defined to be an array in which even numbers and odd numbers appear in the same order from “both directions”. You can assume array has at least one element. See examples below:
                                                                                                                              
{2, 7, 9, 10, 11, 5, 8} is a isSym array.

Note that from left to right or right to left we have even, odd, odd, even, odd, odd, even.

{9, 8, 7, 13, 14, 17} is a isSym array.

Note that from left to right or right to left we have {odd, even, odd, odd, even, odd}.

However, {2, 7, 8, 9, 11, 13, 10} is not a isSym array.
From left to right we have {even, odd, even, odd,  odd, odd, even}.
From right to left we have {even, odd,  odd, odd, even, odd, even},
whichis not the same.

Write a function named isSym that returns 1 if its array argument is a isSym array, otherwise it returns 0.

If you are programming in Java or C#, the function signature is:
   int isSym (int [ ] a)

If you are programming in C or C++, the function signature is:

   int isSym (int a[ ], int len) where len is the number of elements in the array.

Solution :

public static int isSym(int[] a)
        {
            int rtnVal = 0;
            for (int i = 0; i < a.Length; i++)
            {
                if ((a[i] % 2 == 0 && a[a.Length - 1 - i] % 2 == 0) || (a[i] % 2 != 0 && a[a.Length - 1 - i] % 2 != 0))
                {
                    rtnVal = 1;
                }
                else
                {
                    rtnVal = 0;
                    break;
                }

            }
            return rtnVal;
        }

      Second way :

        public static int isSym(int[] a)
        {
            int rtnVal = 0;
            for (int i = 0, j = a.Length - 1; i < j; i++, j--)
            {
                if ((a[i] % 2 == 0 && a[j] % 2 == 0) || (a[i] % 2 == 1 && a[j] % 2 == 1))
                {
                    rtnVal = 1;
                }
                else
                {
                    rtnVal = 0;
                    break;
                }
            }
            return rtnVal;
        }

1 comment:

  1. // O(N) Time | O(1) Space
    static int isSym(int[] arr) {
    if (arr.length < 1)
    return 0;

    int last = arr.length - 1;
    int first = 0;

    while (first < last) {
    if (((arr[first] % 2 == 0) && (arr[last] % 2 == 0)) || ((arr[first] % 2 != 0) && (arr[last] % 2 != 0))) {

    first++;
    last--;
    } else
    return 0;
    }
    return 1;
    }

    ReplyDelete

Powered by Blogger.

Followers

Translate

Currency Converter

Exchange Rate

Featured post

Interpolation in angular 5

When we want to communicate from component class to template ,we can use interpolation which use the { { expression }} to render the bound...

Popular Posts

My Facebook Page