Compare 7 input numbers with 7 Random Numbers - c#

I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..
List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
try {
Console.Write("First Number {0}: ", i);
int x = Convert.ToInt16(Console.ReadLine());
lista1.Add(x);
} catch (Exception ex){
Console.WriteLine("The input number is incorret! It has to be whole number");
Console.WriteLine("Error: {0}", ex.Message);
i--;
}
Console.WriteLine("Random Numbers are: ");
InitArray();
Console.WriteLine(item);
}

If you have your inputs in a list, and your random numbers in another list, your can use the following code to know the count of what is common between your lists.
inputs.Intersect(randoms).Count

This is my interpretation.
class Program
{
private static Random rnd = new Random();
static void Main(string[] args)
{
do
{
uint[] myRandoms = GetRandoms();
uint[] userInput = GetUserInput();
List<uint> matches = GetMatches(userInput, myRandoms);
Console.WriteLine("Your Numbers");
PrintEnumerable(userInput);
Console.WriteLine("The Lottery Winners");
PrintEnumerable(myRandoms);
Console.WriteLine("Numbers You Matched");
PrintEnumerable(matches);
int NumOfMatches = matches.Count;
if (matches.Count >= 4)
Console.WriteLine($"You win! You matched {NumOfMatches} numbers.");
else
Console.WriteLine($"Sorry, you only matched {NumOfMatches} numbers.");
Console.WriteLine("Play again? Enter Y for yes and N for no.");
} while (Console.ReadLine().ToUpper() == "Y");
}
private static uint[] GetRandoms()
{
uint[] newRandoms = new uint[7];
int index = 0;
while (index < 7)
{
//.Next(int, int) limits the return to a non-negative random integer
//that is equal to or greater than the first int and less than the second the int.
//Said another way, it is inclusive of the first int and
//exclusive of the second int.
uint r = (uint)rnd.Next(1, 40);
if (!newRandoms.Contains(r)) //prevent duplicates
{
newRandoms[index] = r;
index++;
}
}
return newRandoms.OrderBy(x => x).ToArray();
}
private static uint[] GetUserInput()
{
uint[] inputs = new uint[7];
int i = 0;
while (i < 7)
{
Console.WriteLine("Enter a whole number between 1 and 39 inclusive. No duplicates, please.");
//Note: input <= 39 would cause an error if the first part of the
// if failed and we used & instead of && (And instead of AndAlso in vb.net).
//The second part of the if never executes if the first part fails
//when && is used. //prevents duplicates
if (uint.TryParse(Console.ReadLine(), out uint input) && input <= 39 && input >0 && !inputs.Contains(input))
{
inputs[i] = input;
i++; //Note: i is not incremented unless we have a successful entry
}
else
Console.WriteLine("Try again.");
}
return inputs.OrderBy(x => x).ToArray();
}
//I used a List<T> here because we don't know how many elements we will have.
private static List<uint> GetMatches(uint[] input, uint[] rands)
{
List<uint> matches = new List<uint>();
int i;
for (i=0; i<7; i++)
{
if(rands.Contains(input[i]))
matches.Add(input[i]);
}
//Or skip the for loop and do as Sunny Pelletier answered
//matches = input.Intersect(rands).ToList();
return matches.OrderBy(x=>x).ToList();
}
//You are able to send both List<T> and arrays to this method because they both implement IEnumerable
private static void PrintEnumerable(IEnumerable<uint> ToPrint)
{
foreach (uint item in ToPrint)
Console.WriteLine(item);
}
}

There are many ways to accomplish that, but a simple way is to use a for loop inside of another for loop. i.e
int[] userInputNumbers = {1,2,3,4,5,6,7};
int[] numbersToCompareTo = {1,9,11,12,4,6,16};
int countOfNumbersThatAreTheSame = 0;
for(int i=0; i<userInputNumbers.Length; i++)
{
for(int j=0; j<numbersToCompareTo.Length; j++)
{
if(userInputNumbers[i] == numbersToCompareTo[j])
{
countOfNumbersThatAreTheSame++;
}
}
}
Console.Write(countOfNumbersThatAreTheSame);
Console.Read();

