简体   繁体   中英

Random Sequence Generator in C#

I want to build a sequence randomiser mobile app in c#. I would like to retrieve the smallest and the largest number in an interval from two diffrent text boxes, and after I click the Generate button to display the random sequence of all the numbers in a new text box.

My code only displays one number. What's wrong with it?

Thanks.

 public sealed partial class MainPage : Page
{
    public MainPage()
    {
       this.InitializeComponent();           
    }
   private void button_Click(object sender, RoutedEventArgs e)
    {
        int seed = 345;
        var result = "";
        int min = Convert.ToInt32(textBox.Text);
        int max = Convert.ToInt32(textBox2.Text);
       Random r3 = new Random(seed);
        for (int i = min; i < max; i++)
        {
            ecran.Text = (/*"," + r3.Next(min, max)*/i).ToString();
        }
    }

To clarify what was wrong with your solution:

Inside the loop you were constantly reassigning the value of ecran.Text.

ie

1st loop cycle      > ecran.Text = ", " + 77
2nd loop cycle      > ecran.Text = ", " + 89

//Value of ecran.Text after 1st cycle is ", 77"
//Value of ecran.Text after 2nd cycle is ", 89"

Overriding the value of ecran.Text with each iteration.

Fixed by adding a plus symbol in front of equals ecran.Text += ", " + LOGIC

This happens because you assign sequence values to ecran.Text in a loop. Instead, you should create a string representation of the sequence, and assign it at the end.

Use Shuffle<T> method from this Q&A:

int min = Convert.ToInt32(textBox.Text);
int max = Convert.ToInt32(textBox2.Text);
if (max < min) return;
var sequence = Enumerable.Range(min, max-min+1).ToList();
Shuffle(sequence);
ecran.Text = string.Join(",", sequence);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM