mercredi 30 août 2017

How to write a recursive function that jumbles up numbers from 0 to 6 in a random manner?

Basically i want to write a function that takes values from 0 to 6 and gives back a random assortment such as 2,3,4,5,0,1,6. Here is the code that i came up with. However the problem is that the integer prev (meaning previous) does not store all the old values of r (random number) and thus some values end up being repeated. How might i fix this?

int s(int b)
    {
        // b is 7
        int h = b-1;
        int prev = -1;// to store the previous r value
        srand(time(0));
        for (int i = 0; i < b; i++)
        {
            int r = rand()%(h - 0 + 1) + 0;
            if (r != prev)
            {
             cout << r << endl;
             prev = r;
            }
            else if (r == prev)
            {
                s(b);
            }
        }

        return 0;
    }




Aucun commentaire:

Enregistrer un commentaire