Skip to content

The shuffle function never shuffles the first element into the first spot. #6

Open

Description

@bwinton

Running the code:

use macroquad::{logging as log, rand::ChooseRandom};

#[macroquad::main(window_conf)]
async fn main() {
    let mut results = [0;4];
    for _ in 0..100 {
        let mut test = vec![0,1,2,3];
        test.shuffle();
        results[test[0]] += 1;
    }
    log::info!("results: {:?}", results);
}

consistently gives the output:

results: [0, 39, 33, 28]

whereas I'd expect something more like:

results: [25, 26, 25, 24]

Activity

  1. bwinton commented on Feb 11, 2021

    @bwinton
    Author

    (I added a copy-ish of the function to my code that looks like:

    pub trait ChooseRandom<T> {
        fn shuffle(&mut self);
    }
    
    impl<T> ChooseRandom<T> for Vec<T> {
        fn shuffle(&mut self) {
            for i in (1..self.len()).rev() {
                let j = gen_range(0, i+1);
                self.swap(i, j);
            }
        }
    }
    

    and that gives much better results, for what it's worth. 🙂)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions