我是新手,从iOS转到WP7。
我正在生成一个随机数系列,我希望将其存储到一个数组中。在iOS中就像这样
for(int i=0; i < num; i++) {
int rand = arc4random_uniform(70);
if([rand_array containsObject:[NSNumber numberWithInt:rand]]) {
i--;
}
我搜索过,谷歌搜索,但认为这是我可以提出问题的地方。请帮助我。
答案 0 :(得分:2)
int min = 1;
int max = 4;
int num = 3;
Random r = new Random();
Int[] ar ;
ar = new Int[num]; // Creates array with 3 palces {ar[0],ar[1],ar[2])
for(i = 0;i =< num - 1;i++) {
ar[i] = r.Next(min,max); // generate random number between 1-4 (include 1 & 4)
}
我认为这应该有效(或者我不了解你)。 祝你好运=]
答案 1 :(得分:2)
Enumerable.Range(1, 70)
生成1到70之间的数字。
然后我们就像一副纸牌一样洗牌。
int[] randomNumbers = Enumerable.Range(1, 70).Shuffle(new Random()).ToArray();
这需要位于同一文件夹中的单独类中。
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{
T[] list = source.ToArray();
int count = list.Length;
while (count > 1)
{
int index = random.Next(count--);
yield return list[index];
list[index] = list[count];
}
yield return list[0];
}
这是你想要的吗?
答案 2 :(得分:1)
我觉得你的代码没有意义。我会使用List。
for(int i=0; i < num; i++)
{
int rand = arc4random_uniform(70);//hope you know what you did here, I don't
if(yourList.Contains(rand))
i--;
else
yourList.Add(rand);
}
如果列表不包含随机数,它将添加它,否则它将重复。
答案 3 :(得分:1)
在C#中做这样的事情:
List<int> numbers = new List<int>();
for ( int i = 0; i < num, i++ ) {
int rand = GetARandomNumber();
if ( !numbers.Contains( rand ) ) {
numbers.Add( rand );
} else {
i--;
}
}
你也可能把它转换成while循环:
List<int> numbers = new List<int>();
while ( numbers.Count < num ) {
int rand = GetARandomNumber();
if ( !numbers.Contains( rand ) ) {
numbers.Add( rand );
}
}
答案 4 :(得分:1)
这很简单,真的!代码的直接端口如下所示:
List<int> rand_array = new List<int>();
for(int i = 0; i < num; i++)
{
int rand = RandomHelper.GetInt(0, 70);
if(rand_array.Contains(rand))
{
i--;
continue;
}
rand_array.Add(rand);
}
要在C#中生成随机数,有一个类恰当地称为“随机”。你只需要使用Random类的一个实例来生成数字,所以如果你想要这样的东西:
static class RandomHelper
{
static Random rng = new Random(); // Seed it if you need the same sequence of random numbers
public static int GetInt(int min, int max)
{
return rng.Next(min, max);
}
}