hey folks, I’m trying to think of an easy way to pick 3 random numbers from a range of 5… or i suppose… how ever many numbers from a range of what ever.
the important thing is that the numbers are all exclusive, and i don’t get any repeats. so in the case of selecting 3 numbers from 1-5, i could get 1,3,5… 2,4,5, 1,2,5, what ever, but not 1,1,2, 2,3,3… etc.
I’m being too descriptive here. You know what i’m talking about.
I’d really rather not do this the long way. any ideas?
I used a shuffle routine for something along those lines:
function Start () {
var numbers = [1, 2, 3, 4, 5];
Shuffle (numbers);
print (numbers[0] + " " + numbers[1] + " " + numbers[2]);
}
function Shuffle (array) {
for (i = 0; i < array.Length-1; i++) {
var rand = i + Random.Range(0, array.Length-i);
var temp = array[i];
array[i] = array[rand];
array[rand] = temp;
}
}
(Uses dynamic typing for simplicity; won’t work on Unity iPhone.)
–Eric
haha wow.
i had to stare at that code for like 15 minutes before i got it. I guess i have a lot to learn before I’m a good coder.
Thanks very much Eric, I really appreciate it. honestly, now that i look at it, I don’t know if i would have ever figgured that out.
you know, on a completely off topic rant here – it would seem to me that these sorts of logical structures are probably one of the big things that separates a good coder from a bad one… is that right? I’ve looked for books on coding, but all i find is language reference.
is there a place that I can find logic structures like this? so that i can build a sort of mental library for logic patterns to apply to various programming problems?
It’s mostly about interest and experience. What you ask about is a classic algorithm problem, and experienced programmers will have implemnted it a few times. But yes, coming up with truly original algorithms is difficult. Humans tend to think alike, so whenever you’re programming something and you think you’re being really clever… usually a lot of other people have done similar things before. 
Very true. I’ll tell you a secret about a little-known web site called “google.com”.
Pretty much all of the most-used algorithms are out there, usually presented in vaguely C-like pseudocode, which translates nicely to JS/C#. As I recall, I got that shuffle algorithm from such a search…while I imagine there would be a certain satisfaction in being able to think up everything yourself, I’m just not that clever, and even if I were, it saves time by doing a search, rather than reinventing the wheel for the umpteenth time.
–Eric