I have a problem with creating a sliding puzzle. I’m trying to make a method to reset & shuffle all 15 buttons, but the problem is the random numbers are repeated.
When I write bool[] usednum = new bool[array.length]; I get an error, so I increase the length of the usednum array …..
private void reset()
{
int[] array = { 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int count = 0;
Random r = new Random();
bool[] usednum = new bool[50];
for (int i = 0; i < usednum.Length; i++)
usednum[i] = false;
while (count < array.Length)
{
int temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button1.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button2.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button3.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button4.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if(usednum[temp] == false)
{
button5.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button6.Text = temp.ToString();
usednum[temp] = true;
count++;
}
/*.
.
.
. to button 15*/
Just shuffle the array: http://en.wikipedia.org/wiki/Shuffling
A simple shuffle algorithm is (in pseudocode)