本文轉載http://blog.csdn.net/zhoufoxcn/article/details/5825093#comments
有時我們需要從指定的數值範圍內隨機產生一個數,利用這個偽隨機數去實現自己想要實現的東西。在園子裡看了不少好文章和代碼,發現zhoufoxcn實現這個演算法的思路很好,尤其是第三個方法,
效率較好,便把這一skill記載了下來,雖然我們可以用諸如Random rand = new Random(Guid.NewGuid().GetHashCode()); int value = rand.next(intMin, intMax)代碼實現,但程式員的最大
樂趣在於自己動腦,用不同的思路寫出不同的演算法。
代碼如下:
View Code View Code
static List<int> GenerateNumber1()
{
List<int> result =new List<int>(100);
Random random =new Random();
int temp =0;
while (result.Count <100)
{
temp = random.Next(1, 34);
if (!result.Contains(temp))
{
result.Add(temp);
}
}
return result;
}
static List<int> GenerateNumber2()
{
List<int> container =new List<int>(33);
List<int> result =new List<int>(6);
Random random =new Random();
for (int i =1; i <=33; i++)
{
container.Add(i);
}
int index =0;
int value =0;
for (int i =1; i <=6; i++)
{
index = random.Next(0, container.Count);
value = container[index];
result.Add(value);
container.RemoveAt(index);
}
return result;
}
staticint[] GenerateNumber3()
{
// 用於存放1到33這33個數
int[] container =newint[33];
//用於儲存返回結果
int[] result =newint[6];
Random random =new Random();
for (int i =0; i <33; i++)
{
container[i] = i +1;
}
int index =0;
int value =0;
for (int i =0; i <6; i++)
{
//從[1,container.Count + 1)中取一個隨機值,保證這個值不會超過container的元素個數
index = random.Next(0, container.Length - i);
//以隨機產生的值作為索引取container中的值
value = container[index];
//將隨機取得值的放到結果集合中
result[i] = value;
//將剛剛使用到的從容器集合中移到末尾去
container[index] = container[container.Length - i -1];
//將隊列對應的值移到隊列中
container[container.Length - i -1] = value;
}
return result;
}