O
O
OverLor12021-03-27 10:02:44
Algorithms
OverLor1, 2021-03-27 10:02:44

Why doesn't the algorithm work?

I need the smallest unused array element let's say {0,1,2,3,5}, UniqueElement = 4
why doesn't ids.Any(d => ids[i] + 1 == ids[i + 1]) work

public static int NextId(int[] ids)
    {
        int UniqueElement = 0;
        for (int i = 0; i < ids.Length; i++)
        {
            for (int j = i + 1; j < ids.Length; j++)
            {
                if (ids[i] == ids[j])
                    return 0;
                if (ids.Any(d => ids[i] + 1 == ids[i + 1]))
                {
                    UniqueElement = ids[i] + 1;
                }
                else
                {
                    return ids.Max() + 1;
                }
            }
        }
        return UniqueElement;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wisdou, 2021-03-27
@OverLor1

Here is a solution in O(n^2), can be done in O(n*logn) using sort or O(n) if the array is already sorted

public static int NextId(int[] ids)
    {
      for (int i = 0; i < ids.Length; i++)
      {
        if (Array.IndexOf(ids, i) == -1)
        {
          return i;
        }
      }
      return ids.Length;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question