0

I want to assign different -random- values (index) to populate a vector. Each time I run the program, it produces a different random value. But, it produces the same random value in each iteration of the loop for the same run.

this is my code :

  void hire (vector<PersonType> &salaryMan, vector<CompanyType> &company){

            double payment;
            string role;
            int i;
            int j;

            for (int x =0; x <5; x++){

                i =randomizeEmp(salaryMan);
                payment =salaryMan[i].getSalary();
                role =salaryMan[i].getTitle();      
                j =randomizeEmp(salaryMan);
                salaryMan[j].setTitle(role);
                salaryMan[j].setSalary(payment);
                company[x].employee.push_back(salaryMan[j]);
            }
        }

  int randomizeEmp(vector<PersonType> &v){
            double i;
            int minNumOfEmp =0;
            unsigned seed =time(NULL);
            srand(seed);
            i =minNumOfEmp +rand()% ((v.size()-1) - minNumOfEmp);
            cout <<i<<endl;
            return i;
        }

My output is the following: CompanyA Florida Miami 100 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
CompanyB NewYork NewYork 101 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
CompanyC California SanJose 102 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
CompanyD Texas Dallas 103 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
CompanyE Florida Talahasse 104 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000

Santiagopph48
  • 131
  • 1
  • 2
  • 8

1 Answers1

2
unsigned seed = time(NULL);
srand(seed);

This is something you generally want to do once, when your program starts.

Every time you do it within the same second (and a lot happens in under a second in the computer world(a)), it will restart the sequence at the same point.


(a) One of the things that's likely to take well under a second is that five-iteration, not-much-work-involved, for loop in your hire() function. Hence probably every iteration of it will use the same seed.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953