0

I'm kinda new to array and I made a char array (with 174 things in it) but I don't know how to output it in a randomize way. I'm trying to make a secured code for my system. I wanted to output 13 char from that 174 char array into a textbox, but I don't think I get the logic. Thank you in advance! Here is the code that only outputs 1 char per button click:

Random rnd = new Random();
int randomnum = rnd.Next(0, 174);
for (int x = 0; x <= 13; x++)
{
    textBox11.Text = chararray[randomnum];
}
1
  • Some lines of code will explain better your problem. Show what have you tried, what is the expected result and what you get instead Commented Jan 30, 2019 at 17:57

2 Answers 2

2

Your code is almost there, but there are a few issues:

  1. You need to append the new character to the end of the string as apposed to just setting the Text value directly. You can do this easily with += instead of =.

  2. You need to pick a different random character for each iteration of the loop, so move your call to .Next inside the for.

Putting this together you'd have something like this:

Random rnd = new Random();

for (int x = 0; x <= 13; x++)
{
    int randomnum = rnd.Next(0, 174);
    textBox11.Text += chararray[randomnum];
}

Note however, that if this is for the purpose of security, using Random isn't great. You should probably use something like the RNGCryptoServiceProvider. For example:

using (var rng = new RNGCryptoServiceProvider())
{
    byte[] password = new byte[10];
    rng.GetBytes(password);
    textBox11.Text = Convert.ToBase64String(password).Remove(13);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This allows for duplicate indices, not sure if that's a desired side effect or not.
1

I've attached a screenshot of this code working. I had a small typo

This will change the seed for random

int seed = 1;

Create an instance of Random, we don't need to recreate it every time we need to use it

Random r = new Random(seed);

This only initializes the characters

char[] _myChars = new char[170];
for(var i = 0; i < _myChars.Length; i++)
{
    _myChars[i] = (char)(i%26 + 65);
}

This is the query you're looking for, it will query the characters and order them by a random order with r.Next()

var output = _myChars.OrderBy(o => r.Next()).Take(13).ToList();

This is only for displaying the output, you would want to use the output in your textbox

for(var i = 0; i < output.Count; i++)
{
    Console.WriteLine(output[i]);
}
Console.ReadLine();

Working code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.