1

C# Windows Form Application - Visual Studio

This is my code that creates an array and sorts it by numerical value, step by step in a textbox. The only problem is that when i click the button multiple times it switches between the actual array and what seems to be another random array. Why is this?

    int[] randArray = new int[5];
    private void txtSeed_TextChanged(object sender, EventArgs e) {
        int notaninteger;
        if (!int.TryParse(txtSeed.Text, out notaninteger)) {
            txtSeed.Text = "0";
        }
        if (int.Parse(txtSeed.Text) < 0) {
            txtSeed.Text = "0";
        }
    }
    private void btnLotto_Click(object sender, EventArgs e) {
        fillArray();
        sortArray();
        showResult();
    }
    private void fillArray() {
        bool inArray = true;
        Random random = new Random(int.Parse(txtSeed.Text));
        for (int i = 0; i < randArray.Length; i++) {
            do {
                int randomNumber = random.Next(1, 51);
                inArray = checkArray(randomNumber);
                if (!inArray) {
                    randArray[i] = randomNumber;
                }
            }
            while (inArray);
        }
    }
    private void displayArray() {
        txtLotto.AppendText(getFormat());
        txtLotto.AppendText("\r\n");
    }
    private void sortArray() {
        txtLotto.Text = "";
        for (int i = 0; i < randArray.Length; i++) {
            for (int j = 0; j < randArray.Length - 1; j++) {
                if (randArray[j] > randArray[j + 1]) {
                    swap(ref randArray[j], ref randArray[j + 1]);
                    displayArray();
                }
            }
        }
    }
    private bool checkArray(int a) {
        for (int i = 0; i < randArray.Length; i ++) {
            if (randArray[i] == a) {
                return true;
            }
        }
        return false;
    }
    private string getFormat() {
        string format = "";
        for (int i = 0; i < randArray.Length; i ++) {
            if (i != 0) {
                format += "-";
            }
            format += randArray[i];
        }
        return format;
    }
    private void showResult() {
        lblFinalResult.Text = "Final Result:    ";
        string format = "";
        for (int i = 0; i < randArray.Length; i++) {
            if (i != 0) {
                format += "-";
            }
            format += randArray[i];
        }
        lblFinalResult.Text += format;
    }
    private void swap(ref int a, ref int b) {
        int tempA = a;
        a = b;
        b = tempA;
    }
  • 2
    You only need one Random instance for the whole app, not for each fill operation. Also, Random doesnt mean unique - most lottos would use 50 unique numbers between 1 and 50 (incl) – Ňɏssa Pøngjǣrdenlarp Oct 26 '16 at 01:15
  • What do you mean by one random instance? – Tyler Arnett Oct 26 '16 at 01:30
  • 1
    @TylerArnett Not random. Random. As in, one instance of `Random`. – Abion47 Oct 26 '16 at 01:45
  • 1
    @Plutonix your suggestion seem to be against code OP tries to write where seed comes from textbox (and hence sequence stays the same till seed manually updated)... – Alexei Levenkov Oct 26 '16 at 02:11
  • Note that if you need actual code that generates shuffled list of numbers in particular range (also known as "unique random numbers") - just shuffle sequncece of 1..n using http://stackoverflow.com/questions/273313/randomize-a-listt and possibly take elements you need with `.Take()`... – Alexei Levenkov Oct 26 '16 at 02:14
  • Alternatively use http://stackoverflow.com/a/1653204/477420 that does not even shuffle whole set... – Alexei Levenkov Oct 26 '16 at 02:22
  • @Plutonix yea the idea was that the seed will keep the numbers the same until a new seed is manually updated. The issue with my code was that I didn't clear the array each time I filled it, so the array was filling with random numbers that weren't already inside the array itself. – Tyler Arnett Oct 26 '16 at 02:46

1 Answers1

0

https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx

If the same seed is used for separate Random objects, they will generate the same series of random numbers.

The reason that you have 2 different kind of arrays is because:

  1. Note that Random will always generate, for ex: 1,2,3,4,5,6,7,8,9,10 after initializing with same seed.
  2. you fill the array with the first 5 series, for ex: 1,2,3,4,5.
  3. the next time it tries to fill with the same amount 1,2,3,4,5, but your code cannot do that, because you avoid inputting duplicates, therefore you get and fill the array with the next 5 series, for ex: 6,7,8,9,10
  4. the next time you try to fill the array, it tries to fill with the same amount 1,2,3,4,5 again, you successfully input to the array.
  5. repeat 3~4

To solve your problem, basically the rule is just create a single Random instance and avoid reinitializing (with same seed). Therefore, you will always get different arrays every click.

private Random random = new Random(); // one instance of random
private int previousSeed = 0; // memorize previous seed
private void fillArray()
{
    bool inArray = true;
    int newSeed = int.Parse(txtSeed.Text);
    if (newSeed != previousSeed)
    {
        // reinitialize the random only if new seed is different
        random = new Random(newSeed);
        previousSeed = newSeed;
    }
kurakura88
  • 2,185
  • 2
  • 12
  • 18