This is how I would Go about approaching it Cleanly using CSharp.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
public List<List<int>> Players { get; set; } //Your Players
public List<int> RandomNumbers { get; set; } //Your Random numbers enerated my Computer
public List<List<int>> MatchedNumbers { get; set; } //to store Matched Numbers for each player
public int NumbersRequiredCount { get; set; } = 7; //Depends on how many numbers the players must guess, initialize to 7 numbers
Program()
{
//Instantiate your objects
Players = new List<List<int>>(); //List of Players with their list of guessed numbers
RandomNumbers = new List<int>();
MatchedNumbers = new List<List<int>>(); //To hold Matched Values
}
private List<int> GenerateAutoNumbers(int Count, int Min, int Max)
{
var Result = new List<int>(); //Result Container - will be returned
var Random = new Random(); //Create Random Number Object
for(int i = 0; i < Count; i++)
{
//Generate your random number and save
Result.Add(Random.Next(Min, Max));
}
//Return "Count" Numbers of Random Numbers generated
return Result;
}
public List<int> EvaluateMatches(List<int> Inputs, List<int> Bases)
{
var result = new List<int>();
//Inplement a counter to check each value that was inputted
for(int i = 0; i < Inputs.Count; i++)
{
for (int r = 0; r < Bases.Count; r++)
{
//Check if the current input equals the current Random Number at the given index
if(Inputs[i] == Bases[r])
{
//If matched. Add the matched number to the matched list
result.Add(Inputs[i]);
}
}
}
//At this point, all matched numbers are organized in result object
return result; //return result object
}
static void Main(string[] args)
{
Program App = new Program();
//Players must input numbers - Assuming they must guess between 1 - 100
//It can be as many players
//Player 1
App.Players.Add(new List<int> { 5, 47, 33, 47, 36, 89, 33 });
//Player 2
App.Players.Add(new List<int> { 1, 17, 38, 43, 34, 91, 24 });
//Player 3
App.Players.Add(new List<int> { 6, 74, 39, 58, 52, 21, 9 });
//At this point the inputs are all in for the 3 players
//Now generate your RandomNumbers
App.RandomNumbers = App.GenerateAutoNumbers(App.NumbersRequiredCount, 1, 100);
//Now you need to evaluate the guessed numbers
//For each Player
for(int p = 0; p < App.Players.Count; p++)
{
//Create the list for each user to hold the matched numbers
App.MatchedNumbers.Add(App.EvaluateMatches(App.Players[p], App.RandomNumbers));
}
//Now all Players numbers are evaluated, all you need is to print the results
Console.WriteLine("Results has been retrieved");
Console.Write("Generated Numbers are: ");
foreach(int i in App.RandomNumbers)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Following Matches were Found: ");
for(int p = 0; p < App.Players.Count; p++)
{
Console.Write($"Player {p + 1} has {App.MatchedNumbers[p].Count} Matches: ");
foreach(int i in App.MatchedNumbers[p])
{
Console.Write(i + " ");
}
Console.WriteLine();
}
Console.Write("\n");
Console.WriteLine("Press any Key to Exit!");
Console.ReadKey();
}
}
}
It will print the numbers matched on the screen.

Try this tested and working example. If you run this method execRandomNumber();
You will get this output ::
The numbers returned are 18
The numbers matching are 18
The numbers returned are 15
The numbers matching are 15
The numbers returned are 17
The numbers returned are 19
The numbers matching are 19
The numbers returned are 16
The numbers matching are 16
The numbers returned are 14
The numbers returned are 20
Using directives ::
using System.Collections.Generic;
Declarations ::
public static List<int> lista1 = new List<int>();
public static List<int> returnedRandomList = new List<int>();
public static int[] myArrNums = new[] { 12, 25, 15, 16, 18, 19 };
public static int[] myRandArr = new[] { 14, 15, 16, 17, 18, 19, 20 };
Method 1 is for if you need to generate the random numbers ::
private void execRandomNumber()
{
//==============Don't have the numbers but need to generate them?==============
returnedRandomList = Gen(returnedRandomList, null);
returnedRandomList.ForEach(delegate (int num)
{
Console.WriteLine(string.Concat("The numbers returned are ", num));
if (numIsMatch(num) == true)
{
lista1.Add(num);
Console.WriteLine(string.Concat("The numbers matching are ", num));
}
});
//==============Generator will return list of random numbers, then we compared them==============
}
Your number generator ::
//==============Your number generator==============
private List<int> Gen(List<int> randGenerator, Random ranNum)
{
ranNum = new Random();
var rn = 0;
returnedRandomList.Clear();
do
{
if (randGenerator.Count == 7)
break;
rn = ranNum.Next(14, 21);
if (!(randGenerator.Contains(rn)) && randGenerator.Count <= 7)
randGenerator.Add(rn);
}
while (randGenerator.Count <= 7);
return randGenerator;
}
And for method two, assuming you have the numbers already generated and stored in a list or array of numbers, you can do the following ::
private void runArgs()
{
//==============Already have the numbers? Loop through them and compare==============
foreach (int i in myRandArr)
{
if (numIsMatch(i) == true)
{
lista1.Add(i);
}
}
lista1.ForEach(delegate (int num)
{
Console.WriteLine(string.Concat("The numbers that match are ", num));
});
}
And to compare your numbers to see if they are a match, you could do something like this ::
//==============Check is numbers are a match==============
private bool numIsMatch(int inValue)
{
foreach (int ii in myArrNums)
{
if (ii.Equals(inValue))
return true;
else
continue;
}
return false;
}
If you have any questions, I will get back to you tomorrow as it is rather late here now. Hope this helps.

Related

How to set a number of indexes in an array to compare them and return the smallest value

Okay, so basically, I have something to do for class and can't get my head around it, most of my code is done and I just need a way to put a minimum and maximum so my code compares the numbers in the array and returns the smallest value.
The code asks what index the user chooses 2 numbers(0 to 3) and then, if the users chooses 1 and 2, the code has to compare the numbers 1 and 2 and return the smallest value.
class Program
{
static int FindSmallestValue(int[] array, int indexMin, int indexMax)
{
int minimum = array[indexMin];
for (int i = 0; i <= indexMax; i++)
{
if (array[i] < minimum)
{
minimum = array[i];
}
}
Console.WriteLine("The smallest value is {0}", minimum);
return minimum;
}
static void Main(string[] args)
{
int[] array = { 64, 28, 42, 37 };
Console.WriteLine("Input the first index(0 à 3)");
int indexMin = int.Parse(Console.ReadLine());
Console.WriteLine("Input the second index(0 à 3)");
int indexMax = int.Parse(Console.ReadLine());
FindSmallestValue(array, indexMin, indexMax);
}
}
As #FrankM_DN said, Your code starting for loop from 0th index. Instead of starting from 0, start for loop from minIndex.
for(int i = indexMin; i <= indexMax; i++)
{
... //Your code goes here
}
If you are using C# 8.0 or higher version you can do it using range operator i.e ..
var minFromSlicedArray = array[indexMin..^indexMax].Min();
.Net Fiddle

In my class i have to creating a method to find multiple maximum numbers in an array C#

