How to randomly generate 1000 sequences of 6 digit number - c#

I want to generate 1000 number randomly and put the result in a rich text box ,but the result I got from my code is just one number appearing in the rich text box !!
private Random _random = new Random();
int min = 000000;
int max = 999999;
string s;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
s = _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
}

You are overriding the value of s each time you get your next number. Instead you have to add the number to a list. Something like this would work.
List<string> numbers = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
numbers.Add(_random.Next(min, max).ToString("D6"));
}
richTextBox1.Text = string.Join(Environment.NewLine, numbers);
}

As most of the answers here using the .net class Random i would not use it, because in a direct comparison it doesn't creates strong random numbers.
Example:
So if you want strong random numbers you should refrain from using Random and use the RNGCryptoServiceProvider from the namesapace System.Security.Cryptography
ExampleCode:
private RNGCryptoServiceProvider _random = new RNGCryptoServiceProvider ();
int min = 000000;
int max = 999999;
private void Form1_Load(object sender, EventArgs e)
{
int[] results = new int[1000];
var buffer = new byte[4];
int min = 100000;
int max = 999999;
for (int i = 0; i < results.Length; i++) {
while(results[i] < min || results[i] > max)
{
_random.GetBytes(buffer);
results[i] = BitConverter.ToInt32(buffer, 0);
}
richTextBox1.Text += results[i].toString();
}
}

You actually need to concatenate the result with previous calculated result, right now it is replacing the string value in s every time loop executes and you end up only with the last value in s, a quick fix is to use contatination using +:
for (int i = 0; i < 1000; i++)
{
s+= _random.Next(min, max).ToString("D6") + "\n"; // now it keeps previous values as well
}

Problem is that you actually overwrite at each iteration the string s. You need to append the number to the old ones.
for (int i = 0; i < 1000; i++)
{
s += _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
You could also use AppendText method
for (int i = 0; i < 1000; i++)
{
richTextBox1.AppendText(_random.Next(min, max).ToString("D6") + "\n");
}
Suggestion by Matthew Watson: When generating such a large string it is very adviseable to use a StringBuilder. Is has much better performance than a normal concatenation of strings:
StringBuilder sb = new StringBuilder(8000);
for (int i = 0; i < 1000; i++)
{
sb.AppendLine(_random.Next(min, max).ToString("D6"));
}
richTextBox1.Text = sb.ToString();

s += _random.Next(min, max).ToString("D6") + "\n";
^
|
---- You're missing this plus sign

on this line of code you override the Text of richTextBox1
for (int i = 0; i < 1000; i++)
{
s = _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
just change it to (add a + after s)
for (int i = 0; i < 1000; i++)
{
s += _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;

Note that the maxValue or Random.Next is exclusive, so 999999 is never genereted.
var numbers = Enumerable.Repeat(new Random(), 1000)
.Select(r => r.Next(1000000).ToString("D6")); // the same new Random() instance is used for all .Next
richTextBox1.Text = string.Join("\r\n", numbers);
Or a bit more efficient:
richTextBox1.Text = Enumerable.Repeat(new Random(), 1000).Aggregate(new StringBuilder(7000)
, (b, r) => b.AppendFormat("{0:D6}\n", r.Next(1000000))).ToString(0, 6999);

just You need to add ' + ' for the richtextbox1 as like below
try this one
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
s = _random.Next(min, max).ToString("D6") + "\n";
richTextBox1.Text + = s;
}
}

Related

For loop c# only prints the last element of loop in windows form

I am making a Windows Form app in C#. I need to print an array with random numbers on the screen.
There are 20 numbers in total (0 till 19). But it only prints the 19th element. Can anyone help me out? (See image) Don't worry about the comparison number. I just want to print all arrays in the label in the form. Here is some code:
const int numberOfItems = 20;
private void Form1_Load(object sender, EventArgs e)
{
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = ci;
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = random.Next(501);
beforeLoop.Text = $"Element {i} = {numbers[i]}";
total += numbers[i];
}
}
private void compare_Click(object sender, EventArgs e)
{
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = random.Next(501);
int numberBigger = numbers[i] + 10;
int numberSmaller = numbers[i] - 5;
total += numbers[i];
int number = int.Parse(numberBox.Text);
if (number > numbers[i])
{
printLabel.Text = $"Element {i} = {numberBigger}";
}
else
{
printLabel.Text = $"Element {i} = {numberSmaller}";
}
}
}
From your question, I understand that you want to concatenate the strings and print them in multiline label control. If so, then try this code:
const int numberOfItems = 20;
private void Form1_Load(object sender, EventArgs e)
{
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = ci;
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
var text = "";
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = random.Next(501);
text += $"Element {i} = {numbers[i]} \n";
total += numbers[i];
}
beforeLoop.Text = text;
}
private void compare_Click(object sender, EventArgs e)
{
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
var text = "";
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = random.Next(501);
int numberBigger = numbers[i] + 10;
int numberSmaller = numbers[i] - 5;
total += numbers[i];
int number = int.Parse(numberBox.Text);
if (number > numbers[i])
{
text += $"Element {i} = {numberBigger} \n";
}
else
{
text += $"Element {i} = {numberSmaller} \n";
}
printLabel.Text = text;
}
}
The solution here is to add text to a variable in each loop combined by a new line \n. Another solution is to append the text to a c# list. Then join the list with a new line to get a multi-lines string.

