天天看點

Smallest unused ID

​​http://www.codewars.com/kata/smallest-unused-id​​

Description:

Hey awesome programmer!

You've got much data to manage and of course you use zero-based and non-negative ID's to make each data item unique!

Therefore you need a method, which returns the smallest unused ID for your next new data item...

Go on and code some pure awesomeness!

自己寫了一段超級爛的

Console.WriteLine("Length = {0}", ids.Length);
            ids = ids.OrderBy(x => x).ToArray();
            foreach (var number in ids)
            {
                Console.Write("{0} ", number);
            }
            Console.WriteLine();

            int count = ids.Count();
            int result = ids.Min() - 1;
            if (result != -1)
            {
                return 0;
            }
            bool loopAllNumber = true;
            for (int i = 0; i < count; i++)
            {
                result++;
                if (result != ids[i])
                {
                    loopAllNumber = false;
                    break;
                }
            }
            Console.WriteLine("after for loop,result = {0}", result);
            if (loopAllNumber)
            {
                result++;
            }
            return result;      

其他人寫的,使用了Linq的Except

var max=ids.Max();
   var excepts= Enumerable.Range(0, max).Except(ids);
           return excepts.Count() == 0 ? max + 1 : excepts.Min();      

//

// 摘要:

// 通過使用預設的相等比較器對值進行比較生成兩個序列的差集。

//

// 參數:

// first:

// 一個 System.Collections.Generic.IEnumerable<T>,将傳回其不在 second 中的元素。

// second:

// 一個 System.Collections.Generic.IEnumerable<T>,如果它的元素也出現在第一個序列中,則将導緻從傳回的序列中移除這些元素。

// 類型參數:

// TSource:

// 輸入序列中的元素的類型。

// 傳回結果:

// 包含兩個序列元素的差集的序列。

// 異常:

// System.ArgumentNullException:

// first 或 second 為 null。

public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);