Keeping track of rng output values - c#

I've managed a random number generator to model rolling a dice 300 times. Now I want to compare the results to see how truly random it was.
class RngPract
{
public void RunProgram()
{
int i;
Random rollingDie = new Random ();
Console.WriteLine("Numbers 1 to 6");
for (i =0; i < 200; i++)
{
Console.WriteLine("Next is: {0}", rollingDie.Next(1,7));
int a = 0;
switch (rollingDie.Next())
{
case 1:
a++;
Console.WriteLine("1 appears:{0}",a);
break;
}
}
}
}
I am having trouble getting my switch statement to execute anything.

You can store the random generated values in a list and then query the occurrences.
Occurrence of each number can be queried by Grouping by the value, and finding the number of items in each group.
For example,
public void RunProgram()
{
int i;
Random rollingDie = new Random ();
Console.WriteLine("Numbers 1 to 6");
var list = new List<int>();
for (i =0; i < 200; i++)
{
var newItem = rollingDie.Next(1,7);
list.Add(newItem);
Console.WriteLine("Next is: {0}", newItem);
}
foreach(var item in list.GroupBy(x=>x))
{
Console.WriteLine($"{item.Key} {item.Count()}");
}
}
If you need to provide a live update (each time random generates a number) of the occurance, you could do the following.
public void RunProgram()
{
int i;
Random rollingDie = new Random ();
Console.WriteLine("Numbers 1 to 6");
var list = new List<int>();
for (i =0; i < 200; i++)
{
var newItem = rollingDie.Next(1,7);
list.Add(newItem);
Console.WriteLine("Next is: {0}", newItem);
var occurance = FindOccurance(list,newItem);
Console.WriteLine($"{newItem} has occured {occurance} times");
}
}
public int FindOccurance(List<int> list,int currentItem)
{
return list.Count(x=>x == currentItem);
}

Related

Lottery program that generates 6 random numbers between 1 and 59 C#

I have created a simple program which randomly generates 6 winning numbers. While the program works, I would also like for it to ensure that the same number isn't outputted twice as well as sorting them into numerical order when outputted. How would I go about doing such a thing while sticking to similar techniques already used? My code is down below. Any help is very much appreciated.
int temp;
int[] lotto = new int[6];
Random rand = new Random();
for (int i = 0; i < 6; i++)
{
temp = rand.Next(1, 59);
lotto[i] = temp;
}
Console.Write($"The lotterry winning numbers are: ");
for (int i = 0; i < 6; i++)
{
Console.Write(lotto[i] + " ");
}
Console.ReadKey();
Based on a Fisher-Yates shuffle, but saves some work because we know we don't need all the values (if we only need 6 values out of 10 million potentials, we only need to take the first six iterations of the fisher-yates algorithm).
public IEnumerable<int> DrawNumbers(int count, int MaxNumbers)
{
var r = new Random(); //ideally, make this a static member somewhere
var possibles = Enumerable.Range(1, MaxNumbers).ToList();
for (int i = 0; i < count; i++)
{
var index = r.Next(i, MaxNumbers);
yield return possibles[index];
possibles[index] = possibles[i];
}
}
var lottoNumbers = DrawNumbers(6, 59);
Console.Write("The lotterry winning numbers are: ");
Console.WriteLine(string.Join(" ", lottoNumbers.OrderBy(n => n)));
See it work here:
https://dotnetfiddle.net/NXYkpU
You can use Linq to create sequence [1..59] and order it by random to shuffle it.
Random rand = new Random();
var winners = Enumerable.Range(1, 59)
.OrderBy(x => rand.Next())
.Take(6)
.OrderBy(x => x)
.ToList();
Console.WriteLine(String.Join(" ", winners));
int temp;
int[] lotto = new int[6];
Random rand = new Random();
int i = 0;
while(i < 6)
{
temp = rand.Next(1, 59);
//check if lotto contains just generated number, if so skip that number
bool alreadyExist = false;
foreach (int item in lotto)
{
if (item == temp)
{
alreadyExist = true;
break;
}
}
if (alreadyExist)
continue;
lotto[i] = temp;
i++;
}
Console.Write($"The lotterry winning numbers are: ");
// Sort array in ascending order.
Array.Sort(lotto);
for (int j = 0; j < 6; j++)
{
Console.Write(lotto[j] + " ");
}
Console.ReadKey();
I would probably do it Dmitri's way because it is quick and obvious and performance isn't that important with an array this size.
But just for fun, this is slightly more efficient.
IEnumerable<int> GetNumbers(int min, int max, int count)
{
var random = new Random();
var size = max - min + 1;
var numbers = Enumerable.Range(min, size).ToArray();
while (count > 0)
{
size--;
var index = random.Next(0, size);
yield return numbers[index];
numbers[index] = numbers[size];
count--;
}
}
This solution creates an array containing all possible values and selects them randomly. Each time a selection is made, the array is "shrunk" by moving the last element to replace the element that was chosen, preventing duplicates.
To use:
var numbers = GetNumbers(1, 59, 6).ToList();
foreach (var number in numbers.OrderBy(x => x))
{
Console.WriteLine(number);
}