How to output only a part of values from ListBox?

I would like to output only a part of items from listBox1 like:response.response.items[counter].first_name to lable_name.Text. How can I do that?
Part of method:
for (int counter = 0; counter < response.response.items.Count; counter++)
{
listBox1.Items.Add(response.response.items[counter].first_name + " " + response.response.items[counter].last_name + Environment.NewLine);
}
The way I output items to lable:
private void listBox1_DoubleClick(object sender, EventArgs e)
{
int count = listBox1.Items.Count -1;
for (int counter = count; counter >= 0; counter--)
{
if (listBox1.GetSelected(counter))
{
lable_name.Text= listBox1.Items[counter].ToString();
}
}
}
lable_name.Text = listbox1.Items[counter].ToString().Split(' ')[0];
could be one of the options ...
just make sure what charackter are qou spliting on as well as the text in string.

random uppercase in a word + multiple string insert

I really need a solution for the next scenario(I've been searching for hours and beating about the bushes to find a smooth solution, but none worked):
I have a winform that:
parse a text file
generate some folders using random words from that file
My code so far:
int value;
string path = null;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog(this) == DialogResult.OK)
{
path = fbd.SelectedPath;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"
}
private void button2_Click(object sender, EventArgs e)
{
if (path != null && Directory.Exists(path))
for (int i = 0; i < value; i++)
{
Random rnd = new Random();
string tick1 = rnd.Next(0, 10).ToString();
var lines = File.ReadAllLines(#"M:\\dictionar.txt");
var r = new Random(DateTime.Now.Millisecond);
var randomLineNumber = r.Next(0, lines.Length - 1);
var line = lines[randomLineNumber];
StringBuilder b = new StringBuilder();
for (int j = 0; j < line.Length; j++)
{
char c = line[j];
if (rnd.Next(2) == 0)
{
c = Char.ToUpper(c);
}
b.Append(c);
if (j % 3 == 2)
{
b.Append(rnd.Next(10));
}
}
line = b.ToString();
Directory.CreateDirectory(Path.Combine(path, string.Format("{0}", line.Insert(2, tick1).Insert(4, tick1).Insert(6, tick1))));
}
}
Is there a way to use ToUpper() method as line.Insert() one so that I can get random upper letters? More, is there a better way of randomizing those index positions form line.Insert() (I'm asking this because when it's generating the folders name: the indexes are the same: e.g pe8rs8on8al and just after that the index changes.)?
I want to achieve the following:
if I have the next words in the .txt file:
personal
football
programming
computer
I would like the folder names to look like:
Pe3rs9oN1al
fO8ot5Ba6lL
You can loop through the characters in the string and build a new string depending on random values:
StringBuilder b = new StringBuilder();
for (int i = 0; i < line.Length; i++ ) {
char c = line[i];
if (rnd.Next(2) == 0) {
c = Char.ToUpper(c);
}
b.Append(c);
if (i % 2 == 1) {
b.Append(rnd.Next(10));
}
}
line = b.ToString();
Note: You shouldn't create Random objects in the loop. You should create a single Random object before the loop and use for all random numbers that you need. Creating instances too close in time will make them return the same sequences of random numbers. Also, you don't need to seed the random generator from the clock, the constructor without parameters does that automatically:
Random rnd = new Random();
So, the code in the method would be:
if (path != null && Directory.Exists(path))
Random rnd = new Random();
for (int i = 0; i < value; i++)
{
var lines = File.ReadAllLines(#"M:\\dictionar.txt");
var randomLineNumber = rnd.Next(0, lines.Length);
var line = lines[randomLineNumber];
StringBuilder b = new StringBuilder();
for (int j = 0; j < line.Length; j++)
{
char c = line[j];
if (rnd.Next(2) == 0)
{
c = Char.ToUpper(c);
}
b.Append(c);
if (j % 2 == 1)
{
b.Append(rnd.Next(10));
}
}
line = b.ToString();
Directory.CreateDirectory(Path.Combine(path, line));
}
}
Note the rnd.Next(0, lines.Length) to pick a random line. The upper limit for the random number is not inclusive, so if you use rnd.Next(0, lines.Length - 1) it will never pick the last line.
That's because you are specifying only tick1 in the same loop. If you want to change this, add additional ticks to your code as below:
string tick1 = rnd.Next(0, 10).ToString();
string tick2 = rnd.Next(0, 10).ToString();
string tick3 = rnd.Next(0, 10).ToString();
Then use those in your formatting of the string:
Directory.CreateDirectory(Path.Combine(path, string.Format("{0}", line.Insert(2, tick1).Insert(4, tick2).Insert(6, tick3))))
Like Guffa said you should not use Random in a loop, in all preference you should only instanciate one of it, but I think you could use it like this
public static class StringRandomize
{
static readonly Random rnd = new Random();
static char[] permmitedCharacters { get; set; }
static StringRandomize()
{
List<char> Chars= new List<char>();
for (int i = 48; i < 48+10; i++)
{
Chars.Add((char)i);
}
for (int i = 65; i < 65+26; i++)
{
Chars.Add((char)i);
}
permmitedCharacters = Chars.ToArray();
}
public static string Randomize(string input, double RandomizePercent = 30)
{
StringBuilder result = new StringBuilder();
int index = 0;
while (index < input.Length)
{
if (rnd.Next(0, 100) <= RandomizePercent)
{
if (rnd.Next(0, 100) <= RandomizePercent)
{
result.Append(GenerateCaracter());
}
else
{
if (rnd.Next(0, 100) > 50)
{
result.Append(input.ToLower()[index]);
}
else
{
result.Append(input.ToUpper()[index]);
}
index++;
}
}
else
{
result.Append(input[index]);
index++;
}
}
return result.ToString();
}
private static char GenerateCaracter()
{
return permmitedCharacters[rnd.Next(0, permmitedCharacters.Length)];
}
}
private static void GenerateRandomDirectories(string path, int value)
{
//I'm supposing value is the number of lines that you want
var lines = File.ReadAllLines(#"M:\\dictionar.txt");
Random rnd = new Random();
if (path != null && Directory.Exists(path))
{
for (int i = 0; i < value; i++)
{
Directory.CreateDirectory(path + "\\" + StringRandomize.Randomize(lines[rnd.Next(0,lines.Length)]));
}
}
}
"pers3o7Nal"
"foOtBaLl"
Got like this
public Form1()
{
InitializeComponent();
string content = "";
using (FileStream fs = new FileStream("D:\\names.txt", FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
content = sr.ReadToEnd();
string[] names = content.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
string path = "D:\\RandDirs";
if (!Directory.Exists(path))Directory.CreateDirectory(path) ;
for (int i = 0; i < 50; i++) Directory.CreateDirectory(path + "\\" + getRandomName(names));
}
Random randName = new Random();
Random insertingNumber = new Random();
Random randUpper = new Random();
Random randInsertNumber = new Random();
string getRandomName(string[] names)
{
string name = names[randName.Next(names.Length)];
name = name.Replace(" ", "");
string result = "";
for (int i = 0; i < name.Length; i++)
result += (randUpper.Next(0, 9) <= 5 ? name[i].ToString().ToLower() : name[i].ToString().ToUpper())
+ (((i + 1) % 2 == 0) ? insertingNumber.Next(0, 9).ToString() : "");
return result;
}
as per your needs, i've changed from randomly inserting numbers to inserting number every 2 characters.

random generator won't generate more than 1 password

I created a random password generator with in a windows form.
The user will select the length of the password and the number of passwords which will be generated in a Richtextbox.
The problem arises when i want to generate more than 1 password.
It does not generate more than 1 password at a time no matter how i do it.
Posting code below.
string passwords = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!/#£#$%&[]+``^~*";
Random pass = new Random();
string passwordline { get; set; }
private void button1_Click(object sender, EventArgs e)
{
passwordline = "";
int passwordsNum = (int)numericUpDown1.Value;
int passwordLength = (int)numericUpDown2.Value;
int length = 0;
for (int i = 0; i<passwordsNum; i++)
{
for (int i2 = 0; i2 < passwordLength; i2++)
{
int randomnumbers = pass.Next(passwords.Length);
passwordline += passwords[randomnumbers];
length++;
if (passwordline.Length == passwordLength)
{
richTextBox1.Text += passwordline + Environment.NewLine;
}
}
}
}
It seems that it could be that you are not resetting the password to empty with every new run. Try changing code to this:
for (int i = 0; i<passwordsNum; i++)
{
passwordline = "";
for (int i2 = 0; i2 < passwordLength; i2++)
{
//Other code is the same
}
}
You simply need to add a new line between two passwords, now you generate sequences of characters you "concatenate" into one password (and remove some errors):
string passwordline = "";
int passwordsNum = (int)numericUpDown1.Value;
int passwordLength = (int)numericUpDown2.Value;
for (int i = 0; i<passwordsNum; i++) {
passwordline = "";
for (int i2 = 0; i2 < passwordLength; i2++) {
int randomnumbers = pass.Next(passwords.Length);
passwordline += passwords[randomnumbers];
}
richTextBox1.Text += passwordline+"\n";
}
The code is also more optimized: you use an if statement in your for-loop, while this code is never executed and simply should be executed at the end of your statement.

Using two for-loops

This is an easy question but I'm still learning this language.
How we can write program that has parameters so that if the the number is 5, it will write
*
**
***
****
*****
I can do this:
*
*
*
*
Using this:
private void button1_Click(object sender, EventArgs e)
{
string message = " ";
for (int count = 0; count < numericUpDown1.Value; count++)
{
for (int m = 0; m < numericUpDown1.Value; count)
{
message += "*" + "\r\n";
}
}
}
I think I need the second for-loop, but I'm not sure what to do next.
if that's not a conceptual homework it would be much easier to solve this way:
for(int i=1; i<=n; i++)
Console.WriteLine(new string('*',i));
You need two loops (see note).
First (a) counts from 1 to 5.
Second (b) counts from 1 to a and adds a "*" each time.
private void button1_Click(object sender, EventArgs e)
{
string message = " ";
for (int count = 0; count < numericUpDown1.Value; count++)
{
for (int m = 0; m < count; m++)
{
message += "*";
}
message += "\r\n"
}
}
Note You can do it with one for loop. But personally I think the two loop version is clearer.
private void button1_Click(object sender, EventArgs e)
{
string line = "";
string message = " ";
for (int count = 0; count < numericUpDown1.Value; count++)
{
line += "*";
message += "\r\n" + line;
}
}
Try this :
private void button1_Click(object sender, EventArgs e)
{
string message = "";
for (int count = 0; count < numericUpDown1.Value; count++)
{
for (int m = 0; m <=count ; m++)
{
message += "*" ;
}
message += "\r\n";
}
}
Yo do not need two for-loops, try this instead
private void button1_Click(object sender, EventArgs e)
{
string message = "";
for (int count = 1; count < numericUpDown1.Value + 1; count++)
{
message += "".PadLeft(count,'*') + Environment.NewLine;
}
}
Try this, just another way to do it for learning:
private static void PrintStars(int num)
{
for (int i = 1; i <= num; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}

Categories