Jump to content


Check out our Community Blogs

TomTheBeast

Member Since 06 May 2012
Offline Last Active Jun 19 2012 09:50 PM
-----

Topics I've Started

Loop Inside Of Method (Not What You Think)

19 June 2012 - 09:18 PM

Hey, well I'm wondering how I could use Random to recieve a random numer of a list and make sure it isnt used.
For example, I have a list called NumsToUse, which contains all digits from 0 to 9. I have to take the digits from that, and randomly place them in a string without there being any repeats. I'm not sure how i would do this, but my strcutre of it would be something like:
public List<int> NumsToUse = new List<int>();
public string getNums() {
string thestoof;
Random rnd = new Random();
int next = rnd.Next(0,9);
if (NumsToUse.Contains(next)) {
thestoof = (thestoof + ", " + next);
NumsToUse.Remove(next);
}
return thestoof;
}

But then how would I make it so when it checks if it contains the number, that isnt being used, to when it IS being used to redo the check?


I've figured out how i could do this, via recurison, and I've tried this method and now i get a Stack Overflow Exeception:

public int ifNum()
		{
				int next = num.Next(0, 9);
				if (!(Nums.Contains(next)))
				{
					Nums.Add(next);
					return next;
				}
				return ifNum();
		}

		public void Randomize()
		{
			foreach (Control button in panel1.Controls)
			{
				if (button.GetType() == typeof(Button))
				{
					int newNum = ifNum();
					button.Text = newNum.ToString();
				}
			}
		}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download