Search code examples
c++randomtimesrand

Issue with C++ Srand Values


So I'm creating a lottery ticket with random values and then sorting it. I'm not worried about the sorting technique since the teacher isn't looking for classes etc. on this assignment and it works, however, my ticket values that I produce - despite using srand (time(0)) and then later the rand() % 40 + 1 - which I think should make my randoms between 1-40... but mainTicket[0] always equals 0. Any ideas? Sorry about the formatting, made me add extra spaces and mess up my indention.

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

void mainLotto (int main[]);
void lottoSort (int ticketArr[]);

int main()
{
int mainTicket[5];

srand (time(0));

mainLotto(mainTicket);

do
{
    lottoSort(mainTicket);
} while (mainTicket[0] > mainTicket[1] || mainTicket[1] > mainTicket[2] || mainTicket[2] > mainTicket[3] || mainTicket[3] > mainTicket[4] || mainTicket[4] > mainTicket[5]);

for (int i = 0; i < 5; i++)
{
    cout << mainTicket[i] << "\n\n";
}

return 0;
}

///
/// <> Creates the actual lottery ticket
///
void mainLotto (int main[])
{
// Creating the ticket
for (int i = 0; i < 5; i++)
{
    main[i] = rand() % 40 + 1;
}
}

///
/// <> Sorts the actual lottery ticket
///
void lottoSort (int ticketArr[])
{
 // Sorting the ticket
for (int j = 0; j < 5; j++)
{
    if (ticketArr[j] > ticketArr[j+1])
    {
        int temp;

        temp = ticketArr[j+1];

        ticketArr[j+1] = ticketArr[j];

        ticketArr[j] = temp;
    }
}
}

Solution

  • I see two problems with your arrays being accessed out of bounds:

    Here:

    int main()
    {
        int mainTicket[5];
    
        srand(time(0));
    
        mainLotto(mainTicket);
    
        do
        {
            lottoSort(mainTicket);
        }
        while(mainTicket[0] > mainTicket[1] || mainTicket[1] > mainTicket[2]
            || mainTicket[2] > mainTicket[3] || mainTicket[3] > mainTicket[4]);
    //      || mainTicket[4] > mainTicket[5]); // OUT OF BOUNDS!!!
    
        for(int i = 0; i < 5; i++)
        {
            cout << mainTicket[i] << "\n\n";
        }
    
        return 0;
    }
    

    And here:

    void lottoSort(int ticketArr[])
    {
        // Sorting the ticket
        for(int j = 0; j < 4; j++) // j < 4 NOT 5!!! <== WAS OUT OF BOUNDS
        {
            if(ticketArr[j] > ticketArr[j + 1])
            {
                int temp;
    
                temp = ticketArr[j + 1];
    
                ticketArr[j + 1] = ticketArr[j];
    
                ticketArr[j] = temp;
            }
        }
    }
    

    Likely the sort routine was dragging in a zero from out side the array bounds.