Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

make the seven days unique so that we get a permutation #include <iostream> #inc

ID: 3595076 • Letter: M

Question

make the seven days unique so that we get a permutation


#include <iostream>
#include <string>

using namespace std;

#include<iostream>
#include<cstdlib>
#include<ctime>

int main()
{
string weekDays[7]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

for (int i=0; i<7; i++)
cout << weekDays[i] << endl;

cout << endl << endl;

for (int i=6; i>=0; i-- )
cout << weekDays[i] << endl;

// write code that will print out all 7 days in random order.
//first seed rand with the time of day

srand(time(0));
cout<<endl;
for (int i=0;i<7;i++)
cout<<"the random day is "<<weekDays[rand()%7]<<endl; // so 7 is the mod, output will be between 0 and 6
return 0;
}

Explanation / Answer

Hi, Please check this code

--------

#include <iostream>

#include <string>

using namespace std;

#include<iostream>

#include<cstdlib>

#include<ctime>

int main()

{

string weekDays[7]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

  

for (int i=0; i<7; i++)

cout << weekDays[i] << endl;

  

cout << endl << endl;

  

for (int i=6; i>=0; i-- )

cout << weekDays[i] << endl;

  

// write code that will print out all 7 days in random order.

//first seed rand with the time of day

  

srand(time(NULL));

  

int random_array[7]; //declare the array

for(int i=0;i<7;i++) //inititalise it

{

random_array[i]=i;

}

//shuffle the contents in the array above

for(int i=0;i<6;i++)

{

int j = i + rand() / (RAND_MAX / (7 - i) + 1);

int temp = random_array[j];

random_array[j] = random_array[i];

random_array[i] = temp;

}

  

cout<<endl;

for (int i=0;i<7;i++)

cout<<"the random day is "<<weekDays[random_array[i]]<<endl; // so 7 is the mod, output will be between 0 and 6

return 0;

}

--------

Problem with rand() is, it can produce duplicate elements.

So, to deal with that problem, we are creating a random_array of size 7

It is storing values from 0 to 6.

After that, we are shuffling the elemnts in this array.

Now that random_array has shuffeled and unique elements, we can loop from 0 to 6 to display weekdays like this:

weekDays[random_array[i]]

------

Output:

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Saturday

Friday

Thursday

Wednesday

Tuesday

Monday

Sunday

the random day is Friday

the random day is Tuesday

the random day is Saturday

the random day is Wednesday

the random day is Thursday

the random day is Sunday

the random day is Monday