Array Contains Performance

后端 未结 4 1450
遇见更好的自我
遇见更好的自我 2021-01-24 18:32

I have a program which works with arrays and at some point I have to check if a lsit of values are inside an array, the function that does this takes about 70% of the program CP

4条回答
  •  感动是毒
    2021-01-24 18:53

    As others in the comments have pointed out, the most efficient way to do this is to generate an array with the values you want and shuffle it:

    public static void Shuffle(T[] arr, Random r)
    {
        for (int i = arr.Length - 1; i > 0; --i)
        {
            int j = r.Next(i + 1);
            T tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
    }
    
    public static int[] Generate(int length, Random r)
    {
        var arr = new int[length];
        for(int i = 0; i < length; ++i)
        {
            arr[i] = i;
        }
        Shuffle(arr, r);
        return arr;
    }
    

    then

    var arr = Generate(10, new Random());
    foreach (int i in arr) { Console.WriteLine(i); }
    

提交回复
热议问题