Silver Hawk
Silver Hawk

Reputation: 57

Problems occur when using while loop in c#

I have this code that shuffle numbers from 1 to 17 and put these numbers into textboxes
The problem occurs when using While loop the form doesn't appear and the calculations take a lot of time what is the wrong ??

this is the code that I wrote :

    private void Level_1_Load(object sender, EventArgs e)
    {

        shuffle();
    }

    private void shuffle()
    {
        Random rand = new Random();
        int randomNum;
        int[] NumArr = new int[17];
        int counter = 0;

        bool IsDuplicate = false;

        do
        {
            randomNum = rand.Next(17);
            IsDuplicate = false;

            for (int i = 0; i < NumArr.Length; i++)
            {
                if (NumArr[i] == randomNum)
                {
                    IsDuplicate = true; break;
                }
            }
            if (IsDuplicate == false)
            {
                NumArr[counter] = randomNum;
                counter++;
            }

        } while (counter < 17);


    TextBox1.Text = NumArr[0].ToString();
    TextBox2.Text = NumArr[1].ToString();
    TextBox3.Text = NumArr[2].ToString();
    TextBox4.Text = NumArr[3].ToString();
    TextBox5.Text = NumArr[4].ToString();
    TextBox6.Text = NumArr[5].ToString();
    TextBox7.Text = NumArr[6].ToString();
    TextBox8.Text = NumArr[7].ToString();
    TextBox9.Text = NumArr[8].ToString();
    TextBox10.Text = NumArr[9].ToString();
    TextBox11.Text = NumArr[10].ToString();
    TextBox12.Text = NumArr[11].ToString();
    TextBox13.Text = NumArr[12].ToString();
    TextBox14.Text = NumArr[13].ToString();
    TextBox15.Text = NumArr[14].ToString();
    TextBox16.Text = NumArr[15].ToString();
    TextBox17.Text = NumArr[16].ToString();

    }

Upvotes: 0

Views: 51

Answers (2)

Shar1er80
Shar1er80

Reputation: 9041

It's probably best that you initialize your array with the numbers you want and then shuffle them around. Something like:

using System;

public class Program
{
    public static void Main()
    {
        int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
        shuffle(numbers);
        Console.WriteLine(String.Join(", ", numbers));
    }

    private static void shuffle(int[] numbers)
    {
        Random r = new Random((int)DateTime.Now.Ticks);
        for (int i = 0; i < numbers.Length; i++)
        {
            int temp = numbers[i];
            int index = r.Next(numbers.Length);
            numbers[i] = numbers[index];
            numbers[index] = temp;
        }
    }
}

RESULT (will be different on each run)

9, 16, 12, 6, 3, 5, 4, 14, 15, 11, 8, 10, 17, 1, 2, 13, 7

Fiddle Demo

Upvotes: 1

Tho Mai
Tho Mai

Reputation: 886

You probably want to use another algorithm for filling an array with non-duplicate numbers.

For example, initialize your array with [0, 1, 2, 3, 4...] and shuffle it.

Upvotes: 0

Related Questions