[Solved] Pseudo code to C++ code [closed]


Can this be done better using standard library functions? Hell yes.
At the very least,

temp = RandomizeArray[i];
RandomizeArray[i] = RandomizeArray[j];
RandomizeArray[j] = temp;

Is all replaced by

std::swap(RandomizeArray[i], RandomizeArray[j]);

The whole process is sort-of replaced (but not quite. Almost certainly a different backing algorithm) by the std::random_shuffle family, but that would be totally defeating the point of the exercise.

Unless the examiner is the sort to go, “Oh! He recognized the algorithm and suggested a time saving replacement! Excellent! Excellent!” Look for these sorts of bosses. They are generally more fun to work for.

Anyway… Is The OP’s solution a correct interpretation of the Pseudo Code?

No.

Take a look at int j = rand() % max_i + i; and run though the possible range of values for j as you proceed through the values of i.

i = 0 : [0 .. max_i] 
i = 1 : [1 .. max_i + 1]
i = 2 : [2 .. max_i + 2]

Note the upper bound is moving, violating the contract of the Pseudo Code. As of i = 1, j may be outside the range of RandomizeArray and it will only get more likely from there on up.

Using a slight modification, int j = rand() % (max_i - i) + i;

i = 0 : [0 .. max_i] 
i = 1 : [1 .. max_i]
i = 2 : [2 .. max_i]

Extra note: rand sucks. C++11 and better have a number of fun toys for generating much better random numbers. A uniform_int_distribution is probably what you’d want here.

1

solved Pseudo code to C++ code [closed]