Find the first uneven number in random array in c#

i must create array and fill it with random numbers , between 1-100. From there, i must find the 1st uneven number and print it.
Also have to print 0 if no uneven numbers are in the array.
Heres what i did:
int[] tab = new int[10];
int[] uneven = new int[tab.Length];
int i;
for (i = 0; i < tab.Length; i++)
tab[i] = new Random().Next(100) + 1;
do
{
uneven[i] = tab[i];
} while (tab[i] % 2 == 1);
Console.WriteLine(uneven[0]);
So my reasoning is that i add uneven numbers in uneven[i] as long as tab[i] is uneven,then print the first element of the array.
However, i get "out of bonds exception".
Thank you in advance for any help.
Your for loop set i to 10 which is outside the bounds of the array. You need to re-set it to 0 before the do loop. Also, you need to increment i.
i = 0;
do
{
uneven[i] = tab[i];
i++;
} while (tab[i] % 2 != 0);
By the time your do loop starts your "i" variable is stuck on 10. Arrays start at 0 so it only goes up to 9 which is why you're seeing the out of bounds exception. Here's a small example of what you're trying to achieve:
int[] tab = new int[10];
var rnd = new Random();
// Create 10 random numbers
for (int i = 0; i < tab.Length; i++)
{
tab[i] = rnd.Next(100) + 1;
}
// Find the first uneven number
bool found = false;
for (int i = 0; i < tab.Length; i++)
{
if (tab[i] % 2 != 0)
{
Console.WriteLine(tab[i]);
found = true;
break;
}
}
// Didn't generate an uneven number?
if (!found)
{
Console.WriteLine("Nothing found");
}
This creates an array[] with random numbers assigned to each element.
The second for loop checks if the number is even/odd then breaks the loop if it is odd.
static void Main(string[] args)
{
int[] numList = new int[100];
var rand = new Random();
Console.WriteLine(rand.Next(101));
for (int i = 0; i <= 99; i++)
{
numList[i] = rand.Next(101);
Console.WriteLine($"Element; {i}: {numList[i]}");
}
for (int i = 0; i <= 99; i++)
{
int num = numList[i];
if (num / 2 != 0)
{
Console.WriteLine($"The first uneven number is: {num} in element: {i}");
break;
}
if(i == numList.Count())
{
Console.WriteLine("All numbers are even");
break;
}
}
Console.ReadLine();
}

Read input different menu c#

Im trying to make a menu where an array will store input from a user (enterednumber 1) and then an admin can check the contents of the array in a different menu(enterednumber 9), but I can't seem to make it readable inside the admin menu.... I've left out the methods for login & startmenu, that part works. - the relevant part of the code currently looks like this:
static void Main(string[] args)
{
while (true)
{
int enteredNumber;
int[] myArray = new int[10];
Startmenu();
enteredNumber = Convert.ToInt32(Console.ReadLine());
if (enteredNumber == 1)
{
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Insert Number:");
myArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Clear();
Console.WriteLine("blabla");
Thread.Sleep(2000);
Console.Clear();
}
if (enteredNumber == 9)
{
if (Login(1234, 3) == true)
{
foreach (int number in myArray)
{
Console.WriteLine(number);
}
}
}
}
}
try this:
static void Main(string[] args)
{
int[] myArray = new int[10];
while (true)
{
int enteredNumber;
// int[] myArray = new int[10]; //when you create a new int array , the array not contain values.
Startmenu();
enteredNumber = Convert.ToInt32(Console.ReadLine());
if (enteredNumber == 1)
{
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Insert Number:");
myArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Clear();
Console.WriteLine("blabla");
Thread.Sleep(2000);
Console.Clear();
}
if (enteredNumber == 9)
{
if (Login(1234, 3) == true)
{
foreach (int number in myArray)
{
Console.WriteLine(number);
}
}
}
}
}
when you create a new int array, the array contains no values, you have creation of an array within the while loop, then, int [] myArray = new int [10]; this empty when you start the cycle again, place the creation before starting the loop.

how to check if an array has the same number

I wanted this program to print out random numbers (1-6) in Columns forever until all the rows of each columns have the exact same number. If the user enters 5 forexample, it will print out 5 columns of random numbers (1-6) until each row of that 5 columns are the same . I am stuck, I don't know how to check all the elements of the array, whether or not they are all the same with one another.
namespace Dice_Roll_2._0
{
class Program
{
static void Main(string[] args)
{
int userinput = Convert.ToInt16(Console.ReadLine());
Random Dice = new Random();
bool search = true;
while (search)
{
var output = string.Empty;
int[] numberofdice = new int[userinput+1];
for (int i = 1; i <=userinput; i++)
{
numberofdice[i] = Dice.Next(1, 7);
output += numberofdice[i];
if (i < userinput )
{
output += "\0";
}
if (numberofdice[i-1] == numberofdice[i])
{
search = false;
}
}
Console.WriteLine(output);
}
Console.ReadLine();
}
}
}
With the Linq namespace, you can do a Distinct() on your array of columns and when the Count() of the Distinct() equals 1, then all the columns are the same and you can stop rolling.
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.Write("Enter number of columns: ");
int userinput = Convert.ToInt16(Console.ReadLine());
int[] columns = new int[userinput];
Random Dice = new Random();
bool search = true;
DateTime start = DateTime.Now;
while (search)
{
for (int i = 0; i < columns.Length; i++)
{
columns[i] = Dice.Next(1, 7);
}
if (columns.Distinct().Count() == 1)
{
Console.WriteLine("All columns match with the value of {0}", columns[0]);
Console.WriteLine("It took {0} to get all columns to match", DateTime.Now.Subtract(start));
search = false;
}
}
}
}
Results (Time span and value will vary on each run):
Enter number of columns: 5
All columns match with the value of 4
It took 00:00:00.0156260 to get all columns to match
Fiddle Demo is limited to 7 columns.
Array indexing should begin with 0. To check that all elements are the same, you can use a loop to compare each element with the first.
static void Main(string[] args)
{
int userinput = Convert.ToInt16(Console.ReadLine());
Random Dice = new Random();
int[] numberofdice = new int[userinput + 1];
while(true)
{
var output = string.Empty;
// Generate the userinput random numbers
// as well as output string
for(int i = 0; i < userinput; i++)
{
numberofdice[i] = Dice.Next(1, 7);
output += numberofdice[i];
}
Console.WriteLine(output);
// Check that they are all same by comparing with first
bool same = true;
int first = numberofdice[0];
for(int i = 1; i < userinput; i++)
{
if(numberofdice[i] != first)
{
same = false;
break;
}
}
// If all were the same, stop.
if(same)
break;
}
}

Create 10 Unique numbers and save to array

I am trying to generate 10 unique random numbers and save it to an array.
Here is my code, but there is run-time error, but I dunno how.
Can someone help me please ?
static void Main(string[] args)
{
int [] generatedNum = new int[10];
bool duplicated;
int tempo;
Random random = new Random();
// Create first number
generatedNum[0] = random.Next(1, 25);
for (int i = 1; i < 10; i++)
{
tempo = random.Next(0, 25);
do
{
duplicated = false;
foreach (int x in generatedNum)
{
if (x == tempo)
duplicated = true;
}
if (duplicated == true)
tempo = random.Next(0, 25);
} while (duplicated == true);
// Save unique number to array
generatedNum[i] = tempo;
}
// To check the number saved
foreach (int i in generatedNum)
{
Console.WriteLine("{0}", generatedNum[i]);
}
}
This may helps:
public List<int> GetNumber()
{
Random random = new Random();
List<int> values = new List<int>();
values.Add(random.Next(0, 25));
while (values.Count < 10)
{
int newValue;
do
{
newValue = random.Next(0, 25);
} while (values.Contains(newValue));
values.Add(newValue);
}
return values;
}
To have x unique items out of an array of y, you need a shuffle bag.
You put your numbers 1-25 in a bag, shuffle it and then take the first 10 items. You will now have 10 random items between 1 & 25.
Your last foreach loop is invalid. i is the value, not index, so you can write it directly:
// To check the number saved
foreach (int i in generatedNum)
{
Console.WriteLine("{0}", i);
}
Change
foreach (int i in generatedNum)
{
Console.WriteLine("{0}", generatedNum[i]);
}
to
for (int j=0;j<generatedNum.Length;j++)
{
Console.WriteLine("{0}", generatedNum[j]);
}
Would this work
If you are allowed to use Linq you can try something like this
You can set the range you want
Random rnd = new Random();
var randomNumbers = Enumerable.Range(1, 100)
.Select(x => new { val = x, order = rnd.Next() })
.OrderBy(i => i.order)
.Select(x => x.val)
.Take(10).ToArray();
static void Main(string[] args)
{
var generatedNum = new List<int>();
var random = new Random();
while (generatedNum.Count < 10)
{
var tempo = random.Next(0, 25);
if (generatedNum.Contains(tempo)) continue;
generatedNum.Add(tempo);
}
foreach (var i in generatedNum)
{
Console.WriteLine("{0}", i);
}
}
And you problem was here no?
// To check the number saved
foreach (int i in generatedNum)
{
Console.WriteLine("{0}", generatedNum[i]);
}
/*try this,i used an arraylist to store the digits
using System;
using System.Collections;
public class SamplesArrayList
{
public static void Main()
{
// Creates and initializes a new ArrayList.
ArrayList values = new ArrayList();
Random random = new Random();
values.Add(random.Next(0, 25));
while (values.Count < 10)
{
int newValue;
do
{
newValue = random.Next(0, 25);
} while (values.Contains(newValue));
values.Add(newValue);
}
PrintValues(values);
}
public static void PrintValues(IEnumerable myList)
{
foreach (Object obj in myList)
Console.Write(" {0}", obj);
Console.WriteLine(myList);
}
}

Categories