dimanche 28 mars 2021

Recursive function doesn't return the vector

I'm trying to create a list which contains 10 unique random numbers between 1 and 20 by using a recursive function. Here is the code.

Compiler: GNU g++ 10.2.0 on Windows

Compiler flags: -DDEBUG=9 -ansi -pedantic -Wall -std=c++11

#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>
using namespace std;

vector<int> random (int size, int range, int randnum, vector<int> randlist ) {
  if (size < 1) {
    cout << "returning...(size=" << size << ")" << endl;
    return randlist;
  }
  else {
    if (any_of(randlist.begin(), randlist.end(),[randnum](int elt) {return randnum == elt;})){
      cout << "repeating number: " << randnum << endl;
      random(size, range, rand() % range + 1, randlist);
      return randlist;
  }
    else {
      cout << "size " << size << " randnum " << randnum << endl;
      randlist.push_back(randnum);
      random(size-1, range, rand() % range + 1, randlist);
      return randlist; }
  }
}


int main (int argc, char *argv[]) {
  srand (time(NULL));
  vector<int> dummy{}; 
  vector<int> uniqrandnums = random(10, 20, (rand() % 20) + 1, dummy );
  cout << "here is my unique random numbers list: " ;
  for_each(uniqrandnums.begin(),uniqrandnums.end(), [](int n){cout << n << ' ';});
  }

To keep track of the unique random numbers, I've added 2 cout lines inside the recursive function random. The recursive function seems to operate correctly but it can't return back the resulting vector<int list randlist correctly; it seems to return a list with just the first random number it found.

Note: Reckoning that the function would finally return from here:

  if (size < 1) {
    cout << "returning...(size=" << size << ")" << endl;
    return randlist;
  }

I haven't initially added the last 2 return randlist; lines inside the recursive function but as is, it gave compilation warning control reaches end of non-void function [-Wreturn-type] That's why I've added those 2 return statements but it made just the warnings go away and it didn't help operate correctly.

Question: How to arrange the code so the recursive function random returns the full list in a correct manner?

Aucun commentaire:

Enregistrer un commentaire