0

I've added a condition that checks if an array is empty and automatically set an integer to larger than the size of the array since it's empty, but i get an "Index was outside the bounds of the array." mesage instead

    public static bool hurdleJump(int[] hurdles, int jumpHeight)
    {
        int max = hurdles[0];

        if (hurdles == null && hurdles.Length == 0)
        {
            return false;
        }
        else if (hurdles != null || hurdles.Length >= 1)
        {
            for (int i = 0; i < hurdles.Length - 1; i++)
            {
                max = max < hurdles[i+1] ? hurdles[i+1] : max;
            }
            if (jumpHeight >= max)
            {
                return true;
            }
        }
            return false;
    }

    static void Main(string[] args)
    {
        Console.WriteLine(hurdleJump(new int[] {}, 7));
    }
5
  • Does this answer your question? What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it? Commented Jul 29, 2020 at 10:57
  • 2
    if (hurdles == null && hurdles.Length == 0) should be if (hurdles == null || hurdles.Length == 0) Currently, you'll get a NullReferenceException if hurdles is null. Then you won't need the check against null in the else if condition. Commented Jul 29, 2020 at 10:57
  • 3
    Also, you need to move the int max = hurdles[0] into the else if body. Have a think about why this is necessary. Commented Jul 29, 2020 at 10:59
  • you also could use the Any() method, learn.microsoft.com/en-us/dotnet/api/… Commented Jul 29, 2020 at 10:59
  • hurdels[0] accesses the first element, while you provide an empty one. Simply omit that line. Commented Jul 29, 2020 at 11:02

1 Answer 1

1
  1. Moved the max initialization to after we've ensured handles is not null or empty.

  2. Changed the first && to an ||.

     public static bool hurdleJump(int[] hurdles, int jumpHeight)
     {
         if (hurdles == null || hurdles.Length == 0)
         {
             return false;
         }
         else
         {
             int max = hurdles[0];
             for (int i = 0; i < hurdles.Length - 1; i++)
             {
                 max = max < hurdles[i + 1] ? hurdles[i + 1] : max;
             }
             if (jumpHeight >= max)
             {
                 return true;
             }
         }
         return false;
     }
    
Sign up to request clarification or add additional context in comments.

1 Comment

In the "else" you don't need to re-check the condition of the "if". You already know it isn't true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.