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));
    }
Nathan
  • 1
  • 1
  • Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – sticky bit Jul 29 '20 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. – Matthew Watson Jul 29 '20 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. – Matthew Watson Jul 29 '20 at 10:59
  • you also could use the Any() method, https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netcore-3.1 – pbachman Jul 29 '20 at 10:59
  • `hurdels[0]` accesses the **first** element, while you provide an **empty** one. Simply omit that line. – MakePeaceGreatAgain Jul 29 '20 at 11:02

1 Answers1

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;
     }
    
Andrew Arthur
  • 1,563
  • 2
  • 11
  • 17