Create a Lottery Generator
Several companies that I have worked for have requested a lottery generator as a task prior to interviewing by phone or in person.
Below are several solutions to this problem
Solution 1 : Using Random
This solution a class is created with Random Initialised when the class is instanciated. If random is not declared outside the method then it will return the same 6 numbers every time you call the method. This is a common gotcha when using Random.
The LottoNumbers method returns a string with six numbers comma separated. The Dump method is used in LINQPad to output the results.
using System;
using System.Collections.Generic;
using System.Linq;
void Main()
{
var lotto = new LottoGenerator();
var candidates = lotto.LottoNumbers();
Console.WriteLine(candidates);
}
public class LottoGenerator
{
private Random _random = new Random();
public string LottoNumbers()
{
var numbers = new List<int>();
for (var i = 0 ; i<6; i++)
{
numbers.Add(_random.Next(1,60));
}
return string.Join(", ",numbers.Select(x=> x.ToString()));
}
}
Solution 2 : Using Enumerable.Range() and Guid.NewGuid()
This solution is much more elegant and simpler to use.
- Enumerable.Range(1,60) creates a list of integers from 1 to 60
- OrderBy Guid.NewGuid() generates a new random order each time
- String.Join returns the list flattened out into a comma separated string.
void Main()
{
var numbers = GenerateLottoNumbers();
Console.WriteLine(numbers);
}
string GenerateLottoNumbers()
{
var numbers = Enumerable.Range(1, 60)
.Select(c => c)
.OrderBy(o => Guid.NewGuid())
.Take(6);
return string.Join(", ", numbers);
}
Output
The output of three runs is as follows
- 59, 8, 40, 13, 58, 32
- 26, 7, 29, 59, 36, 38
- 31, 60, 56, 48, 44, 29