In my class i have to create a method that will find multiple maximum numbers within an array. the user will input how many maximum numbers they are wanting and then the code should display all those numbers. if i select 2 this code will show me the 2 maximum numbers but if im wanting more it just doesnt work. i was trying to search the array for the maximum number and then have it display the outcome and then change that element to 0 and than repeat the loop until it hits that number (userinput). im soo frustrated can someone help me please
public static int FindingMaxNum(int[] arr, int max)
{
int userinput;
Console.Write("Enter the number of maximum values: ");
userinput = Convert.ToInt32(Console.Read());
int i = 0;
int c = 0;
for (i = 0; i < arr.Length; i++)
{
if (arr[i] >= max)
{
max = arr[i];
c++;
while (c <= userinput)
{
Console.WriteLine(max);
arr[i] = 0;
break;
}
}
}
return -1;
}
If I understand correctly, you want to get some number of items from an array whose values are greater than all the others in the array.
If so, something like this modified version of your method may do the trick:
public static void WriteMaxNum(int[] arr)
{
if (arr == null)
{
Console.WriteLine("The array is null");
return;
}
if (arr.Length == 0)
{
Console.WriteLine("The array is empty");
return;
}
int count = arr.Length;
int numMaxValues;
// Get number of max values to return from user
do
{
Console.Write("Enter the number of maximum values (1 - {0}): ", count);
} while (!int.TryParse(Console.ReadLine(), out numMaxValues) ||
numMaxValues < 1 ||
numMaxValues > count);
// Output the max values
Console.Write("The {0} max values are: ", numMaxValues);
Console.WriteLine(string.Join(", ", arr.OrderByDescending(i => i).Take(numMaxValues)));
}
Usage
static void Main(string[] args)
{
var myArray = new[] { 1, 9, 4, 8, 2, 5, 0, 7, 6, 3 };
WriteMaxNum(myArray);
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
Simple solution with average complexity O(nlogn):
Sort the array first then print the last N nos.
int[] arr = new int[]{-5,-69,1250,24,-96,32578,11,124};
Array.Sort(arr);
int n=3;
for(int i=arr.Length-1;i>=0 && n>0 ;--i){
n--;
Console.WriteLine(arr[i]);
}
Now coming to your code, there are multiple problems. First there is no need to take 'max' as parameter in your function. Second you are looping only arr.Length times once. There should be nested loop, outer one of which has to run userInput times and inner on has to iterate over all the values. Third you should initialize to extracted value position to minimum value so that the method works for negative numbers too.
Refined code:
for(int i=0;i<userinput;++i){
int max = int.MinValue,pos=-1;
for(int j=0;j<arr.Length;++j){
if(max<arr[j]){
pos = j;
max = arr[j];
}
}
arr[pos] = int.MinValue;
Console.Write(max+",");
}

Sum of Numbers as Distinct Primes

//List Style
using System;
using System.Collections.Generic;
using System.Linq;
public class pr{
static public void Main (){
int n, i, j, k, l, sum,flag = 0;
//int sum = i+j;
//int k = (n-i);
//int l = (n-j);
//System.Console.WriteLine ("Enter a number");
//n = Convert.ToInt32 (Console.ReadLine());
//List <int> primes = new List <int>(); //list to handle the numbers
//HashSet <int> myPrimes = new HashSet <int> (primes);
System.Console.WriteLine ("Enter a number");
n = Convert.ToInt32 (Console.ReadLine());
//myPrimes.Add(n);
//myPrimes.Add(i);
//myPrimes.Add(j);
// var count = string.Join(", ", primes);
//System.Console.WriteLine("The value of n is {0}",myPrimes);
for(i=3; i<n/2; i++){
for(j=3; j<n/2; j++){
if(checkPrime(i) == 1){
if(checkPrime(j) == 1){
if (checkPrime(n-i) == 1){
if (checkPrime(n-j) == 1){
//if(i == j){
//sum = i+j;
System.Console.WriteLine("{0}={1}+{2}\n",n,i,n-i);
//}
}
}
}
}
if (flag == 0 && (n-i) <= 0 && (n-j) <= 0){ //check to avoid dupes
if (n <= 0 && i <= 0 && j <= 0){
Console.Write("{0}\n",n);
}
}
}
}
}
public static int checkPrime(int n){
int i, j, flag = 1;
for (i = 2; i<=(Math.Sqrt(n)); i++){
for (j = 2; j<=(Math.Sqrt(n)); j++){
if (n%i == 0 && n%j == 0 ){ //even number check
i++;
j++;
flag = 0;
}
}
}
return flag;
}
}
So I have been experimenting with this for a while now. I cant seem to print all possible solutions. For example for 24 I am able to print 7+17 but not 2+5+17. There are also some answers being repeated and this might have to do with the fact that I dont have duplicate checks. I tried to push the integers in a list and then use a hashset to only have distinct integers but I got stuck and tried to brute force it. All the numbers to be printed are supposed to be distinct prime integers. I dont understand how to print all distinct numbers and is there an elegant way to print out all the possible.
Thanks for the help!
Don't know if it's elegant enough for you, but I've just mashed a dirty way to make it work:
static void Main()
{
Console.WriteLine("Enter a number");
var numberToSum = Convert.ToInt32(Console.ReadLine());
var primesInRange = GetPrimesUpTo(numberToSum);
var foundSolutions = primesInRange.SubSetsOf().Where(prime => prime.Sum() == numberToSum);
foreach (var solution in foundSolutions.ToList())
{
var formatOperation = solution
.Select(x => x.ToString())
.Aggregate((a, n) => a + " + " + n) + " = " + numberToSum;
Console.WriteLine(formatOperation);
}
Console.ReadLine();
}
public static IEnumerable<int> GetPrimesUpTo(int end)
{
var primes = new HashSet<int>();
for (var i = 2; i <= end; i++)
{
var ok = true;
foreach (var prime in primes)
{
if (prime * prime > i)
break;
if (i % prime == 0)
{
ok = false;
break;
}
}
if (ok)
primes.Add(i);
}
return primes;
}
public static IEnumerable<IEnumerable<T>> SubSetsOf<T>(this IEnumerable<T> source)
{
if (!source.Any())
return Enumerable.Repeat(Enumerable.Empty<T>(), 1);
var element = source.Take(1);
var haveNots = SubSetsOf(source.Skip(1));
var haves = haveNots.Select(set => element.Concat(set));
return haves.Concat(haveNots);
}
I've found your solution quite dirty so I divided the problem to be more understandable. GetPrimesUpTo returns all prime number from 2 to the number you've provided in the input, SubSetsOf returns combination of numbers that summed up equals the input number you've provided and finally the foreach in Main produces formatted output that is easy on the eye. Hope it helps!
Providing that you have collection of primes and IsPrime method
private static int[] primes = new[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 };
private static bool IsPrime(int value) {
return primes.Contains(value);
}
You can implement recoursive solution
private List<List<int>> ToListOfPrimes(int value, List<int> parts = null) {
if (null == parts)
parts = new List<int>();
List<List<int>> result = new List<List<int>>();
if (value == 0) {
result.Add(parts.ToList());
return result;
}
int minPrime = parts.Count <= 0 ? 0 : parts[parts.Count - 1];
if (value <= minPrime)
return result;
// not that efficient: binary search will be a better choice here
for (int i = 0; i < primes.Length; ++i) {
int p = primes[i];
if (p <= minPrime)
continue;
else if (p > value)
break;
var list = parts.ToList();
list.Add(p);
var outcome = ToListOfPrimes(value - p, list);
foreach (var solution in outcome)
result.Add(solution);
}
return result;
}
Test
var result = ToListOfPrimes(28);
string report = String.Join(Environment.NewLine, result
.Select(line => String.Join(", ", line)));
Console.Write(report);
Outcome (28)
2, 3, 5, 7, 11
2, 3, 23
2, 7, 19
3, 5, 7, 13
5, 23
11, 17
For 24
2, 3, 19
2, 5, 17
5, 19
7, 17
11, 13
If you really want to implement it in other languages just throw your solution to rubbish bin. You should be more explicit about what is happening during execution. Nested for loops with multiple if statements are not explicit at all. What's even worse in the sample - you'll need to add new for loop every time you want more numbers in the sum. I do believe it's hard to understand it for a novice, but I find recursion the only way to go here.
See for yourself:
it's hard to say why output of your program is wrong, because of the logic
Variables should be named meaningfully so you know what they store instead of blind guessing.
Your checkPrime method returns int even though you return 0 or 1 so it should really return bool type
Use debugger and a piece of paper to understand how recursion works either in my previous answer or the one provided by Dmitry Bychenko

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());

