2013-01-12 57 views
10

可能重复:
Access random item in list如何从数组随机值在C#

我有一个数字数组,我想从这个数组随机元素。例如:{0,1,4,6,8,2}。我想选择6并将该数字放在另一个数组中,新数组的值将为{6,....}。

我使用random.next(0,array.length),但是这给出了一个随机数的长度,我需要随机数组数。

for (int i = 0; i < caminohormiga.Length; i++) 
{ 
    if (caminohormiga[i] == 0) 
    { 
     continue; 
    } 

    for (int j = 0; j < caminohormiga.Length; j++) 
    { 
     if (caminohormiga[j] == caminohormiga[i] && i != j) 
     { 
      caminohormiga[j] = 0; 
     } 
    } 
} 

for (int i = 0; i < caminohormiga.Length; i++) 
{ 
    int start2 = random.Next(0, caminohormiga.Length); 
    Console.Write(start2); 
} 

return caminohormiga; 
+1

用一个简单的随机选择,你会得到重复。你想返回一个洗牌的'caminohormiga'吗? –

+1

@shebystian是否重复适用? – exexzian

+0

你想洗牌或旋转你的'caminohormiga'阵列吗? –

回答

16

我使用random.next(0,array.length),但是这给长度的随机数和我需要的随机阵列的数字。

random.next(0, array.length)使用返回值作为指数从array

Random random = new Random(); 
int start2 = random.Next(0, caminohormiga.Length); 
Console.Write(caminohormiga[start2]); 
+1

谢谢!代码终于起作用了,但是这些数字是重复的,任何想法如何避免重复? – Shebystian

+1

是的,删除循环中的元素窗体数组。 – Tilak

+0

要避免重复的数字,请使用IEnumerable.OrderBy(n => Guid.NewGuid())'。看到我的[回复](http://stackoverflow.com/a/14297930/444610)。 –

1

获得价值你只需要使用随机数作为参考阵列:

var arr1 = new[]{1,2,3,4,5,6} 
var rndMember = arr1[random.Next(arr1.Length)]; 
0
Console.Write(caminohormiga[start2]); 
2

请试试这个

012的

代替

int start2 = random.Next(0, caminohormiga.Length); 
12

要随机

int[] numbers = new [] {0, 1, 4, 6, 8, 2}; 
int[] shuffled = numbers.OrderBy(n => Guid.NewGuid()).ToArray(); 
+2

有趣的方法! – vbocan

+0

绝对是从一组中获得N个随机元素的最佳答案。非常好。 –

1

我在你想不重复的评论注意到了,所以要进行“洗牌”类似于一副牌号码。

我会用源项List<>,抓住他们随机他们一个Stack<>创造数字的甲板。

下面是一个例子:

private static Stack<T> CreateShuffledDeck<T>(IEnumerable<T> values) 
{ 
    var rand = new Random(); 

    var list = new List<T>(values); 
    var stack = new Stack<T>(); 

    while(list.Count > 0) 
    { 
    // Get the next item at random. 
    var index = rand.Next(0, list.Count); 
    var item = list[index]; 

    // Remove the item from the list and push it to the top of the deck. 
    list.RemoveAt(index); 
    stack.Push(item); 
    } 

    return stack; 
} 

那么接下来:

var numbers = new int[] {0, 1, 4, 6, 8, 2}; 
var deck = CreateShuffledDeck(numbers); 

while(deck.Count > 0) 
{ 
    var number = deck.Pop(); 
    Console.WriteLine(number.ToString()); 
}