Am Fri, 20 Dec 2013 15:53:08 +0100
schrieb "marcpmichel" <>:

> I participated in the "global day of code retreat 2013", and we 
> had to do refactoring on a very ugly piece of code which was 
> available on many languages.
> But there was no D version, so I made one (based on the java 
> version) and pull-requested it.
> Here is the ugly thing :

bool notAWinner;
do {
    game.roll(rand.front() % 5 + 1);

    if (rand.front() % 9 == 7) {        // <-- WARNING! WARNING!
        notAWinner = game.wrongAnswer();
    } else {
        notAWinner = game.wasCorrectlyAnswered();
} while (notAWinner);

This kind of code is a dangerous gamble.

This is a story about my student time: I once sat in a Java
class and one of the students had an issue with their code not
outputting anything and not quitting either. When the teacher
came around, we found only one obvious point for an infinite
loop could occur and it looked like this:

  Random rng = new Random();
  int count = 0;

  // Visit all items once
  while (count < list.size()) {
    bool found = false;
    while (!found) {
      int idx = rng.nextInt() % list.size();
      if (list[idx].visited == false) {
        list[idx].visited = true;
        found = true;

[I don't remember the exact lines, but this is the gist of it.]
The teacher himself wrote this code and presented it to the
class as a simple way to iterate over a list in random order
which was part of todays programming task.
It didn't cause issues for any of the other students, but on
this particular computer the random seed that the Random ctor
chose caused a degenerate case where it never hit any of the 3
remaining indexes of the list.

The morale is that "uniform" random numbers doesn't imply that
every value in the range will eventually be generated once!


Reply via email to