Sunday, 24 December 2017

Question :
A non-empty array a of length n is called an array of all possiblities if it contains all numbers between 0 and a.length-1 inclusive. Write a method named isAllPossibilities that accepts an integer array and returns 1 if the array is an array of all possiblities, otherwise it returns 0.
If you are programming in Java or C#, the function signature is
int isAllPossibilities(int[ ] a)
If you are programming in C or C++, the function signature is
int isAllPossibilities(int a[ ], int len) where len is the number of elements in the array
Examples
If the input array is
return
{1, 2, 0, 3}
1
{3, 2, 1, 0}
1
{1, 2, 4, 3}
0 (because 0 not included and 4 is too big)
{0, 2, 3}
0 (because 1 is not included)
{0}
1
{}
0

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

2 comments:

  1. Hi Sengson, please do you mind offering some explanation (may be by adding comments) on the code function isAllPossibilities.
    Thanks

    ReplyDelete
  2. solution is not easy to understand.

    for any one interested try this

    public static int isAllPossibilities(int[] a){
    if(a.length < 1){
    return 0;
    }
    else{
    for(int i = 0; i < a.length; i++){
    boolean iIsInSide = false;

    for(int j : a){
    if( i == j){
    iIsInSide = true;
    break;
    }
    }

    if(!iIsInSide){
    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