Java Dailly Tip: Codility Frog River One

Java Dailly Tip: Codility Frog River One

Problem

I have a problem with one task on codility. I can't find a way to make them 100%. Here is the link to the quest: https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/. Any hints?

Solution

The task can be done in two lines of code:


public int solution (int X, int [] A)
{
     int [] B = A.Distinct(). ToArray();
     return (B.Length! = X)? -1: Array.IndexOf  (A, B [B.Length - 1]);
}

But if you want to have fun, you can also write them this way:


public static int frogRiver(int X, int[] A)
    {
        int leaves = A.Length;
        int[] counter = new int[X + 1];
        int stepsAvailForTravel = 0;

        for(int i = 0; i < leaves; i++)
        {
            //we won't get to that leaf anyway so we shouldnt count it,
            if (A[i] > X)
            {
                continue;
            } 
            else
            {
                //first hit!, keep a count of the available leaves to jump
                if (counter[A[i]] == 0)
                    stepsAvailForTravel++;

                counter[A[i]]++;

            }
            //We did it!!
            if (stepsAvailForTravel == X)
            {
                return i;
            }
        }

        return -1;

    }

Now consider what is more important to you. Whether making the task simple and space-saving or writing redundant unnecessary code.

Share this Post