C# how to include 0 in Roulette Simulation? - c#

So I want to simulate a roulette to proof that the House always wins.
I’m almost done but I stumbled upon a problem. I’m able to enter how many times to roll and it works fine. I get different numbers and it also tells me if red or black.
However the number 0 won’t show up in the results. I don’t know how to fix this, the code looks fine to me.
Code:
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
int[] Null = new int[1] { 0 };
int[] Rote = new int[18] { 1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36 };
int[] Schwarze = new int[18] { 2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35 };
// 0 ohne Tischlimit
var list = new List<int>();
list.AddRange(Rote);
list.AddRange(Schwarze);
list.AddRange(Null);
Console.WriteLine("Wie oft soll gespielt werden?");
int Anzahl = Convert.ToInt32(Console.ReadLine());
Random zufall = new Random();
for (int i = 0; i < Anzahl; ++i)
{
int number = list[zufall.Next(0, list.Count - 1)];
if (Rote.Contains(number))
{
Console.WriteLine("Rot" + number);
}
if (Schwarze.Contains(number))
{
Console.WriteLine("Schwarz" + number);
}
if (Null.Contains(number))
{
Console.WriteLine("Null" + number);
}
}
Console.ReadLine();
}
}

Ok, the thing is that Random.Next Method (Int32, Int32) uses upper bound as exclusive. So you have 0 as last element of list. And passing list.Count - 1 results in generating values between 0 and list.Count - 2. So the last element of the list is just ignored as you will never generate the last index list.Count - 1. You need to pass list.Count to Next method:
int number = list[zufall.Next(0, list.Count)];
https://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx
The Next(Int32, Int32) overload returns random integers that range
from minValue to maxValue – 1

Related

Custom sorting array - smaller values between larger values

I have an array A with values: {10, 12, 6, 14, 7} and I have an array B with values: {1, 8, 2}
I have sorted the array B in an ascending order and then combined both the arrays in a new array C as shown in the following code -
static void Main()
{
int A[] = {10, 12, 6, 14, 7};
int B[] = {1, 8, 2};
Array.Sort(B);
var myList = new List<int>();
myList.AddRange(A);
myList.AddRange(B);
int[] C = myList.ToArray();
//need values in this order: 10, 1, 12, 2, 8, 6, 14, 7
}
Now I wanna sort the array C this way: 10, 1, 12, 2, 8, 6, 14, 7
The smaller values should be between the larger values, for ex: 1 is between 10 and 12, 2 is between 12 and 8, 6 is between 8 and 14, so on and so forth.
How can I do this in C#?
If recursion is needed, how can I add it to the code?
What I understood from your example is that you are trying to alternate between large and small values such that the small value is always smaller than the number to the left and the right. I wrote an algorithm below to do that however it does not yield the exact same results you requested. However I believe it does meet the requirement.
The straggling 7 is considered the next smallest number in the sequence but there is no number that follows it. Based on your example it appears that is allowed.
To Invoke
int[] A = { 10, 12, 6, 14, 7 };
int[] B = { 1, 8, 2 };
var result = Sort(A, B);
Sort Method
public static int[] Sort(int[] A, int[] B)
{
var result = new int[A.Length + B.Length];
var resultIndex = 0;
Array.Sort(A);
Array.Sort(B);
//'Pointer' for lower index, higher index
var aLeft = 0;
var aRight = A.Length-1;
var bLeft = 0;
var bRight = B.Length - 1;
//When Items remain in both arrays
while (aRight >= aLeft && bRight >= bLeft)
{
//Add smallest
if (resultIndex % 2 > 0)
{
if (A[aLeft] < B[bLeft])
result[resultIndex++] = A[aLeft++];
else
result[resultIndex++] = B[bLeft++];
}
//Add largest
else
{
if (A[aRight] > B[bRight])
result[resultIndex++] = A[aRight--];
else
result[resultIndex++] = B[bRight--];
}
}
//When items only in array A
while (aRight >= aLeft)
{
//Add smallest
if (resultIndex % 2 > 0)
result[resultIndex++] = A[aLeft++];
//Add largest
else
result[resultIndex++] = A[aRight--];
}
//When items remain only in B
while (bRight >= bLeft)
{
//Add smallest
if (resultIndex % 2 > 0)
result[resultIndex++] = B[bLeft++];
//Add largest
else
result[resultIndex++] = B[bRight--];
}
return result;
}
Result
[14, 1, 12, 2, 10, 6, 8, 7]

assigning values to an array whose length isn't known ahead of time in C# [duplicate]

This question already has answers here:
Array of an unknown length in C#
(11 answers)
Closed 2 years ago.
I am designing a program that asks for the user to input 2 numbers. It then finds the prime factors of each number. The number of prime factors depends on what number the user inputs. I need an array whose number of elements isn't known ahead of time so that I can input the prime factors of one of the numbers into the array of variable length.
int a = -1, b = -1;
string sa, sb;
int GCF = 0;
int LCM = 0;
int temp = 1, tempb = 1;
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
while (aValid == true)
{
for (int i = 0; i < 25; i++)
{
if (a % primes[i] == 0)
{
Console.Write(" ");
Console.Write(primes[i]);
//my attempt below to input current prime factor into variable array
int[] arrb = primes[i];
a = a / primes[i];
}
}
if (a == 1)
{
break;
}
}
You can use List<int> instead of int array.
When declaring a new List you don't need to specify the capacity.
In your code, add the following line above while loop:
List<int> arrb = new List<int>();
Then replace int[] arrb = primes[i]; with
arrb.Add(primes[i]);

How do you realign array data in comparison to another array when the index is out of sync?

I've created a "Choose your Case" game using a cash prize array of all the prize amounts and the case numbers a user can pick. When they pick a number, it tells the user what is in their case. However, at the end it spits out all the cases and what was in each one, and the data is misaligned by one index.
static void Main(string[] args)
{
int[] cashPrizeArray = new int[26] { 0, 1, 2, 5, 10, 20, 50, 100, 150, 200, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 10000, 15000, 20000, 25000, 50000, 75000, 100000, 200000 };
int[] caseArray = new int[26] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 };
Array.Sort(cashPrizeArray);
Random rnd = new Random();
int[] cashPrizeArrayR = cashPrizeArray.OrderBy(x => rnd.Next()).ToArray();
foreach (int i in cashPrizeArrayR)
{
Console.Write("{0} ", i);
}
Console.WriteLine("\n(please ignore the numbers above)\n\n\nDeal or Not!");
Console.Write("Choose a case: 1-26: ");
int userCase = int.Parse(Console.ReadLine());
if (!caseArray.Contains(userCase))
{
Console.WriteLine("\nUnexpected input text.\nThis application will now be terminated.\nPress ENTER to continue...");
Console.ReadLine();
Environment.Exit(0);
}
else
{
Console.WriteLine("You chose case " + userCase);
Console.ReadLine();
}
Console.WriteLine("This case contains...\n$" + cashPrizeArrayR[userCase]);
Console.ReadLine();
Console.WriteLine("\nFor reference, below are the case numbers and their values: ");
Console.ReadLine();
var caseAndPrize = cashPrizeArrayR.Zip(caseArray, (p, c) => new { Prize = p, Case = c });
foreach (var pc in caseAndPrize)
{
Console.WriteLine("Case " + pc.Case + " $" + (pc.Prize));
}
Console.ReadLine();
}
It runs fine, but it outputs the value incorrectly, as if the data column is shifted downwards. Can anyone provide a solution where I have gone wrong? Many thanks.
cashPrizeArrayR[userCase] selects based on index. Have you considered to use instead of int[] a KeyValuePair or an Dictionary?
change this line:
Console.WriteLine("This case contains...\n$" + cashPrizeArrayR[userCase]);
to this:
Console.WriteLine("This case contains...\n$" + cashPrizeArrayR[userCase - 1]);
further suggestion:
replace this:
int userCase = int.Parse(Console.ReadLine());
with
bool validKey = int.TryParse(Console.ReadLine(), out var userCase);
if (!validKey|| !caseArray.Contains(userCase))
{
// <snipped>

How to output lowest number in array (also to see if I'm doing this right)

Back with another C# question.
Here's my current task:
Problem Definition:
A computer program is required to read the daily hours parked by customers. There are 30 entries for customer’s parking hours (integer numbers) stored in a data file ‘hours.txt’. You are required to read the file and store the data in an array. Calculate the highest, lowest and average of the daily parking hours.
Sample Data:
30 parking hours: {8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8}
Highest parking hours = 24
Lowest parking hours = 1
Average parking hours = 9.13
Overall Tasks:
Read the data file ‘hours.txt’ into an array of data type integer
Find highest value
Find lowest value
Calculate the average
Output the array of hours, highest, lowest and average (formatted to 2 decimal places)
Note: Since the topic of “files” is not covered until Session 6, for now, declare your array and assign the numbers as shown below
int[] hoursArray = {8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8};
In session 6 you will need to modify your code so the data is read from the hours.txt file.
So from this I gather I need to run a program that spits out the average, highest, and lowest of the hours entered. Note that it says to use the data from a text file, but further down says that is for a different topic, so I haven't done that. Instead, I had opted for manually entering in the 30 digits.
First question I suppose, is is that right, or is there a way that using
int[] hoursArray = {8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8};
the data is automatically entered without the user manually entering the digits? Not sure if I'm reading the task right.
Second question is here is the code I have done. I can succesfully output the average and highest value, but I don't seem to be able to output the lowest value below 8 (ie, the value of 1 in there). How do I fix this?
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IntsArray
{
class Program
{
static void Main(string[] args)
{
int[] hours;
hours = new int[30];
int[] hoursArray = { 8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8 };
hours[0] = 8;
hours[1] = 24;
hours[2] = 9;
hours[3] = 7;
hours[4] = 6;
hours[5] = 12;
hours[6] = 10;
hours[7] = 11;
hours[8] = 23;
hours[9] = 1;
hours[10] = 2;
hours[11] = 9;
hours[12] = 8;
hours[13] = 8;
hours[14] = 9;
hours[15] = 7;
hours[16] = 9;
hours[17] = 15;
hours[18] = 6;
hours[19] = 1;
hours[20] = 7;
hours[21] = 6;
hours[22] = 12;
hours[23] = 10;
hours[24] = 11;
hours[25] = 23;
hours[26] = 1;
hours[27] = 2;
hours[28] = 9;
hours[29] = 8;
for (int index = 0; index < hours.Length; index++)
{
Console.Write("Enter your hours: ");
hours[index] = int.Parse(Console.ReadLine());
}
int total = 0;
double average = 0;
for (int index = 0; index < hours.Length; index++)
{
total = total + hours[index];
}
average = (double)total / hours.Length;
Console.WriteLine("Average = " + average.ToString("N2"));
int high = hours[0];
for (int index = 1; index < hours.Length; index++)
{
if (hours[index] > high)
{
high = hours[index];
}
}
Console.WriteLine("Highest number = " + high);
int low = hours[0];
for (int index = 0; index > hours.Length; index++)
{
if (hours[index] < low)
{
low = hours[index];
}
}
Console.WriteLine("Lowest number = " + low);
Console.ReadKey();
}
}
}
Thank you in advance :)
For getting the lowest number change following piece of code
for (int index = 0; index > hours.Length; index++)
{
if (hours[index] < low)
{
low = hours[index];
}
}
Console.WriteLine("Lowest number = " + low);
To
for (int index = 0; index < hours.Length; index++)
{
if (hours[index] < low)
{
low = hours[index];
}
}
Console.WriteLine("Lowest number = " + low);
Simply use the Linq extension methods
int[] hours = { 8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8 };
Console.WriteLine("Average = {0:F2}", hours.Average());
Console.WriteLine("Highest number = {0}", hours.Max());
Console.WriteLine("Lowest number = {0}", hours.Min());
Output
Average = 9.13
Highest number = 24
Lowest number = 1

Randomly pick from a list of numbers until specific limit

Let's say I have a list of predefined numbers, and a list of predefined max limits.
When a user picks a limit, I need to randomly pick a certain amount of numbers from the first list, up until their totals match (As close to, but never over) the user selected total.
What I've tried so far:
void Main()
{
List<int> num = new List<int>(){ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,17, 18, 19, 20 };
int maxNum = 17;
List<int> curNum = new List<int>();
int curTotal = 0;
foreach(int sel in num.Where(x => x < maxNum)){
curTotal += sel;
if(curTotal <= maxNum){
curNum.Add(sel);
}
}
}
There needs to be x amount of numbers picked. In this case, 5 numbers picked, +- 20 numbers to be randomly picked from, and 1 max values.
So the end list should look like this:
1, 2, 3, 4, 7 (17)
1, 2, 3, 5, 6 (17)
1, 2, 3, 4, 6 (16) <- This will be fine if there isn't a solution to the max value.
Building upon #AlexiLevenkov's answer:
class Program
{
static void Main(string[] args)
{
int limit = 17;
int listSize = 5;
List<int> a = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
a.Shuffle();
List<int> genList = new List<int>();
int stoppedCount = 0;
for (int i = 0; i < a.Count(); i++)
{
if (i < listSize)
{
genList.Add(a[i]);
stoppedCount = i;
}
else
{
break;
}
}
while (genList.Sum() > limit)
{
genList.Remove(genList.Max());
stoppedCount++;
genList.Add(a[stoppedCount]);
}
}
}
static class ThisClass
{
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
I think shuffle + "take while sum < limit" may be what you are looking for.
Something like following:
var shuffledList = num.ToList();
shuffledList.Shuffle();
var sum = 0;
var count = 0;
while (shuffledList[count] + sum < max)
{
sum += shuffledList[count++];
}
return shuffledList.Take(count);

Categories

Resources