简体   繁体   中英

Efficiency of an algorithm for scrambled input

I am currently writing a program, its done for the most part, in CPP that takes in a file, with numbered indices and then pushes out a scrambled quiz based on the initial input, so that no two are, theroretically, the same. This is the code

   // There has to be a more efficient way of doing this...                      
  for (int tempCounter(inputCounter);
       inputCounter != 0;
       /* Blank on Purpose*/) {
    randInput = (rand() % tempCounter) + 1;

    inputIter = find (scrambledArray.begin(),
                      scrambledArray.end(),
                      randInput);

    // Checks if the value passed in is within the given vector, no duplicates.
    if (inputIter == scrambledArray.end()) {
      --inputCounter;
      scrambledArray.push_back(randInput);
    }
  }

The first comment states my problem. It will not happen, under normal circumstances, but what about if this were being applied to a larger application standpoint. This works, but it is highly inefficient should the user want to scramble 10000 or so results. I feel as if in that point this would be highly inefficient. I'm not speaking about the efficiency of the code, as in shortening some sequences and compacting it to make it a bit prettier, I was more or less teaching someone, and upon getting to this point I came to the conclusion that this could be done in a way better manner, just don't know which way it could be...

So you want just the numbers 1..N shuffled? Yes, there is a more efficient way of doing that. You can use std::iota to construct your vector :

// first, construct your vector:
std::vector<int> scrambled(N);
std::iota(scrambled.begin(), scrambled.end(), 1);

And then std::shuffle it:

std::shuffle(scrambled.begin(), scrambled.end(),
             std::mt19937{std::random_device{}()});

If you don't have C++11, the above would look like:

std::vector<int> scrambled;
scrambled.reserve(N);
for (int i = 1; i <= N; ++i) {
    scrambled.push_back(i);
}
std::random_shuffle(scrambled.begin(), scrambled.end());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM