how to check if an array has the same number - c#

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;
}
}

Related

breaks while loop when all die rolls the same number

using System;
using System.Collections.Generic;
namespace AnyDice
{
class Program
{
static void Main(string[] args)
{
int diceSides;
int rollDie;
int count = 0;
bool keepRolling = true;
List<int> num = new List<int>();
Random random = new Random();
Console.Write("Write the number of sides of your die: ");
diceSides = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Type the numbers of the die");
for (int i = 0; i < diceSides; i++)
{
int rank = 1 + i;
Console.Write(rank + "~~> ");
num.Add(Convert.ToInt32(Console.ReadLine()));
}
num.Sort();
Console.WriteLine("\nHere's the die and its contents");
for (int i = 0; i < num.Count; i++)
{
Console.Write("[");
Console.Write(num[i]);
Console.Write("]");
}
Console.WriteLine("\nHow many times do you want to roll at once");
rollDie = Convert.ToInt32(Console.ReadLine());
while (keepRolling)
{
for (int i = 0; i < rollDie; i++)
{
Console.Write("[");
Console.Write(num[random.Next(num.Count)]);
Console.Write("]");
count++;
}
Console.ReadLine();
}
Console.WriteLine("It took you " + count + " attempts");
Console.ReadLine();
}
}
}
For example if (4,4,4,4) is rolled or (2,2) in any "n" number of column the while loop breaks.
I thought of storing each die rolled value in another arraylist and comparing each value in it. If its all equal then it breaks.. but I have no clue on how to implement it.
We have Linq. It lives in the System.Linq namespace and this might help you.
I'll should two ways of checking if all die are the same:
int first = dies.First();
if (dies.All(i => i == first))
{
// break if all are equals to the first die
}
Or using Distinct we can filter out any copies.
if (dies.Distinct().Count() == 1)
{
// if we only have unique items and the count is 1 every die is the same
}
I am not 100% sure I understand your requirement, but in any case, you should write a separate function that returns a flag indicating whether the array is in a state that should trigger a break.
bool KeepRolling(int[] num)
{
for (int i=0; i<num.Length; i++)
{
if (num[i] >= i) return false;
}
return true;
}
Then just call it from within your loop:
keepRolling = KeepRolling(num);
while (keepRolling)
{
rolls.Clear();
for (int i = 0; i < rollDie; i++)
{
var firstRoll = num[random.Next(num.Count)];
rolls.Add(firstRoll);
Console.Write(firstRoll + " ");
count++;
}
if (rolls.Distinct().Count() == 1)
{
Console.WriteLine("It took you " + count + " attempts");
keepRolling = false;
break;
}
Console.ReadLine();
}

C#, Trying to pull prime numbers from generated array all I get is 0

