If I have an array that contains some values. How to get different random number each time - which represents an indexes - in which to get different values from the array ?
Asked
Active
Viewed 531 times
-2
-
Have you tried removing the selected result from the list of available locations and then randomising from the remaining locations? – phuzi Jun 21 '17 at 14:00
-
3Don't "generate" random numbers. Collect all possible numbers and shuffle them. Then enumerate the shuffled numbers. -- `foreach(int randomIndex in Enumerable.Range(0,5).OrderBy(rnd.Next())) { [...] }` might be a start. – Corak Jun 21 '17 at 14:02
-
1@phuzi : I cant because I need this array in different methods – Rose Jun 21 '17 at 14:11
1 Answers
0
Generate the sequence of the range you need, and sort it randomly. Then, put the values in a stack and pick from that stack. For example:
var rnd = new Random();
var randomValues = new Stack<int>(Enumerable.Range(0,5).OrderBy(x => rnd.Next()));
var randomIndex1 = randomValues.Pop();
var randomIndex2 = randomValues.Pop();

Cody Gray - on strike
- 239,200
- 50
- 490
- 574

Magnus
- 45,362
- 8
- 80
- 118
-
Why did you re-open this question (which had previously been closed as a duplicate), just to post an answer that proposes [a sub-optimal solution](https://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm)? This looks a bit like abuse of your gold tag badge privileges to me. Can you explain why you disagree that this question is a duplicate of [this one](https://stackoverflow.com/questions/9592166/unique-number-in-random) and [this one](https://stackoverflow.com/questions/26931528/random-number-generator-with-no-duplicates)? – Cody Gray - on strike Aug 07 '17 at 13:24
-
@CodyGray Yes, you are correct, I think I was a little to quick to re-open the question. I though the top answer in the duplicate question just shuffled the array, but it does fill it also. So yes, the only difference with my answer is really only that I also show an easy way to pick the values using a stack. – Magnus Aug 14 '17 at 09:43
-
Cool. Thanks for replying. I just got a couple of flags about suspicious behavior here, and wanted to give you a heads up. In the future, it would probably work out better to specifically mention what your answer was adding that is *not* covered by the answers in a proposed duplicate (just like we ask the asker to clarify in their question when they are protesting a duplicate closure). – Cody Gray - on strike Aug 14 '17 at 12:03