My professor asked us to write a program that:
uses a loop to simulate the rolling of a pair of dice one thousand times(Here I think a for loop would be useful).
With each iteration, the loop needs to count the number of times each value from 2 to 12(Here I am thinking if/else statements would apply)
When the loop ends, must display the number of times each value(from 2 to 12) occurred.
He has the assignment structured like so:
He wants us to use a function that goes into the 1000-time for loop, that calls ANOTHER function TWO TIMES per function call(to simulate two dice being thrown).
Let me explain what I have managed to put down
//
// main.cpp
// RollingDice
#include <iostream>
#include <ctime>
using namespace std;
int roll();
int rollDice();
int main(int argc, const char * argv[])
{
for (int i = 1; i < 1000; i++)
{
rollDice(); //This is the function that is supposed to call the roll();
//function two times. This makes sense to me that TWO DICE
//are being rolled 1000 times.
}
int result; //These two statements was where I was just hoping for something
//to work. I put these variable statements outside of the for
//loop because I was thinking that the int rollDice(); function
//definition(below) wouldn't know how to use it otherwise. I
//know that doesn't make sense, but I just can't explain why.
result = rollDice();
}
int roll()
{ //This function was provided to us by my professor.
static bool randomInitialized = false;
int points;
if (!randomInitialized)
{
srand((unsigned int) time(NULL));
randomInitialized = true;
}
points = (rand() % 6) + 1;
return points;
}
int rollDice()
{ //This I wrote myself. I'm imagining this is how you call a function twice.
//The return statement in this function was my attempt of returning the sum
//of the values of the two dice.
roll();
roll();
return result;
}
Besides this part of the program not working, the other issue I still have is determining a way to have a counter for each value that occurs(however, I am imagining that that part of the program belongs in the for loop. that's about all I know though.). I have thinking deeply about this program since yesterday. I came back to it today hoping a fresh mind would solve it, but I'm still struggling. Any and all help is greatly appreciated.
The expression roll() evaluates to a number. To add numbers, we use +. To return a value, we use return.
Putting that together, we get a simple function to sum two rolls
int rollDice() { return roll() + roll(); }
If you have a numbered sequence of things, and the numbers are both close together and start near 0, one of the standard library's SequenceContainers is an appropriate holder for the whole sequence.
Here the things are counts for a particular throw. We know up front exactly the available values (2 - 12 inclusive), so std::array is appropriate. Any integral value that can hold at least 1000 is appropriate for a count. I choose std::size_t here.
#include <array>
#include <iostream>
int main()
{
std::array<std::size_t, 13> counts {};
This will give us 13 0s, starting at position 0
for (std::size_t i = 0; i < 1000; ++i)
{
++counts[rollDice()];
We choose which number with rollDice, and use it to select a count to increment
}
for (std::size_t i = 2; i < 13; ++i)
{
We can now loop over our results, displaying the counts
std::cout << "The count for " << i << " is " << counts[i] << std::endl;
}
}
1- Using maps to count how many times each number from 2 to 12: ( most practical)
int sumOfDice;
map <int,int> diceOccurances;
for (int i=0; i < 1000; i++)
{
sumOfDice=rollDice();
diceOccurances[sumOfDice];
// Here you are storing how many times each of the dice values occured. Here's
// how you access the map;
}
for (auto const& x : socks)
{
cout <<" Dice Total Number: " << x.first ;
cout <<" Dice Number of Occurances: "<< x.second<<endl;
}
int rollDice()
{ //This I wrote myself. I'm imagining this is how you call a function twice.
//The return statement in this function was my attempt of returning the sum
//of the values of the two dice.
int die1,die2;
die1= roll();
die2= roll();
result = die1+die2;
return result;
}
2- Using if/else ( or switch );
int two, three, four, five, six, seven, eight, nine, ten ,eleven ,twelve;
two=three=four=five=six=seven=eight=nine=ten=eleven=twelve=0;
for (int i=0; i < 1000; i++)
{
if ( rollDice()==2) two++;
if (rollDice()==3) three++;
if (rollDice()==4) four++;
// and so forth until twelve++;
}
int rollDice()
{ //This I wrote myself. I'm imagining this is how you call a function twice.
//The return statement in this function was my attempt of returning the sum
//of the values of the two dice.
int die1,die2;
die1= roll();
die2= roll();
result = die1+die2;
return result;
}
you could do something like this(needs some alteration to fit into the rest of your Proff's code)
int rollDice()
int main(int argc, const char * argv[])
{
srand(time(0));// randomly seed every time you run the code
int dice1;
int dice2;
int storageData[11];//stores the number of times the values from 2 to 12 appears;
for(int i=0; i<1000; i++)
{
dice1=rollDice();
dice2=rollDice();
int sum=dice1+dice2;
storageData[sum-2]+=1; // updates the number of times the sum has appeared.
}
cout << "the value x has appeared "<< storageData[x-2] <<" times"<< endl; // change the value of x depending on which sum number you want.
}
int rollDice()
{
int x=rand()%6+1;// rand()%6 produces a no. from 0-5. rand()%6+1 produces a number from 1-6.
return x;
}
NOTE in the above code we subtract (-2) for every element cos the sum starts from 2 and not 0.
Related
I've written some code in c++ that is meant to find the minimum and maximum values that can be calculated by summing 4 of the 5 integers presented in an array. My thinking was that I could add up all elements of the array and loop through subtracting each of the elements to figure out which subtraction would lead to the smallest and largest totals. I know this isn't the smartest way to do it, but I'm just curious why this brute force method isn't working when I code it. Any feedback would be very much appreciated.
#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;
void minimaxsum(vector<int> arr){
int i,j,temp;
int n=sizeof(arr);
int sum=0;
int low=INT_MAX;
int high=0;
for (j=0;j<n;j++){
for (i=0;i<n;i++){
sum+=arr[i];
}
temp=sum-arr[j];
if(temp<low){
low=temp;
}
else if(temp>high){
high=temp;
}
}
cout<<low;
cout<<high<<endl;
}
int main (){
vector<int> arr;
arr.push_back(1.0);
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
There are 2 problems.
Your code is unfortunately buggy and cannot deliver the correct result.
The solution approach, the design is wrong
I will show you what is wrong and how it could be refactored.
But first and most important: Before you start coding, you need to think. At least 1 day. After that, take a piece of paper and sketch your solution idea. Refactor this idea several times, which will take a complete additional day.
Then, start to write your code. This will take 3 minutes and if you do it with high quality, then it takes 10 minutes.
Let us look first at you code. I will add comments in the source code to indicate some of the problems. Please see:
#include <iostream>
#include <vector>
#include <limits.h> // Do not use .h include files from C-language. Use limits
using namespace std; // Never open the complete std-namepsace. Use fully qualified names
void minimaxsum(vector<int> arr) { // Pass per reference and not per value to avoid copies
int i, j, temp; // Always define variables when you need them, not before. Always initialize
int n = sizeof(arr); // This will not work. You mean "arr.size();"
int sum = 0;
int low = INT_MAX; // Use numeric_limits from C++
int high = 0; // Initialize with MIN value. Otherwise it will fail for negative integers
for (j = 0; j < n; j++) { // It is not understandable, why you use a nested loop, using the same parameters
for (i = 0; i < n; i++) { // Outside sum should be calculated only once
sum += arr[i]; // You will sum up always. Sum is never reset
}
temp = sum - arr[j];
if (temp < low) {
low = temp;
}
else if (temp > high) {
high = temp;
}
}
cout << low; // You miss a '\n' at the end
cout << high << endl; // endl is not necessary for cout. '\n' is sufficent
}
int main() {
vector<int> arr; // use an initializer list
arr.push_back(1.0); // Do not push back doubles into an integer vector
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
Basically your idea to subtract only one value from the overall sum is correct. But there is not need to calculate the overall sum all the time.
Refactoring your code to a working, but still not an optimal C++ solution could look like:
#include <iostream>
#include <vector>
#include <limits>
// Function to show the min and max sum from 4 out of 5 values
void minimaxsum(std::vector<int>& arr) {
// Initialize the resulting values in a way, the the first comparison will always be true
int low = std::numeric_limits<int>::max();
int high = std::numeric_limits<int>::min();;
// Calculate the sum of all 5 values
int sumOf5 = 0;
for (const int i : arr)
sumOf5 += i;
// Now subtract one value from the sum of 5
for (const int i : arr) {
if (sumOf5 - i < low) // Check for new min
low = sumOf5 - i;
if (sumOf5 - i > high) // Check for new max
high = sumOf5 - i;
}
std::cout << "Min: " << low << "\tMax: " << high << '\n';
}
int main() {
std::vector<int> arr{ 1,2,3,1,2 }; // The test Data
minimaxsum(arr); // Show min and max result
}
This is my first C++ class and I'm not really sure how to proceed in my homework, as understanding arrays has been fairly difficult for me. I've successfully completed the 1st task, but got stuck understanding the 2nd and don't really know how to start it.
The tasks are:
Define a function named harmonicNum() that finds and returns the nth harmonic number using an iteration statement where n is a positive int-typed argument provided by the caller.
Given a valid array index i, define a function named fillHarmonic() that iteratively calls harmonicNum() to initialize the ith element of an array parameter wit the i+1th number of the harmonic series. I must define this function to work on a one-dimensional array of any size.
This is the code that I have so far:
#include <iostream>
#include <cmath>
using namespace std;
double harmonicNum(int n);
int n;
int main()
{
do
{
cout << "Please input a positive integer: " << endl;
cin >> n;
} while (n < 0);
cout << harmonicNum(n) << endl;
return 0;
}
double harmonicNum(n)
{
double harmonic = 0.00
for (int i = 1; i <= n; i++)
{
harmonic = harmonic + 1.00 / i;
}
return harmonic;
}
Something like this?
Method definition:
void fillHarmonic(double &i_elem, int i){
i_elem = harmonicNum(i+1);
}
Call without error checking:
double arr [5];
//TODO init values
for(int i = 0; i < (sizeof(arr)/sizeof(double)); i++ ){
fillHarmonic(arr[i], i);
}
This is the problem I am working with
Using a loop and rand(), simulate a coin toss 10000 times
Calculate the difference between heads and tails.
Wrap the above two lines in another loop, which loops 1000 times.
Use an accumulator to sum up the differences
Calculate and display the average difference between the number of heads and tails.
The accumulator is not working the way I want It to? Very much a C++ Noob, for homework lol. Anyone help please?
Why am I using rand()????
second part of the assignment has us using the newer method (mt19937), just trying to tackle this bit first before moving on.
#include <iostream>
using namespace std;
int main() {
int heads = 0, tails = 0, num, total = 0;
srand(time(NULL));
for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
for (int i = 0; i < 10000; i++) // COIN TOSS
{
int random = rand() % 2;
if (random == 0)
{
heads++;
}
else
{
tails++;
}
}
cout << abs((heads++ - tails++));
cin >> num;
total =+ num;
}
cout << "The average distance between is " << total / 1000 << endl;
cin.get();
return 0;
}
With your code, you never actually save the values that you need. And there's some unnecessary arithmetic that would throw off your results. This line:
cout << abs((heads++ - tails++)); increments the heads and tails variables, but they shouldn't be.
The next two lines make no sense. Why do you need to get a number from the user, and why do you add that number to your total?
Finally, this expression: total / 1000 performs integer division, which will throw off your results.
Those are the immediate issues I can spot in your code.
Next, we move on to your problem statement. What is an accumulator? To me, it sounds like you're supposed to have a class? It also reminds me of std::accumulate, but if that's what you intended, it would have said as much. Also, std::accumulate would require storing results, and that's not really necessary for this program. The code below performs the main task, i.e. it runs the necessary simulations and tracks results.
You'll notice I don't bother counting tails. The big average is also calculated as it goes since the total number of simulations is known ahead of time.
#include <cmath>
#include <iostream>
#include <random>
int flip_coin() {
static std::mt19937 prng(std::random_device{}());
static std::uniform_int_distribution<int> flip(0, 1);
return flip(prng);
}
int main() {
constexpr int tosses = 10'000;
constexpr int simulations = 1'000;
double diffAvg = 0.0;
for (int i = 0; i < simulations; ++i) {
int heads = 0;
for (int j = 0; j < tosses; ++j) {
if (flip_coin()) {
++heads;
}
}
diffAvg +=
std::abs(heads - (tosses - heads)) / static_cast<double>(simulations);
}
std::cout << "The average heads/tails diff is: " << diffAvg << '\n';
return 0;
}
What I ended up doing that seems to work for **THIS VERSION WITH RAND() (using the new method later) **
#include <iostream>
using namespace std;
int main()
{
int heads = 0, tails = 0, total = 0;
srand(time(NULL));
for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
{
for (int i = 0; i < 10000; ++i) // COIN TOSS
if (rand() % 2 == 0)
++heads;
else
++tails;
total += abs(heads - tails);
}
}
cout << "The average distance between is " << total / 1000.0 << '\n';
cin.get();
return 0;
}
I am writing a simple code to calculate Fabonacci numbers as an exercise. The code works, but i don't get why. I have some special cases for n=1 and n=2 which is the place of the number in the sequence (the numbers are 0 and 1). However after those, the number is calculated in this loop.
while(n>LoopCount)
{
Fib_n=Fib_1+Fib_2;
Fib_2=Fib_1;
Fib_1=Fib_n;
LoopCount++;
}
Going in to the loop, Fib_1=0, Fib_2=0, and Fib_n=1. Why does not this loop just spit out 0 no matter what? The whole code is below.
#include <iostream>
using namespace std;
int main()
{
cout <<"Which number of the Fibonacci sequence do you want to calculate?" <<endl;
int n;
cin >>n;
cout <<endl;
int Fib_n;
int Fib_1;
int Fib_2;
int LoopCount=1;
if(n>1)
{
Fib_n=1;
LoopCount++;
while(n>LoopCount)
{
Fib_n=Fib_1+Fib_2;
Fib_2=Fib_1;
Fib_1=Fib_n;
LoopCount++;
}
}
cout <<Fib_n;
return 0;
}
int Fib_1;
int Fib_2;
were never initialized. Therefore, the first time you calculate Fib_n=Fib_1+Fib_2;, Fib_n will get the sum of two uninitialized variables.
I have modified your code so it would work.
#include <iostream>
using namespace std;
int main()
{
cout <<"Which number of the Fibonacci sequence do you want to calculate?" <<endl;
int n;
cin >> n;
cout << endl;
int Fib_1 = 1;
int Fib_2 = 1;
int count = 0;
while(n > count)
{
Fib_1 = Fib_1 + Fib_2;
Fib_2 = Fib_1 - Fib_2;
count++;
}
cout << Fib_1;
return 0;
}
Fib_1
You have that as an uninitalized variable, so you may get a garbage value for output.
Fib_2 = Fib_1
Next, you initialize Fib_2 with Fib_1, meaning they both share the same (random) value.
In debug mode, these are both initialized to 0, and adding them:
Fib_n=Fib_1+Fib_2;
makes the sum equal 0. In release mode, you can expect random values from the compiler. Here is more info on Uninitialized Variables.
I am considering a society where there are an arbitrary number of people. Each person has just two choices. Either he or she stays with her current choice or she switches. In the code that I want to write, the probability that the person switches is inputted by the user.
To make clear what I am trying to do, suppose that the user tells the computer that there are 3 people in the society where the probabilities that each person chooses to switch is given by (p1,p2,p3). Consider person 1. He has probability of p1 of switching. Using him as a base for our calculation, the probability given person 1 as a base, that exactly no one in the society chooses to switch is given by
P_{1}(0)=(1-p2)*(1-p3)
and the probability using person 1 as a base, that exactly one person in the society chooses to switch is given by
P_{1}(1)=p2*(1-p3)+(1-p2)*p3.
I can't figure out how to write this probability function in C++ without writing out every term in the sum. I considered using the binomial coefficient but I can't figure out a closed form expression for the sum since depending on user input, there are arbitrarily many probabilities that need to be considered.
I have attached what I have. The probability function is only a part of what I am trying to do but it is also the hardest part. I named the probability function probab and what I have in the for loop within the function is obviously wrong.
EDIT: Basically I want to calculate the probability of choosing a subset where each element in that subset has a different probability of being chosen.
I would appreciate any tips on how to go about this. Note that I am a beginner at C++ so any tips on improving my programming skills is also appreciated.
#include <iostream>
#include <vector>
using namespace std;
unsigned int factorial(unsigned int n);
unsigned int binomial(unsigned int bin, unsigned int cho);
double probab(int numOfPeople, vector<double> probs, int p, int num);
int main() {
char correctness;
int numOfPeople = 0;
cout << "Enter the # of people: ";
cin >> numOfPeople;
vector<double> probs(numOfPeople); // Create a vector of size numOfPeople;
for (int i = 1; i < numOfPeople+1; i++) {
cout << "Enter the probability of person "<< i << " will accept change: ";
cin >> probs[i-1];
}
cout << "You have entered the following probabilities of accepting change: (";
for (int i = 1; i < numOfPeople+1; i++) {
cout << probs[i-1];
if (i == numOfPeople) {
cout << ")";
}
else {
cout << ",";
}
}
cout << endl;
cout << "Is this correct? (Enter y for yes, n for no): ";
cin >> correctness;
if (correctness == 'n') {
return 0;
}
return 0;
}
unsigned int factorial(unsigned int n){ // Factorial function
unsigned int ret = 1;
for(unsigned int i = 1; i <= n; ++i) {
ret *= i;
}
return ret;
}
unsigned int binomial(unsigned int totl, unsigned int choose) { // Binomial function
unsigned int bin = 0;
bin = factorial(totl)/(factorial(choose)*factorial(totl-choose));
return bin;
}
double probab(int numOfPeople, vector<double> probs, int p, int num) { // Probability function
double prob = 0;
for (int i = 1; i < numOfPeople; i++) {
prob += binomial(numOfPeople, i-1)/probs[p]*probs[i-1];
}
return prob;
}
For future reference, for anybody attempting to do this, the probability function will look something like:
double probability (vector<double> &yesprobabilities, unsigned int numOfPeople, unsigned int yesNumber, unsigned int startIndex) {
double kprobability = 0;
// Not enough people!
if (numOfPeople-1 < yesNumber) {
kprobability = 0;
}
// n == k, the only way k people will say yes is if all the remaining people say yes.
else if (numOfPeople-1 == yesNumber) {
kprobability = 1;
for (int i = startIndex; i < numOfPeople-1; ++i) {
kprobability = kprobability * yesprobabilities[i];
}
}
else if (yesprobabilities[startIndex] == 1) {
kprobability += probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
}
else {
// The first person says yes, k - 1 of the other persons have to say yes.
kprobability += yesprobabilities[startIndex] * probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
// The first person says no, k of the other persons have to say yes.
kprobability += (1 - yesprobabilities[startIndex]) * probability(yesprobabilities,numOfPeople-1,yesNumber,startIndex+1);
}
return probability;
}
Something called a recursive function is used here. This is completely new to me and very illuminating. I credit this to Calle from Math stack exchange. I modified his version slightly to take vectors instead of arrays with some help.