[C#]產生不重覆的數值

  • 3130
  • 0

摘要:[C#]產生不重覆的數值

太麻煩的程式就不想寫了 看到這篇[.NET]產生不重覆的數值(List vs HashSet) 無聊跟著玩玩。

連結內文主要是比較List與HashSet的速度。

取不重覆的數,我只會一招,用了十年~

我電腦上HashSet的時間為Time elapsed: 00:00:00.0066502

Random rand = new Random();
HashSet check = new HashSet();
const int minValue = 0;
const int maxValue = 50001;
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();

// Begin timing
stopwatch.Start();
for (Int32 i = 0; i < 30000; i++)
{
	int curValue = rand.Next(minValue, maxValue);
	while (check.Contains(curValue))
	{
		curValue = rand.Next(minValue, maxValue);
	}
	check.Add(curValue);
}
var resultArray = check.ToArray();
// Stop timing
stopwatch.Stop();

// Write result
Console.WriteLine("Time elapsed: {0}",
	stopwatch.Elapsed);

而我唯一會的招,是用洗牌的作法Time elapsed: 00:00:00.0025364

            Random rand = new Random();
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            int[] ary = new int[50000];
            for (int i = 0; i < 50000; i++)
            {
                ary[i] = i;
            }
            int tmp;
            int r;
            for (int i = 0; i < 50000; i++)
            {
                r = rand.Next(50000);
                tmp = ary[r];
                ary[r] = ary[i];
                ary[i] = tmp;
            }
​            var resultarray = ary.Take(30000);
            stopwatch.Stop();
            Console.WriteLine("Time elapsed: {0}",
                stopwatch.Elapsed);

速度雖然比較快,但明顯的在此命題下,我浪費了兩萬個int空間。