Uploaded image for project: 'Commons RNG'
  1. Commons RNG
  2. RNG-61

PermutationSampler shuffle contains unnecessary conditional

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Trivial
    • Resolution: Fixed
    • None
    • 1.2
    • sampling
    • None

    Description

      The Fisher-Yates algorithm in the PermutationSampler has a conditional if statement within the loop that checks if the step is the first in the loop. It then swaps a position with itself. For example for the towards head variant:

      for (int i = 0; i <= start; i++) {
          final int target;
          // Check for start
          if (i == start) {
              target = start; // this means target == i
          } else {
              target = rng.nextInt(start - i + 1) + i;
          }
          // if target == i then this step is not needed.
          final int temp = list[target];
          list[target] = list[i];
          list[i] = temp;
      }
      

      This can be removed by altering the iteration loop:

      for (int i = start; i > 0; i--) {
          final int target = rng.nextInt(i + 1);
          final int temp = list[target];
          list[target] = list[i];
          list[i] = temp;
      }
      

      An equivalent fix is available for the shuffle towards the tail.

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              aherbert Alex Herbert
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: