Skip to content

seq: fix duplicate indices in sample_floyd#1755

Closed
PrarthanaPurohit wants to merge 1 commit intorust-random:masterfrom
PrarthanaPurohit:fix/sample-floyd-duplicate-indices
Closed

seq: fix duplicate indices in sample_floyd#1755
PrarthanaPurohit wants to merge 1 commit intorust-random:masterfrom
PrarthanaPurohit:fix/sample-floyd-duplicate-indices

Conversation

@PrarthanaPurohit
Copy link

Fix duplicate indices in sample_floyd

Problem

sample_floyd implements Floyd's combination algorithm to sample
amount distinct indices from 0..length. The algorithm has two cases
for each step:

  • If the randomly picked value t is already in the set → add j instead
  • If t is new → add t

The previous code unconditionally called indices.push(t) after the
if let block, so when t was a duplicate it was both replaced by j
at its old position and re-appended — producing duplicate indices
in the output.

Fix

Move push(t) into the else branch so it only runs when t is
a genuinely new element:

// Before
if let Some(pos) = indices.iter().position(|&x| x == t) {
    indices[pos] = j;
}
indices.push(t); // always ran — bug!

// After
if let Some(pos) = indices.iter().position(|&x| x == t) {
    indices[pos] = j;
} else {
    indices.push(t); // only when t is new
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant