Adding the sum of two randomly generated numbers (using arrays) - c#

class Program
{
const int ROLLS = 51;
static void Main(string[] args)
{
Random r = new Random();
int sum = 0;
int[] dice1 = new int[ROLLS];
int[] dice2 = new int[ROLLS];
for (int roll = 0; roll <= 50; roll++)
{
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
Console.WriteLine("ROLL{0}: {1} + {2} = sum goes here", roll+1, dice1[roll]+1, dice2[roll]+1);
}
}
static int GenerateNum (Random r)
{
return r.Next(1, 7);
}
}
}
So what I have is two arrays to store two different int values that are randomly generated and what I am trying to achieve is the sum of these two randomly generated int values.
Upon execution it should display:
Roll 1: (random number) + (random number) = (sum of the two random numbers)

Just add the two together and store them in sum. Then present sum in the same manner you have presented the rest of the values in the output of the console:
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
sum = dice1[roll] + dice2[roll];
Console.WriteLine("ROLL{0}: {1} + {2} = {3}", roll + 1, dice1[roll], dice2[roll], sum);

Related

C# Random number generator, to display in MessageBox

I'm trying to create a random number generator, ranging from 1 to 1000 for 100 times to achieve the following results on both Console App and popup Windows Message Box (MessageBox.Show) in this format:
100 random numbers in order from smallest to largest
Amount of even numbers generated
Smallest number generated
Largest number generated
The range of numbers
I'm confused at creating the array to store the value and getting the amount of even numbers generated with what I have here, say for example my array name would be "array" and to store the numbers with "n"
string [] array = {item};
string output = string.Join("\n", array);
MessageBox.Show(output)
This is my code, how do I add this in?
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace NumberGenerator
{
class Program
{
static void Main(string[] args)
{
Random number = new Random();
int min = int.MaxValue,
max = int.MinValue;
for (int counter = 0; counter < 100; counter++)
{
int n = number.Next(0, 999);
Console.WriteLine(n);
if (n < min)
min = n;
if (n > max)
max = n;
}
int range = min - max + 1;
string[] array = { "Minimum number is (min)" };
string output = string.Join("\n", array);
Console.WriteLine("Minimum number = {0}, Maximum number = {1}, Range = {2}", min, max, range);
MessageBox.Show(output);
}
}
}
Here is one way to do it.
Code should be self expanatory
static void Main(string[] args)
{
Random number = new Random();
int rangeFrom = 0;
int rangeTo = 999;
List<int> generatedNumbers = new List<int>();
for (int counter = 0; counter < 100; counter++)
{
generatedNumbers.Add(number.Next(rangeFrom, rangeTo));
}
generatedNumbers.Sort();
string output = "generated numbers: {0} \r\n\rmin: {1}\r\n\r\nmax: {2}\r\n\r\nrange: {3}-{4}";
output = string.Format(output,
string.Join(", ", generatedNumbers.ToArray()),
generatedNumbers.Min(),
generatedNumbers.Max(),
rangeFrom,
rangeTo);
MessageBox.Show(output);
}
to summarize:
I have used List for easier manipulation of data and used Linq (make sure you have using System.Linq; in your app).

get max odd number

