Created
October 3, 2013 14:21
-
-
Save asus4/6810651 to your computer and use it in GitHub Desktop.
Random class. but inconsecutive value, like Lottery.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Collections.Generic; | |
namespace ExMath { | |
/// <summary> | |
/// Lottery random. | |
/// </summary> | |
public class LotteryRandom <T> { | |
public IList<T> initialLots; | |
Stack<int> indexes; | |
public LotteryRandom(IList<T> initail_lots) { | |
if(initail_lots.Count == 0) { | |
throw new System.Exception("initial lots need more than 1"); | |
} | |
this.initialLots = initail_lots; | |
RenewIndexes(); | |
} | |
void RenewIndexes() { | |
var numbers = new List<int>(Enumerable.Range(0,initialLots.Count-1)).ToArray(); | |
var numbers2 = numbers.OrderBy(i => System.Guid.NewGuid()).ToArray(); | |
indexes = null; | |
indexes = new Stack<int>(numbers2); | |
} | |
public T GetNext() { | |
if(indexes.Count == 0) { | |
RenewIndexes(); | |
} | |
int i = indexes.Pop(); | |
return initialLots[i]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage
LotteryRandom lottery = LotteryRandom(new List(System.Linq.Enumerable.Range(0,10)));
lottery.GetNext();
lottery.GetNext();
...
...