This question already has answers here:
Best way to repeat a character in C#
(21 answers)
Closed 5 years ago.
Hi im trying to make it so I can generate a random number 1-35 so for example if the number is 25 it will write out in a string 25 equal signs. How can I do that?
Random r = new Random();
r.next(1, 35);
R's result = 25
string result = 25 equal signs
Class string has a constructor that can do the work for you.
Random r = new Random();
int number = r.next(1, 35);
string result = new string('=', number);
Note also that it should be r.Next() not r.next().
Random r = new Random();
int occurrences = r.Next(1, 35);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < occurrences; i++)
{
sb.Append('=');
}
string output = sb.ToString();
Console.WriteLine(output);
You need a loop to repeat adding = to your result.
Update your code to
Random r = new Random();
int total = r.next(1, 35);
string result = "";
for (int i = 0; i < total; i++)
{
result += "=";
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
int random = 0;
int lineNumber = 0;
for (int i = 0; i < 5; i++)
{
lineNumber++;
Random rand = new Random();
random = rand.Next(1, 1001);
Console.WriteLine($"Number {lineNumber}: {random}");
}
I want to print all the random numbers (already done) and then sum all these numbers and print the summary.
You create a new Random object every iteration which prevents you from generating a random result, it will always be the same. To sum up the values I made a variable to which you will add a random value every iteration.
using System;
public class Program
{
public static void Main()
{
Random rand = new Random();
int random = 0;
int lineNumber = 0;
int sum = 0;
for (int i = 0; i < 5; i++)
{
lineNumber++;
random = rand.Next(1, 1001); // Random number between 1 and 1000
sum += random; // Sum random values
Console.WriteLine("Number {0}: {1}", lineNumber, random); // Debug
}
Console.WriteLine("Sum of number values: " + sum);
}
}
// Number 1: 539
// Number 2: 325
// Number 3: 606
// Number 4: 919
// Number 5: 877
// Sum of number values: 3266
To add a Linq alternative to to answers:
Random rand = new Random();
var randomNumbers = Enumerable.Range(1, 5)
.Select(i => rand.Next(1, 1001));
var sumOfRandomNumbers = randomNumbers.Sum();
var linesToPrint = randomNumbers.Select((number, index) => $"Number {index}: {number}");
foreach (var line in linesToPrint)
{
Console.WriteLine(line);
}
Console.WriteLine(sumOfRandomNumbers);
Not only can you move the Random initialization outside the for-loop, you can also remove your linenumber count since this is already encapsulated in the iterable you use in your for-loop: i.
I hereby suggest a solution that also takes advantage of the fact that you can increase a variable with another variable that gets its value assigned at the same time.
int numberCount = 5;
int sum = 0;
int random;
Random rand = new Random();
for (int i = 0; i < numberCount; i++)
{
sum += random = rand.Next(1, 1001);
Console.WriteLine($"Number {i+1}: {random}");
}
Console.WriteLine($"Sum: {sum}");
This question already has answers here:
Random number generator only generating one random number
(15 answers)
C# Random does not work like a random
(4 answers)
Closed 3 years ago.
I have a problem with a random function.
I am trying to create a string with 10 random letters/numbers.
However when I run the function, I get the same string 10 times in a row. What does that depend on and how can I truly create a random string in this case?
void testfunction()
{
for (int i = 0; i < 10; i++)
{
String randomname = getRandomLetterNumbers(10);
listBox1.Items.Add(randomname);
}
}
public String getRandomLetterNumbers(int nrLetterNumbers)
{
String letters = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random(); String str = ""; int rand = 0;
for (int i = 0; i < nrLetterNumbers; i++)
{
rand = random.Next(0, letters.Length);
str = str + letters.Substring(rand, 1);
}
return str;
}
You need to move the random instantiation at class level else you got the same randoms (see duplicates for explanation).
Also you don't need to call substring, you can use char indexer.
private Random random = new Random();
public String getRandomLetterNumbers(int nrLetterNumbers)
{
String letters = "abcdefghijklmnopqrstuvwxyz0123456789";
String str = "";
int rand = 0;
for ( int i = 0; i < nrLetterNumbers; i++ )
{
rand = random.Next(0, letters.Length);
str = str + letters[rand];
}
return str;
}
Result:
l7jvgw77rf
e8h6i6bg1q
2jz8alaf7q
2k1rh5byqo
esgcmdy0f5
sjmhvbilu4
v29bm4gzym
4nznljdwv7
xk9c8s7u6f
wzev2msf0s
If you plan to generate long strings several times you may use StringBuilder instead of string concatenation, that avoids the copy of strings items each time you add a char:
using System.Text;
private string letters = "abcdefghijklmnopqrstuvwxyz0123456789";
public string GetRandomLetterNumbers(int nrLetterNumbers)
{
var builder = new StringBuilder(nrLetterNumbers);
for ( int i = 0; i < nrLetterNumbers; i++ )
{
builder.Append(letters[random.Next(0, letters.Length)]);
}
return builder.ToString();
}
This question already has answers here:
Generating random, unique values C#
(17 answers)
Closed 6 years ago.
I'm trying to randomize four numbers without them being the same, or else it breaks my code. What can I do to so that they are all the same?
This is my code:
Random r = new Random();
_unknown1 = r.Next(1, 8);
_unknown2 = r.Next(1, 8);
_unknown3 = r.Next(1, 8);
_unknown4 = r.Next(1, 8);
If I understand your question correctly. You dont want to repeat your random numbers. This might do the trick for you
List<int> randomNumbers = new List<int>();
for (int i=0; i<4; i++)
{
int number;
do
{
number = random.Next(1, 8);
}
while (randomNumbers.Contains(number));
randomNumbers.Add(number);
}
Pull your random numbers from a randomized list:
Random r = new Random();
var set = Enumerable.Range(1, 8)
.OrderBy(x => r.Next())
.Take(4)
.ToList();
_unknown1 = set[0];
_unknown2 = set[1];
_unknown3 = set[2];
_unknown4 = set[3];
This question already has answers here:
Random number generator with no duplicates
(12 answers)
Closed 6 years ago.
int Min = 0;
int Max = 20;
int[] test2 = new int[5];
Random randNum = new Random();
for (int i = 0; i < test2.Length; i++)
{
test2[i] = randNum.Next(Min, Max);
}
How can I make sure that the numbers between 0 and 20 will not be the same in the array ? For example I don't want to have in the array twice the number 5.
And how to do it with a List ? or array is better ?
Create an array of Max length and insert numbers from 0 to Max. Then use a random algorithm to choose one element of the array (possibly mod(Max-chosenElementsNumber)). After delete element from array. Done.
Or use LINQ. (By generating a sequence between Min and Max with Enumerable.Range):
var rnd = new Random();
var res = Enumerable.Range(Min, Max - Min + 1).OrderBy(x => rnd.Next()).ToList();
And if you want to pick specific number of the sequence you can use Take method. Like this:
var res = Enumerable.Range(Min, Max - Min + 1).OrderBy(x => rnd.Next()).Take(5).ToList();
You can use an HashSet<int>, it doesn't allow duplicates.
int Min = 0;
int Max = 20;
var test2 = new HashSet<int>();
Random randNum = new Random();
while(test2.Count < 5)
{
test2.Add(randNum.Next(Min, Max));
}
You can also randomize with LINQ:
int Min = 0;
int Max = 20;
Random randNum = new Random();
var test2 = Enumerable.Range(Min, Max - Min + 1)
.OrderBy(x => randNum.Next())
.Take(5)
.ToArray();
Just continue to get another random number if you get a duplicated one.
int Min = 0;
int Max = 20;
int[] test2 = new int[5];
Random randNum = new Random();
for (int i = 0; i < test2.Length; i++)
{
int r;
do
{
r = randNum.Next(Min, Max);
} while (test2.Contains(r));
test2[i] = r;
}
This is normal method of sorting integers 0 to 19
List<KeyValuePair<int, int>> numbers = new List<KeyValuePair<int, int>>();
Random randNum = new Random();
for (int i = 0; i < 20; i++)
{
numbers.Add(new KeyValuePair<int,int>(i, randNum.Next()) );
}
numbers = numbers.OrderBy(x => x.Value).ToList();
Console.WriteLine(string.Join(",", numbers.Select(x => x.Key).ToArray()));
Console.ReadLine();
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
I've run into a strange issue. When I run the following code, each of my text boxes get's filled with the same randomly generated number.
public void diceAdd()
{
int[] die = new int[4];
for(int i = 0; i < total.Length; i++)
{
for (int r = 0; r < die.Length; r++)
{
//Simulates rolling a 6 sided die
Random rand = new Random();
randomNumber = rand.Next(1, 7);
die[r] = randomNumber;
}
int smallest = die[0];
for (int c = 1; c < die.Length; ++c)
{
if (die[c] < smallest)
{
smallest = die[c];
}
}
total[i] = die[0] + die[1] + die[2] + die[3] - smallest;
}
strTxt.Text = total[0].ToString();
dexTxt.Text = total[1].ToString();
conTxt.Text = total[2].ToString();
intTxt.Text = total[3].ToString();
wisTxt.Text = total[4].ToString();
chaTxt.Text = total[5].ToString();
The thing is, if I add this messagebox
MessageBox.Show(i.ToString());
after
total[i] = die[0] + die[1] + die[2] + die[3] - smallest;
the numbers each get unique outputs, as intended.
I'm thinking it has something to do with threading, but figured I'd ask here before messing something up.
you are recreating the random number generator every time in the loop, create one before the loop:
Random rand = new Random();
for(int i = 0; i < total.Length; i++)
{
...
}
see also here and here, it explains why the numbers don't change