I'm supposed to generate random numebers and then giveout the numbers but with different name.
I managed to create random numbers, but I stuck at the giving the right output:
My code:
static Random rnd = new Random();
public static int GetZufall()
{
int random = rnd.Next(0, 10); // from 0 to 9
return random;
}
static void Main(string[] args)
{
Console.WriteLine("How many random numbers do you want: ");
int input = int.Parse(Console.ReadLine());
Console.WriteLine();
int[] array = new int[10];
for (int i = 0; i < input; i++)
{
array[GetZufall()]++;
//Console.WriteLine(GetZufall()); // Random numbers
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"{i} : {array[i]}");
}
int maxValue = array.Max(); // Linq
Console.WriteLine();
Console.WriteLine("Most common value: " + maxValue);
foreach (var item in array)
{
string result = array.ToString();
result = result.Replace("1", "X");
Console.WriteLine(result);
}
}
So as you can see I've tried to convert the array to String and then replace each number with X.
Input: 5 random numbers Output:
This output is right, but the next one should be like this:
I've tried also using Regex Regex r = new Regex("[0-9]"", RegexOptions.None);
First mistake is
string result = array.ToString();
should be
string result = item.ToString();
Here's one solution:
foreach (var item in array)
{
string result = "";
if (item == 0)
result = "0";
else
for (int i = 0; i < item; i++)
result += "X";
Console.WriteLine(result);
}
UPDATE
"If I would like to output it like 0 : XX , also the numbers of array in the front what should I do ?"
This should work:
int count = 0;
foreach (var item in array)
{
string result = "";
result = count.ToString() + " : ";
count++;
for (int i = 0; i < item; i++)
result += "X";
Console.WriteLine(result);
}
You are replacing 1s with 'X'. You should use the values to add Xs like this:
foreach (int x in array)
{
result = "";
for (i = 0; i < x; i++)
result += "X"
if (result == "")
result = "0";
}
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.