C# Dice Times each number is rolled

I've created a Dice program which rolls a dice dependant on how many times the user wishes to roll. The problem I'm having is being able to calculate how many times each number appears.
Example. Roll Twice - Number is 5.
Number is 4.
I want to be able to count that a 4 and a 5 has being rolled and display it back to the user.
My Code so far
using System;
namespace Dice
{
class Dice
{
private Random randy;
int total;
public static void Main()
{
Dice myDice = new Dice();
myDice.randy = new Random();
Console.Clear();
myDice.manyThrow();
myDice.throwDice();
Console.ReadKey();
}
//*******************************************************
public void throwDice()
{
double count = 0;
while(count != total)
{
count++;
Console.WriteLine("Throw No " + count + " is " + oneThrow());
}
}
//*******************************************************
public int oneThrow()
{
return randy.Next(6) + 1; // pick a number from 1 to 6 and return this
}
public int manyThrow()
{
Console.Write("How many times do you want to roll\t");
total = Convert.ToInt32(Console.ReadLine());
return total;
}
public void countEm()
{
// This is where I intend to place the code
}
}
}
I've being trying to solve this for hours.
Add an array to count roll results:
using System;
namespace Dice
{
class Dice
{
private Random randy;
int total;
int [] rolls = new int[7];
public static void Main()
{
Dice myDice = new Dice();
myDice.randy = new Random();
Console.Clear();
myDice.manyThrow();
myDice.throwDice();
myDice.countEm();
Console.ReadKey();
}
//*******************************************************
public void throwDice()
{
double count = 0;
while (count != total)
{
count++;
Console.WriteLine("Throw No " + count + " is " + oneThrow());
}
}
//*******************************************************
public int oneThrow()
{
var result = randy.Next(6) + 1; // pick a number from 1 to 6 and return this
this.rolls[result]++;
return result;
}
public int manyThrow()
{
Console.Write("How many times do you want to roll\t");
total = Convert.ToInt32(Console.ReadLine());
return total;
}
public void countEm()
{
for (int i = 1; i<7; i++)
{
Console.WriteLine("{0} rolled {1} times", i, rolls[i]);
}
}
}
}
Try this:
static int[] counts = new int[6];
And in oneThrow():
int result = randy.Next(6);
counts[result]++;
return result + 1;
Then in countEm():
for (int i = 0; i < counts.Length; i++)
{
Console.WriteLine("{0}: {1}", i + 1, counts[i]);
}
Keep an array of the possible outcomes count.
class Dice
{
private Random randy;
private int total;
private static const int NUM_SIDES = 6;
private int[] counts;
public Dice()
{
randy = new Random();
counts = new int[ NUM_SIDES ];
}
public static void Main()
{
Dice myDice = new Dice();
Console.Clear();
int throws = myDice.manyThrow(); // need to save the number of throws
myDice.throwDice( throws );
countEm();
Console.ReadKey();
}
public void throwDice( int throws )
{
double count = 0;
while(count != throws)
{
count++;
int result = oneThrow();
counts[ result - 1 ]++; // NOTE: result-1 because arrays are 0-based.
Console.WriteLine("Throw No " + count + " is " + oneThrow());
}
}
// ...
public void countEm()
{
for( int i = 0; i < counts.Count; ++i )
Console.WriteLine( (i+1) + " thrown " + counts[i] + " times." );
}
If you just want to keep track of the count of each number rolled, then you add to your class an array of integers to store the count of each number rolled. The number of the dice roll could be the index into the array.
If you need to keep track of the order of the numbers rolled. Your class could could use a linked list or other ordered list to keep track of the numbers.
This sort of sounds like a homework assignment, so I'll leave the implementation details to the reader :)
Modify the countEM like this:
public void countEm(int numberOfThrows)
{
List<int> Throws = new List<int>(); //Create list, where value of throws will be stored.
for(int i = 0; i < numberOfThrows) //Loop as many times as are given by parameter.
{
Throws.Add(OneThrow()); //Add return value of throw to the list.
}
//Show values in Throws list.
foreach(var diceValue in Throws)
{
Console.WriteLine(string.Format("Value of throw: {0}", diceValue ));
}
}
coutEM should be called with the number of times you want to throw like:
countEM(5);
Above represents 5 throws. The result for example could be filled with:
1, 4, 6, 3, 4

Categories

Resources