Sunday, 24 December 2017

Question :
An integer array is said to be evenSpaced, if the difference between the largest value and the smallest value is an even number. Write a function isEvenSpaced(int[] a) that will return 1 if it is evenSpaced and 0 otherwise. If array has less than two elements, function will return 0. If you are programming in C or C++, the function signature is:
   int isEvenSpaced (int a[ ], int len) where len is the number of elements in the array.

Examples

Array
Largest value
Smallest value
Difference
Return value
{100, 19, 131, 140}
140
19
140 -19 = 121
0
{200, 1, 151, 160}
200
1
200 -1 = 199
0
{200, 10, 151, 160}
200
10
200 -10 = 190
1
{100, 19, -131, -140}
100
-140
100 - (-140 ) = 240
1
{80, -56, 11, -81}
80
-81
-80 - 80 = -161
0
Solution :
 public static int isEvenSpaced(int[] a)
        {
            int max = a[0], min = a[0];
            for (int i = 0; i < a.Length; i++)
            {
                if (max < a[i])
                {
                    max = a[i];
                }
                if (min > a[i])
                {
                    min = a[i];
                }

            }
            if ((max - min) % 2 == 0)
            {
                return 1;
            }
            else
            {
                return 0;
            }

        }

1 comment:

  1. you didn't implement this
    If array has less than two elements, function will return 0.

    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