class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] mass = new int[10];
for (int i = 0; i < mass.Length; i++)
{
mass[i] = rnd.Next(0, 10);
}
Console.WriteLine("display random Massive: \n");
foreach (var i in mass)
{
Console.Write("{0} ", i);
}
Console.WriteLine("\n");
int max = mass.Max();
Console.WriteLine("max value in Massive = {0}", max);
Console.ReadLine();
}
}
my code gives me max value in massive, I need get max odd value. How to get max odd value?
You can use Linq to do this easily
mass.Where (x => x % 2 != 0).Max ();
You can do this easier using linq:
static void Main(string[] args)
{
Random rnd = new Random();
int[] mass = Enumerable.Range(0, 10).Select(i => rnd.Next(0, 10)).ToArray();
Console.WriteLine("display random Massive: ");
Console.WriteLine(string.Join(" ", mass));
Console.WriteLine();
int max = mass.Where(i => (i & 1) == 1).Max();
Console.WriteLine("max value in Massive = {0}", max);
Console.ReadLine();
}
Explanations:
I initialize the array by generating 10 random numbers, converting them to an array
I output them using string.Join
using Where with testing that the last bit is set filters for odd numbers
calling Max on only these odd numbers.
Note that you don't need to use \n as Console.WriteLine adds a new line at the end.
just change
int max = mass.Max();
to
int max = mass.Where(x=>(x%2)==1).Max();
I am asuming you're a beginner like me and don't understand linq yet
Declare a list for holding odd values
List<int> oddList = new List<int>();
Then in your foreach method
foreach (var i in mass)
{
if (i % 2 != 0) //check that number is odd
{
oddList.Add(i); //add odd randoms to list
{
}
Console. WriteLine(oddList.Max().ToString());

Total sum/average of random numbers in c#

I am new to programming and i would be delighted if someone could help me with the following question: "Write a program that randomly selects integers whose values range from 0 to 9. The program will calculate the average of the random numbers and print how many of the random numbers are larger than the average. The program's user will specify how many numbers will be randomly generated". How do you get the total sum of random numbers so you can get the average? This is what i got so far:
int ChosenRandom;
Console.Write("Choose a number between 0-10; ");
ChosenRandom = int.Parse(Console.ReadLine());
Random rnd = new Random();
int RandomNumber = rnd.Next(0, 10);
for (int i = 0; i < ChosenRandom; i++)
{
Console.WriteLine("Random numbers: " + rnd.Next(0, 10));
}
int TotalRandom;
TotalRandom = ChosenRandom + (RandomNumber);
Console.WriteLine("Total is:" + TotalRandom);
int avr;
avr = TotalRandom / ChosenRandom;
Console.WriteLine("Average is: " + avr);
if (ChosenRandom > avr)
{
Console.WriteLine("Numbers larger than average" + ChosenRandom);
}
else
{
Console.WriteLine("All numbers under average");
}
simplest way is by using arrays,
store the numbers in an array while generating them
use the array elements to find the total and average
traverse through array comparing each element with that of average
Check if this solution helps for you.
I have used linq to create average and find all numbers above the 'average'.
using System;
using System.Linq;
namespace Test
{
class Program
{
static void Main()
{
int chosenRandom;
Console.WriteLine("Choose a number between 0-10");
chosenRandom = int.Parse(Console.ReadLine());
Random rand = new Random();
double[] randomNumbers = new double[chosenRandom];
for(int i = 0; i < chosenRandom; i++)
{
Console.WriteLine("Random numbers: " + (randomNumbers[i] = rand.Next(0, 10)));
}
double average = randomNumbers.Average(t => t);
var numbersAboveAverage = randomNumbers.Where(t => t > average);
Console.WriteLine("Average of all random numbers - {0}", average);
foreach(var number in numbersAboveAverage)
Console.WriteLine(number);
}
}
}
Your program looks good. But, you understood the question in a wrong way! The question says that the value of random integers should be 0-9. Not the no of random numbers. The number of random numbers can be of any value as given by user.
Please find below the complete implementation.
class Program
{
static void Main(string[] args)
{
//Step 1. Get the no of random numbers (n) to be generated from user.
Console.WriteLine("Enter the no of Random numbers: ");
int n = int.Parse(Console.ReadLine());
//Step 2. Generate 'n' no of random numbers with values rangeing from 0 to 9 and save them in an array.
Random rand = new Random();
int[] randCollection = new int[n];
for (int i = 0; i < n; i++)
{
randCollection[i] = rand.Next(9);
Console.WriteLine("Random No {0} = {1}", i + 1, randCollection[i]);
}
//Step 3. Compute Average
double average = randCollection.Average();
Console.WriteLine("Average = {0}", average);
//Step 4. Find out how many numbers in the array are greated than the average.
int count = 0;
foreach(int i in randCollection){
if (i > average) count++;
}
Console.WriteLine("No of random numbers above their average = {0}", count);
Console.ReadLine();
}
}
Hope this helps. Let me know if you have any questions.

C# Arrays in a Bowling Program. Wont use Lowest Score

I am trying to create a bowling program that when you enter in your name followed by your score, it will take the average, lowest, and highest scores of the players and print them. However for some reason I cannot get the lowest score to print, as when I hit enter twice, it will use the blank value instead of the lowest entered value and name. How can I fix this so that it will display the lowest score?
{
class Program
{
static void Main(string[] args)
{
const int SIZE = 10;
int i;
// create an array with 10 elements
string[] scoreInfo = new string[SIZE];
string[] names = new string[SIZE];
int[] scores = new int[SIZE];
for (i = 0; i < SIZE; i++)
{
// Prompt the user
Console.Write("Enter your first name and score on one line");
Console.WriteLine(" separated by a space.");
// Read one line of data from the file and save it in inputStr
string inputStr = Console.ReadLine( );
// if statement to break when the user enters a zero
if (inputStr == String.Empty)
{
break;
}
// The Split method creates an array of two strings
scoreInfo = inputStr.Split();
// Parse each element of the array into the correct data type
names[i] = scoreInfo[0];
scores[i] = int.Parse(scoreInfo[1]);
}
Console.WriteLine("The avarage score is {0}", AverageScore(scores, i));
Console.WriteLine("{0} scored the lowest at {1}", names[LowScore(scores, i--)], scores[LowScore(scores, i--)]);
Console.WriteLine("{0} scored the highest at {1}", names[HighScore(scores)], scores[HighScore(scores)]);
Console.ReadLine();
Console.ReadLine();
}
static int LowScore(int[] scores, int j)
{
int min = scores.Min();
return Array.IndexOf(scores, min);
}
static int HighScore(int[] scores)
{
int max = scores.Max();
return Array.IndexOf(scores, max);
}
static double AverageScore(int[] numbers, int j)
{
double average = 0;
for (int i = 0; i < j--; i++)
{
int product = 1;
product = numbers[i] * product;
average = product / j;
}
return average;
}
}
}
Use a different data structure and make less work for yourself.
Start with a dictionary that maps names to scores so that you don't have to mess around with indexes.
Then, LINQ is your friend, as you've already noticed. You don't need to create functions for things that already exist (like min/max/average).
eg.
Dictionary<string, int> ranking = new Dictionary<string, int>();
ranking.Add("adam", 20);
ranking.Add("bill", 10);
ranking.Add("carl", 30);
double avg = ranking.Average(kvp => (double)kvp.Value);
var sorted = ranking.OrderBy(kvp => kvp.Value);
var min = sorted.First();
var max = sorted.Last();
Console.WriteLine("Average: {0}", avg);
Console.WriteLine("Lowest: {0} with {1}", min.Key, min.Value);
Console.WriteLine("Highest: {0} with {1}", max.Key, max.Value);
Modify your Average function like this:-
static double AverageScore(int[] numbers, int j)
{
double sum = 0;
for (int i = 0; i < j; i++)
{
sum += numbers[i];
}
return (double)sum / j;
}
I am not sure why you were taking product of items for finding average of scores.
And Your Min function like this:-
static int LowScore(int[] scores, int j)
{
int min = scores.Where((v, i) => i < j).Min();
return Array.IndexOf(scores, min);
}
Here, you are passing the complete array of integer, so if only 3 players entered values, rest of the values will be initialized to default, i.e. 0 for int, Thus you were getting 0 as Min value.
Also, You need to change the method invocation like this:-
Console.WriteLine("{0} scored the lowest at {1}", names[LowScore(scores, i)], scores[LowScore(scores, i)]);

Adding Array Elements

i'm attempting to learn C# and I have this code. I want it to display a random list of integers and then add them all together within the array and then display the average of all the numbers. Where have I gone wrong, can anyone help? Thanks.
using System;
class grades
{
public static void Main(string[] args)
{
int sumValue = 0;
int[] grades = new int [ 30 ];
Random rnd = new Random();
for (int i = 0; i < 30; i++)
grades[i] = rnd.Next(1,101);
foreach (int i in grades)
{
Console.WriteLine("{0}", i);
sumValue = sumValue + i;
}
double average = sumValue/30;
Console.WriteLine("{0}", average);
}
}
Yeah, the random integers are displayed but the adding and the average isn't calculated.
Yes, it is; you can make it more obvious:
double average = sumValue / 30.0;
Console.WriteLine("The average is: {0:##0.0}", average);
Note also the .0 which ensures we aren't doing integer arithmetic (different fraction / rounding rules).

Categories

Resources