How can I pick randomly between a minus and plus sign?
I'm making a math game, and I need to make it randomly pick between-
or +
.
I have already tried this:
Random rnd = new Random();
string name = rnd.Next(-, +);
But that doesn't work. Anyone have a way I can do this?
As a commenter mentioned the Random
class does not let you generate a random letter. However, it does offer a random number generation function: Next()
. See https://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx
So, to generate a random +
or -
becomes really trivial with that - we just create an array containing the possible options, and generate a random number between 0 and the length of the array. You might think, but wait, if my array contains 2 items, and the random number is 2, and I try to access the array at index 2, wouldn't I get an index out of bounds exception? The answer to that is no, because the upper bound is exclusive in the Next()
function - it can return anything between 0 and upperBound - 1
.
char[] options = {'+', '-'};
Random rnd = new Random();
int randomNumber = rnd.Next(0, options.Length);
char randomChar = options[randomNumber];
public static class Extensions
{
public static T NextItem<T>(this Random r, params T[] items)
{
// Thanks to nbokmans for catching my error here: The second parameter
// is not the largest value it can return; it's the "exclusive upper bound".
return items[r.Next(0, items.Length)];
}
}
...
Random rnd = new Random();
string name = rnd.NextItem("-", "+");
Solution using LINQ:
static void Main(string[] args)
{
Random random = new Random();
int count = 10;
char[] plusesAndMinuses = new int[count]
.Select(i => random.Next())
.Select(i => i % 2 == 0 ? '+' : '-')
.ToArray();
string result = new string(plusesAndMinuses);
Console.WriteLine(result);
}