The program will generate a sequence of randomly chosen numbers between 1 – 100. The sequence will consist of 20 elements.
Your program should display the sequence once it is generated.
Then, it will display all prime numbers within this sequence.
The code so far:
class Program
{
int[] rnum = new int[100];
int[] selecting = new int[20];
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Numbers();
myProgram.PrimeN();
Console.ReadLine();
}
public void Numbers()
{
int[] rnum = new int[100];
// Filling the array with values 1 to 100:
for (int i = 0; i < rnum.Length; i++)
{
rnum[i] = i + 1;
}
// Shuffling the elements of the array:
Random rnd = new Random();
for (int i = 0; i < rnum.Length; i++)
{
int j = rnd.Next(i, rnum.Length);
int temp = rnum[i];
rnum[i] = rnum[j];
rnum[j] = temp;
}
// Selecting and presenting 20 numbers:
int[] selecting = new int[20];
for (int i = 0; i < 20; i++)
selecting[i] = rnum[i];
selecting.ToList().ForEach(i => Console.Write(i.ToString() + ", "));
Console.WriteLine();
}
public void PrimeN()
{
List<int> primeNumbers = new List<int>();
for (int i = 0; i < selecting.Length; i++)
{
if (IsPrime(selecting[i]))
{
primeNumbers.Add(selecting[i]);
}
}
Console.Write("Non-Prime Numbers:");
for (int i = 0; i < primeNumbers.Count; i++)
{
Console.Write(primeNumbers[i] + " ");
}
}
bool IsPrime(int number)
{
for (int i = 2; i < Math.Sqrt(number); i++)
{
if (number % i == 0) return false;
}
return true;
}
}
}
You created local variable called selecting inside Numbers() function. Scope of this local variable is within Numbers() function.
When you are trying to read same variable in PrimeN(), it is referring to the globally defined selecting variable.
As there is nothing stored in global selecting variable you are getting 0 as result in primeNumbers array.
To Solve this issue, do not create local variable called selecting inside Numbers() function, use globally defined variable i.e. selecting defined at class level
...
public void Numbers()
{
...
// Selecting and presenting 20 numbers:
//COMMENT BELOW LINE
//int[] selecting = new int[20];
for (int i = 0; i < 20; i++)
selecting[i] = rnum[i]; //This will refer member which is defined globally
selecting.ToList().ForEach(i => Console.Write(i.ToString() + ", "));
Console.WriteLine();
}
The first problem I see, is you are creating local variables, instead of using the instance members you have declared, after your method runs, nothing gets changed... it all happened locally in the method.
Comment out the below lines, you have already declared them
public static void Numbers(int size)
{
//int[] rnum = new int[size];
...
//int[] selecting = new int[20];
Though it could all be reduced to
private static readonly Random _r = new Random();
static void Main(string[] args)
{
var numbers = Generate(100);
var selected = numbers.Take(20).ToArray();
Console.WriteLine("Selected : " + string.Join(", ", selected));
Console.Write("Primes : " + string.Join(",", selected.Where(IsPrime)));
Console.ReadLine();
}
public static int[] Generate(int size)
{
var numbers = Enumerable.Range(1, 100).ToArray();
// Shuffling the elements of the array:
for (var i = 0; i < numbers.Length; i++)
{
var j = _r.Next(i, numbers.Length);
var temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
return numbers;
}
private static bool IsPrime(int number)
{
for (var i = 2; i < Math.Sqrt(number); i++)
if (number % i == 0) return false;
return true;
}
Output
Selected : 92, 79, 1, 44, 83, 48, 70, 49, 80, 19, 27, 65, 50, 40, 20, 10, 68, 25, 9, 28
Primes : 79,1,83,49,19,25,9

Keeping track of rng output values

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

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.

Inputting values for jagged array

Ok, I'm attempting to make a simple program that reads in number of pizzas sold for a given day and then have the user input the type of pizza sold for that day (with this I need to use the Split() with the user input).
I'm having issues populating the columns for my jagged array.
Now, I can get what I have to work for only 1 pizza sold, but anything beyond that it is not taking in my user input for the type of pizzas sold for that day (the column values). It's not reading in the user input as separate items so once I input, it goes to the next line like it's waiting for data instead of moving on. (Since I'm testing this for one day, it would end the program once the user input was read in).
I'm not quite sure where my issue is with my loops putting in my column values, but I'm figuring it has something with reading in the user input and placing that in the column of the jagged array. Any help would be great.
static void Main(string[] args)
{
Greeting();
string[][] pizza = new string[7][];
GetPizzas(pizza);
}
static void Greeting()
{
Write("Welcome to Z's Pizza Report!");
}
static void GetPizzas(string[][] array)
{
int numOfPizza;
string day;
for (int r = 0; r < array.Length; r++)
{
if (r == 0)
{
day = "Monday";
Write("How many total pizzas were there for {0}? ", day);
numOfPizza = int.Parse(ReadLine());
while (numOfPizza < 0)
{
Write("Number cannot be negative. Try Again: ");
numOfPizza = int.Parse(ReadLine());
}
array[r] = new string[numOfPizza];
Write("Enter all the pizzas for {0}, seperated by spaces: ", day);
for (int c = 0; c < array[r].Length; c++)
{
string total = ReadLine();
array[c] = total.Split(' ');
while (array[r] != array[c])
{
Write("Input does not match number needed. Try Again: ");
total = ReadLine();
array[c] = total.Split(' ');
}
}
}
else if (r == 1)
{
day = "Tuesday";
}
else if (r == 2)
{
day = "Wednesday";
}
else if (r == 3)
{
day = "Thursday";
}
else if (r == 4)
{
day = "Friday";
}
else if (r == 5)
{
day = "Saturday";
}
else
{
day = "Sunday";
}
}
}
The code seems overly complicated to me, but does something like this help? Oh, notice that I'm using the built-in DayOfWeek enum to parse the friendly name for the day. The difference between this and yours is that Sunday is day 0.
This line of code casts the integer to the enum, and then gets the string value:
var dayOfWeek = ((DayOfWeek)i).ToString();
I also added a helper function to get an integer from the user. It takes in a prompt string, an error string, an optional min value and an optional max value, then it prompts the user for an integer and won't return until they enter a valid value:
static int GetIntFromUser(string prompt, string error,
int minValue = int.MinValue, int maxValue = int.MaxValue)
{
int result;
if (!string.IsNullOrEmpty(prompt)) Console.Write(prompt);
while (!int.TryParse(Console.ReadLine(), out result)
|| result < minValue || result > maxValue)
{
if (!string.IsNullOrEmpty(error)) Console.Write(error);
}
return result;
}
The rest of the code looks like:
static void Main(string[] args)
{
var pizzasSold = new string[7][];
GetPizzas(pizzasSold);
for (int i = 0; i < pizzasSold.Length; i++)
{
var dayOfWeek = ((DayOfWeek)i).ToString();
Console.WriteLine("You sold {0} pizzas on {1}: {2}",
pizzasSold[i].Length, dayOfWeek, string.Join(", ", pizzasSold[i]));
}
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
static void GetPizzas(string[][] array)
{
for (int r = 0; r < array.Length; r++)
{
var dayOfWeek = ((DayOfWeek)r).ToString();
var numPizzasSold =
GetIntFromUser($"How many total pizzas were there for {dayOfWeek}? ",
"Number cannot be negative. Try Again: ", 0);
Console.Write($"Enter all the pizzas for {dayOfWeek}, seperated by spaces: ");
var pizzasSold = Console.ReadLine().Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
while (pizzasSold.Length != numPizzasSold)
{
Console.Write($"Input does not match number needed. Try Again: ");
pizzasSold = Console.ReadLine().Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
}
array[r] = pizzasSold;
}
}
using System;
namespace ConsoleApp12
{
class Program
{
static void Main(string[] args)
{
int[][] n = new int[3][];
int i;
n[0] = new int[4];
n[1] = new int[3];
n[2] = new int[2];
// n[1] = new int[] { 1, 2, 3 };
// Console.WriteLine("enter the rollno");
for (i = 0; i < 4; i++)
{
n[0][i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < 3; i++)
{
n[1][i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < 2; i++)
{
n[2][i] = Convert.ToInt32(Console.ReadLine());
}
// for (i = 0; i < 3; i++)
// {
// n[i][j] = Convert.ToInt32(Console.ReadLine());
//}
for (i = 0; i <4; i++)
{
Console.Write(n[0][i] + " ");
}
Console.WriteLine();
for (i = 0; i < 3; i++)
{
Console.Write(n[1][i] + " ");
}
}
}
}

Categories