I have been given this question, in my computer science class, and I cannot figure out how to answer it.
Question:
•Create a procedure called tossCoins with one integer parameter - numTosses
•Inside your tossCoins procedure, call your tossCoin function from challenge #5
numTosses times. So for example if we enter tossCoins(50), the tossCoin function will be called 50 times.
•Your tossCoins procedures should then print out the number of times that the coin landed on heads and the number of times the coin landed on tails
•Extend your main program, so that the user can choose how many times to toss the coin
I have already created the tossCoin function, but cannot figure out how to run it the amount of times the user asks, or how to create a tally of heads and tails.
This is the code I have so far:
static void Main(string[] args)
{
Random rnd = new Random();
Console.WriteLine(tossCoin(rnd));
Console.Write("Please enter a number: ");
int numTosses = Convert.ToInt16(Console.ReadLine());
Console.ReadLine();
}
static string tossCoin(Random rnd)
{
int num = rnd.Next(1, 3);
string heads = "Heads";
string tails = "Tails";
if(num == 1)
{
return heads;
}
else
{
return tails;
}
}
static void tossCoins(int numTosses)
{
int headsTally = 0;
int tailsTally = 0;
for(int i = 0; i < numTosses; i++)
{
string outcome = tossCoin(rnd);
numTosses--;
if(outcome == heads)
{
headsTally++;
}
else
{
tailsTally++;
}
}
}
}
If anyone can help, it would be great, as I am trying to learn the different rules of using functions, and procedures. Thanks, Leighton.
A couple things, first it looks like you've almost got it. You just need to call your tossCoins() function in your main method. Second, you don't need to decrement numTosses in your for loop, ie. remove the line numTosses--;
EDIT: as Tommy said, the statement outcome == heads wont compile since heads isn't defined. Either replace heads with "Heads" or define it earlier in the function. And yea you might want to return/print the result.
Related
So this is a very simple code that i can for the love of me get right because of some small mistake but the point here is the first int the user gives is the amount of numbers you will give after it so i have made this but for some reason the program wants 1 more int than it should. Lets say i enter 3 at first. That should mean that it would take 3 ints after that and then print them and end the program but fore some reason if i enter 3 after that it wants 4. if i enter 4 after that it wants 5 and you get the point. I have tried changing the whole code but i think the problem is that i am just making it to long and to complicated. here is the code
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
int[] numbers = new int[ammount];
for(int i = 0; i < ammount; i++)
{
numbers[i] = Enters;
Enters = int.Parse(Console.ReadLine());
}
int ammountEntered = 0;
while(ammountEntered < ammount)
{
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
Take a moment to think about this. If the user enters amount = 1, what would Happen? You would first ask a number, then enter the loop one time, where it asks for another number. Why is it asking for another number in this case? Why not just skip the Enter variable and assign numbers inside the loop?
for(int i = 0; i < ammount; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
I would highly recommend reading eric lipperts article on How to debug small programs, since problems like this should be very easy to diagnose when stepping thru a program. You might also consider reading the coding convensions guide, local variables should for example use "camelCasing".
You might also consider using a foreach loop when printing variables:
foreach(var number in numbers){
Console.WriteLine(number);
}
I think i understand your code!
This is how i would do it, and do read my explanation down below aswell!
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many numbers do you want to add to your array?");
int amount = int.Parse(Console.ReadLine());
int[] numbers = new int[amount];
for (int i = 0; i < amount; i++)
{
Console.WriteLine($"Numer {i+1}/{amount}"); // Just tells the user what I of number their adding. aka unessecary
int Enters = int.Parse(Console.ReadLine());
numbers[i] = Enters;
}
Console.WriteLine("\n");
int ammountEntered = 0;
while (ammountEntered < amount)
{
Console.Write($"Number {ammountEntered + 1}/{amount} : ");
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
The first problem was that you asked for a unnesecary ReadLine in the beggining, so that i removed! Then inside you for-loop i switched the position of the adding, aswell as the one asking for a new number. I also added a few counters so that you can see a bit more in detail what the code does!
My first post on here! I started learning how to program a couple of days ago and have picked up a rolling dice project. I think I have done the main part of it but my problem comes from:
Printing how many times each side came up (maybe store them in an array)?
Bonus: Print out the percentage of times each side appeared (rounded up to 2 decimals)
Keep in mind the times and sides are user input so could be e.g. 50 times x 35 sides.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
namespace Dice_roll
{
class Program
{
static void Main(string[] args)
{
static int getRandomNumber(int min, int max)
{
Random randomRoll = new Random();
lock (randomRoll)
{
return randomRoll.Next(min, max);
}
}
int sides, rollTimes, i;
i = 0;
bool boolCheckSides = false;
bool boolCheckRolls = false;
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
Console.WriteLine("Now select how many times you want it to roll: \n");
do
{
boolCheckRolls = Int32.TryParse(Console.ReadLine(), out rollTimes);
if (boolCheckRolls == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckRolls == false);
do
{
Console.WriteLine("Rolling... " + getRandomNumber(1, sides));
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
int[] arr = new int[rollTimes];
}
}
}
I'm sorry if my code is messy or something, I'm still very beginner.
Well, I assume that your code is not complete yet, so I will just share some opinions of mine.
1- You are adding a method getRandomNumber inside your main function. This method won't compile and should be moved outside the scope of main function. The scope of main function is any code between the curly brackets "{}" shown in the code below
static void main(string[] args){}
just a small side note, try to use Uppercase letters for naming methods in C#, except the main function as that's a naming convention ;-)
2- You did a great job in declaring the variables you need (boolCheckSides, boolCheckRolls, i) before you start assigning them values. However, you also need to declare the Array before using it not after, so your code should look something like this
//Declare the Array
int[] arr = new int[rollTimes];
do
{
int temp = getRandomNumber(1, sides);
Console.WriteLine("Rolling... " + temp);
//Save the value acquired from this roll in the array
arr[i] = temp;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
Then you can easily play around with the array and find the frequency of any number. I would suggest you refer to this post Count the frequency of element of an array in C# if you want to find the short answer, and refer to this post Frequency of Numbers in a 1D Array for the long answer. Just please note that the second post is using C++ language, but it is still showing the same logic though.
3- Just a small advise, please try to avoid "do...while" loops as much as possible. It needs a lot of attention when you write them as they can easily get you into infinite loop.
I suggest you to use a Dictionary, with the side (1 to X) as Key and number of time its appears .
class Program
{
Dictionary<int, int> RollDice = new Dictionary<int, int>();
static void Main(string[] args)
{
:
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
//Initialize the dictionary with key and value
for(int i = 1; i<=sides;i++)
RollDice.Add(i, 0);
:
i = 0;
do
{
var value = getRandomNumber(1, sides + 1)
Console.WriteLine("Rolling... " + value);
RollDice[i]++;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
and you could display your stats by looping over the dictionary:
foreach (var pair in RollDice)
{
Console.WriteLine($"DiceSide:{pair.Key} , appears: {pair.Value}, probability: {(float)pair.Value/(float)rollTimes:0.00}");
}
today I have an issue which is driving me up a wall. I am a novice programmer, currently learning the basics of C#, after learning Java.
Today, I was working on a practice example when I encountered this problem:
Code Running
This is a screenshot of my code running, and I have left a print statement inside the loop to show me what my index variable is doing. As you can see, it is incrementing more than once per each execution of the loop. I have also gotten the same results when using a while loop, and in other projects.
Here is the code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many values are you entering");
int value = Convert.ToInt32(Console.Read());
Console.WriteLine("Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.Read());
Console.WriteLine("i is: "+i);
}
}
}
I cannot really proceed with this assignment until I can figure out what is causing this issue. Thanks!
try ReadLine() instead of Read() like
Console.WriteLine("How many values are you entering");
string input = Console.ReadLine();
int value = Convert.ToInt32(input);
Console.WriteLine(value +" Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("i is: " + i);
}
Hi Welcome to the wonderful world of C#
Your problem here is Console.Read()
Console.Read() will give you an int of the character 4 which is your first typed character. And that character will be 52.
So it will loop 52 times.
Instead of Console.Read() use Console.ReadLine()
This will be so easy for some of you programming geniuses out there but I am a student who recently began learning about C# (and programming in general) and I find myself.... stuck.
This is an assessment I am working on so I am not looking for a copy/paste answer, it would be preferable if I could find out where I am going wrong/where to start so I can fix it myself.
The aim of the assessment is to:
use the random number generator to generate 4 numbers - 2 for player 1 and 2 for the dealer.
Add players 2 numbers together, add dealers 2 numbers together (show results on screen)
this is where I become stuck...
I need to create a function that basically says:
If DealerResult is > PlayerResult display: Dealer Wins.
If PlayerResult > DealerResult, display: You win.
If DealerResult == PlayerResult display: it is a draw.
So far I have the following code. As you will see, I can generate the numbers, add them together and display the results on screen.
using System;
namespace Assessment
{
class MainClass
{
public static void Main (string[] args)
{
//Decalre Variables
Random r = new Random ();
int PlayerNumber1 = r.Next (6, 25);
int PlayerNumber2 = r.Next (6, 25);
int DealerNumber1 = r.Next (6, 25);
int DealerNumber2 = r.Next (6, 25);
int PlayerTotal = (PlayerNumber1 + PlayerNumber2);
int DealerTotal = (DealerNumber1 + DealerNumber2);
Console.WriteLine ("Welcome!");
Console.ReadLine ();
Console.WriteLine ("Your total is: " + PlayerTotal);
Console.ReadLine ();
Console.WriteLine ("Dealer total is: " + DealerTotal);
Console.ReadLine ();
}
}
}
From here, I am stuck. Suggestions would be so appreciated as to how I should proceed to compare the numbers and display the appropriate result/s through a function.
As mentioned earlier, this is an assessment so I am not looking for a quick fix or final answer. Also, the assessment requires the use of a FUNCTION to generate the result, not a loop or any other type of programming magic that some of you super-geniuses may be aware of. (And I say that with envy - I wish I was half as smart as some of the people I see posting on here). :)
You just need simple if statements, and put them into a function:
private static void DisplayResult(int playerTotal, int dealerTotal)
{
if(playerTotal > dealerTotal)
{
Console.WriteLine("You win!");
}
else if(playerTotal < dealerTotal)
{
Console.WriteLine("Dealer wins!");
}
else
{
Console.WriteLine("Draw!");
}
}
Explanation: We create a function that takes two int parameter.One of them is playerTotal, another is dealerTotal.The function compare these values and display the proper result in the console according to this comparison.After you create your function all you need to do is pass PlayerTotal and DealerTotal variables to your function like this:
DisplayResult(PlayerTotal, DealerTotal);
Note: You should put this method into MainClass
To start you will need a function. Functions look like this:
<access modifier> <return type> <Name> ( <parameters> )
{}
A quick example:
private bool GetResult (int playerValue, int dealerValue)
{
}
What this means is that the function will return a bool, and it takes two int parameters.
To return nothing, return void. To call the function, use its name and pass the parameters inside the parenthesis:
bool result = GetResult(1, 2);
Now to do a comparison, we use the if statement:
if (<expression> <comparator> <expression>)
{}
Another quick example:
if (playerScore > dealerScore)
{
Console.WriteLine("Player wins!");
}
Which says, "If PlayerScore is greater than DealerScore, do what is inside the brace" (a print in this case).
I'm trying to explain the basics, instead of give an actual answer, as you requested. Please let me know if I can clarify anything better, and good luck learning programming in C#!
Another variation demonstrating function returning result as a string.
using System;
namespace Assessment
{
class MainClass
{
public static void Main(string[] args)
{
//Decalre Variables
Random r = new Random();
int PlayerNumber1 = r.Next(6, 25);
int PlayerNumber2 = r.Next(6, 25);
int DealerNumber1 = r.Next(6, 25);
int DealerNumber2 = r.Next(6, 25);
int PlayerTotal = (PlayerNumber1 + PlayerNumber2);
int DealerTotal = (DealerNumber1 + DealerNumber2);
Console.WriteLine("Welcome!");
Console.ReadLine();
Console.WriteLine("Your total is: " + PlayerTotal);
Console.ReadLine();
Console.WriteLine("Dealer total is: " + DealerTotal);
Console.ReadLine();
Console.WriteLine("Dealer total is: " + DealerTotal);
Console.WriteLine(Environment.NewLine);
Console.WriteLine(DisplayResult(PlayerTotal, DealerTotal));
Console.ReadLine();
}
private static string DisplayResult(int playerTotal, int dealerTotal)
{
var result = "An unhandled exception has occured ";
if (playerTotal > dealerTotal)
{
result = "You win!";
}
else if (playerTotal < dealerTotal)
{
result = "Dealer wins!";
}
else
{
result = "Draw!";
}
return result;
}
}
}
I have a coding/maths problem that I need help translating into C#. It's a poker chip calculator that takes in the BuyIn, the number of players and the total amount of chips for each colour (there are x amount of colours) and their value.
It then shows you every possible combination of chips per person to equal the Buy In. The user can then pick the chipset distribution they would like to use. It's best illustrated with a simple example.
BuyIn: $10
Number of Players: 1
10 Red Chips, $1 value
10 Blue Chips, $2 value
10 Green Chips, $5 value
So, the possible combinations are:
R/B/G
10/0/0
8/1/0
6/2/0
5/0/1
4/3/0
2/4/0
1/2/1
etc.
I have spent a lot of time trying to come up with an algorithm in C#/.NET to work this out. I am stumbling on the variable factor - there's usually only 3 or 4 different chips colours in a set, but there could be any amount. If you have more than one player than you have to count up until TotalChips / NumberOfPlayers.
I started off with a loop through all the chips and then looping from 0 up to NumberOfChips for that colour. And this is pretty much where I have spent the last 4 hours... how do I write the code to loop through x amount of chips and check the value of the sum of the chips and add it to a collection if it equals the BuyIn? I need to change my approach radically methinks...
Can anyone put me on the right track on how to solve this please? Pseudo code would work - thank you for any advice!
The below is my attempt so far - it's hopeless (and wont compile, just an example to show you my thought process so far) - Might be better not to look at it as it might biased you on a solution...
private void SplitChips(List<ChipSuggestion> suggestions)
{
decimal valueRequired = (decimal)txtBuyIn.Value;
decimal checkTotal = 0;
ChipSuggestion suggestion;
//loop through each colour
foreach (Chip chip in (PagedCollectionView)gridChips.ItemsSource)
{
//for each value, loop through them all again
foreach (Chip currentChip in (PagedCollectionView)gridChips.ItemsSource)
{
//start at 0 and go all the way up
for (int i = 0; i < chip.TotalChipsInChipset; i++)
{
checkTotal = currentChip.ChipValue * i;
//if it is greater than than ignore and stop
if (checkTotal > valueRequired)
{
break;
}
else
{
//if it is equal to then this is a match
if (checkTotal == valueRequired)
{
suggestion = new ChipSuggestion();
suggestion.SuggestionName = "Suggestion";
chipRed.NumberPerPlayer = i;
suggestion.Chips.Add(chipRed);
chipBlue.NumberPerPlayer = y;
suggestion.Chips.Add(chipBlue);
chipGreen.NumberPerPlayer = 0;
suggestion.Chips.Add(chipGreen);
//add this to the Suggestion
suggestions.Add(suggestion);
break;
}
}
}
}
}
}
Here's an implementation that reads the number of chips, the chips (their worth and amount) and the buyin and displays the results in your example format. I have explained it through comments, let me know if you have any questions.
class Test
{
static int buyIn;
static int numChips;
static List<int> chips = new List<int>(); // chips[i] = value of chips of color i
static List<int> amountOfChips = new List<int>(); // amountOfChips[i] = number of chips of color i
static void generateSolutions(int sum, int[] solutions, int last)
{
if (sum > buyIn) // our sum is too big, return
return;
if (sum == buyIn) // our sum is just right, print the solution
{
for (int i = 0; i < chips.Count; ++i)
Console.Write("{0}/", solutions[i]);
Console.WriteLine();
return; // and return
}
for (int i = last; i < chips.Count; ++i) // try adding another chip with the same value as the one added at the last step.
// this ensures that no duplicate solutions will be generated, since we impose an order of generation
if (amountOfChips[i] != 0)
{
--amountOfChips[i]; // decrease the amount of chips
++solutions[i]; // increase the number of times chip i has been used
generateSolutions(sum + chips[i], solutions, i); // recursive call
++amountOfChips[i]; // (one of) chip i is no longer used
--solutions[i]; // so it's no longer part of the solution either
}
}
static void Main()
{
Console.WriteLine("Enter the buyin:");
buyIn = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the number of chips types:");
numChips = int.Parse(Console.ReadLine());
Console.WriteLine("Enter {0} chips values:", numChips);
for (int i = 0; i < numChips; ++i)
chips.Add(int.Parse(Console.ReadLine()));
Console.WriteLine("Enter {0} chips amounts:", numChips);
for (int i = 0; i < numChips; ++i)
amountOfChips.Add(int.Parse(Console.ReadLine()));
int[] solutions = new int[numChips];
generateSolutions(0, solutions, 0);
}
}
Enter the buyin:
10
Enter the number of chips types:
3
Enter 3 chips values:
1
2
5
Enter 3 chips amounts:
10
10
10
10/0/0/
8/1/0/
6/2/0/
5/0/1/
4/3/0/
3/1/1/
2/4/0/
1/2/1/
0/5/0/
0/0/2/
Break the problem down recursively by the number of kinds of chips.
For the base case, how many ways are there to make an $X buy-in with zero chips? If X is zero, there is one way: no chips. If X is more than zero, there are no ways to do it.
Now we need to solve the problem for N kinds of chips, given the solution for N - 1. We can take one kind of chip, and consider every possible number of that chip up to the buy-in. For example, if the chip is $2, and the buy-in is $5, try using 0, 1, or 2 of them. For each of these tries, we have to use only the remaining N - 1 chips to make up the remaining value. We can solve that by doing a recursive call, and then adding our current chip to each solution it returns.
private static IEnumerable<IEnumerable<Tuple<Chip, int>>> GetAllChipSuggestions(List<Chip> chips, int players, int totalValue)
{
return GetAllChipSuggestions(chips, players, totalValue, 0);
}
private static IEnumerable<IEnumerable<Tuple<Chip, int>>> GetAllChipSuggestions(List<Chip> chips, int players, int totalValue, int firstChipIndex)
{
if (firstChipIndex == chips.Count)
{
// Base case: we have no chip types remaining
if (totalValue == 0)
{
// One way to make 0 with no chip types
return new[] { Enumerable.Empty<Tuple<Chip, int>>() };
}
else
{
// No ways to make more than 0 with no chip types
return Enumerable.Empty<IEnumerable<Tuple<Chip, int>>>();
}
}
else
{
// Recursive case: try each possible number of this chip type
var allSuggestions = new List<IEnumerable<Tuple<Chip, int>>>();
var currentChip = chips[firstChipIndex];
var maxChips = Math.Min(currentChip.TotalChipsInChipset / players, totalValue / currentChip.ChipValue);
for (var chipCount = 0; chipCount <= maxChips; chipCount++)
{
var currentChipSuggestion = new[] { Tuple.Create(currentChip, chipCount) };
var remainingValue = totalValue - currentChip.ChipValue * chipCount;
// Get all combinations of chips after this one that make up the rest of the value
foreach (var suggestion in GetAllChipSuggestions(chips, players, remainingValue, firstChipIndex + 1))
{
allSuggestions.Add(suggestion.Concat(currentChipSuggestion));
}
}
return allSuggestions;
}
}
For some large combinations this is propably not solvable in finite time.
(It is a NP problem)
http://en.wikipedia.org/wiki/Knapsack_problem
There are also links with Code? that could help you.
Hope this helps a bit.