c# - Removing a number, after randomly picking it from a list -
i'm making little bingo game have list of numbers (1-90). have randomly pick number, how remove number after have randomly chosen it?
this attempt far:
public partial class form1 : form { int r = 0; public form1() { initializecomponent(); } private void btn_number_click(object sender, eventargs e) { random random = new random(); list<int> bingonumbers = new list<int>(); for(int = 0; < 91; i++) { bingonumbers.add(i); } r = random.next(bingonumbers.count); bingonumbers.removeat(r); richtextbox1.text = bingonumbers[r].tostring(); richtextbox2.text = bingonumbers[r].tostring(); } }
everytime click on button, list gets refilled 90 numbers. guess should contain 1 less number every click, yes?
then need instantiate outside click method.
list<int> bingonumbers = enumerable.range(1, 90).tolist(); private void btn_number_click(object sender, eventargs e) { int r = bingonumbers.orderby(bn => guid.newguid()).firstordefault(); bingonumbers.remove(r); richtextbox1.text = bingonumbers[r].tostring(); richtextbox2.text = bingonumbers[r].tostring(); }
i've removed random variable, , replaced linq magic, orders remaining bingo numbers random factor , takes first argument - , removes it. if bingonumbers empty return 0.
if want implement real shuffling, go fisher-yates-shuffle:
random rnd = new random(); //fisher-yates-shuffle (int x = bingonumbers.count - 1; x > 0; x--) { int y = rnd.next(x + 1); //swapping int temp = bingonumbers[x]; bingonumbers[x] = bingonumbers[y]; bingonumbers[y] = temp; } //take first item out of shuffled list int r = bingonumbers[0]; //remove item bingonumbers.remove(r);
Comments
Post a Comment