Sunday, 24 December 2017

Question :
A Nice array is defined to be an array where for every value n in the array, there is also an element n-1 or n+1 in the array.

For example, {2, 10, 9, 3} is a Nice array because
2 = 3-1
10 = 9+1
3 = 2 + 1
9 = 10 -1

Other Nice arrays include {2, 2, 3, 3, 3}, {1, 1, 1, 2, 1, 1} and {0, -1, 1}.

The array {3, 4, 5, 7} is not a Nice array because of the value 7 which requires that the array contains either the value 6 (7-1) or 8 (7+1) but neither of these values are in the array.

Write a function named isNice that returns 1 if its array argument is a Nice array. Otherwise it returns a 0.

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

If you are programming in C or C++, the function signature is
   int isNice(int a[ ], int len) where len is the number of elements in the array.

Solution:


public static bool isNice(int[] a)
        {
            int i, j, x, y;
            bool isNice = true, step = false;
            for(i=0;i<a.Length;i++)
            {
                step = false;
                for(j=0;j<a.Length;j++)
                {
                    x = a[j] + 1;
                    y = a[j] - 1;
                    if(a[i]==x || a[i]==y)
                        step = true;
                }
                if(j==a.Length && step==false)
                {
                    isNice =false;
                    break;
                }
            }
            bool res = isNice == true ? true : false;
            return res;
        }

2 comments:

  1. Hello,
    Your solution is great but I think a refactorization would be nice:


    public static bool IsNice(int[] arr)
    {
    return arr.All(element => arr.Contains(element + 1) || arr.Contains(element - 1)) && arr.Length > 0;
    }

    ReplyDelete
  2. the return type should be int

    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