Choosing a random string in C# for WP7
I am making a WP7 app that, when a user taps an image, randomly decides what they will get.
Right now, I have this code:
string firstdoor = "";
string seconddoor = "";
string thirddoor = "";
and
string prize1 = "vacation to Hawaii with all expenses covered";
string prize2 = "used glue stick";
string prize3 = "pile of dog dung";
string prize3 = "vacation to Europe w开发者_运维问答ith all expenses covered";
string prize3 = "million dollars";
string prize3 = "blank CD";
string prize3 = "temporary tattoo";
string prize3 = "nickel";
string prize3 = "dime";
and
What I want to do is randomly assign the door
s to the prize
s.
For instance, when the user taps the image, dime
is assigned to thirddoor
, nickel
is assigned to firstdoor, and million dollars
is assigned to secondoor
.
Here are the steps that seem to make the most sense to me (not going to write all the code for you):
Put all prize strings in an array.
Generate three random numbers between 0 and the maximum number of prizes.
Assign each door the prize from the prize array with each of the random numbers.
...
Profit!
Edit
Actually, here's a little bit of code to help out:
var randomGenerator = new Random();
string[] prizes = { "vacation to Hawaii with all expenses covered",
"used glue stick",
"pile of dog dung",
"vacation to Europe with all expenses covered" };
string firstDoor = prizes[randomGenerator.Next(prizes.Length)];
string secondDoor = prizes[randomGenerator.Next(prizes.Length)];
string thirdDoor = prizes[randomGenerator.Next(prizes.Length)];
On the assumption that you don't want to repeat any of the prizes the solution is a little more complicated, but you can bring some Linq and a little trick with Random into play:
var prizes = new string[] {
"vacation to Hawaii with all expenses covered",
"used glue stick",
// etc
"dime"
};
var rand = new Random();
var result = (from prize in prizes
orderby rand.NextDouble()
select prize).Take(3).ToArray();
Justin, your answer is fine but might result in 2 doors having the same prize. I believe this might be better:
string[] prizes = new string[]
{
"Prize 1",
"Prize 2",
"Prize 3",
"Prize 4",
"Prize 5"
};
Random r = new Random();
var choices = prizes.OrderBy(x => r.Next()).Take(3).ToArray();
string firstDoor = choices[0];
string secondDoor = choices[1];
string thirdDoor = choices[2];
精彩评论