Using a vector as a counter for coin toss?

So this is my code so far and I took my array code and tried to incorporate a vector rather than an array. It's supposed to roll 36000 times and then tally up how many times you get which roll and display that vector. This runs but the program stops working as soon as it starts. Help please!

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
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;

int main()
{
    int n = 13;
    int counter = 0;
    vector<int> myVec;
    int dice1, dice2;

    for (int i = 0; i < n; i++) // I probably don't need this part for the vectors, right?
    {
            myVec[i] = 0;
    }


    for (int i = 0; i <= 36000; i++)
    {
        dice1 = rand()%6 + 1;
        dice2 = rand()%6 + 1;
        myVec.push_back(dice1 + dice2);
        myVec[dice1 + dice2]++;
    }

    cout << "Sum of rolls\t" << "Tally" << endl;

    for(int i = 2; i < n; i++)
    {
        cout << i << "\t\t" << myVec[i] << endl;
    }

    return 0;
}
Last edited on
Yes, the first for-loop is not needed. I think you don't need line 24 either. Whack that line and the first for-loop and see if it runs better.
so taking your suggestion my code is now

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
27
28
29
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;

int main()
{
    int n = 13;
    int counter = 0;
    vector<int> myVec;
    int dice1, dice2;

    for (int i = 0; i <= 36000; i++)
    {
        dice1 = rand()%6 + 1;
        dice2 = rand()%6 + 1;
        myVec.push_back(dice1 + dice2);
    }

    cout << "Sum of rolls\t" << "Tally" << endl;

    for(int i = 2; i < n; i++)
    {
        cout << i << "\t\t" << myVec[i] << endl;
    }

    return 0;
}


But it doesn't output what I need it to. Without line 24, there isn't a way to make the myVec[dice1 + dice2] to increase by 1 as a counter.
So I worked on it a bit more and I refined it slightly.

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
27
#include <iostream>
#include <cstdlib>
#include <vector>

using namespace std;

int main()
{
    vector<int> counter(11);
    int dice1, dice2;

    for (int i = 0; i <= 36000; i++)
    {
        dice1 = rand()%6 + 1;
        dice2 = rand()%6 + 1;
        counter[dice1 + dice2]++;
    }

    cout << "Sum of rolls\t" << "Tally" << endl;

    for(int i = 2; i < counter.size(); i++)
    {
        cout << i << "\t\t" << counter[i] << endl;
    }

    return 0;
}


Now it outputs what I need but it crashes (stops working) after it finishes. Why is that?
The possible values of dice1 + dice2 on line 16 range from 2 to 12. The valid indexes for counter are 0 through 10.

Change line 9 to vector<int> counter(13);

Btw, dice are not coins.
Last edited on
Topic archived. No new replies allowed.