Skip to content

Updating the STL random_shuffle for permutations article #143

@K-Maehashi

Description

@K-Maehashi

Hello, I found random_shufle() used in STL random_shuffle for permutations was not available in C++17. The following code returns the same result, and I thought it would be helpful for other users. Since this is a minor change to the article, I opened this issue instead of sending a pull request.

#include <Rcpp.h>

inline int randWrapper(const int n) { return floor(unif_rand()*n); }

// [[Rcpp::export]]
Rcpp::NumericVector randomShuffle(Rcpp::NumericVector a) {

    // clone a into b to leave a alone
    Rcpp::NumericVector b = Rcpp::clone(a);
    int n = b.size();
    int j;

    // Fisher-Yates Shuffle Algorithm
    for (int i = 0; i < n - 1; i++)
    {
      j = i + randWrapper(n - i);
      std::swap(b[i], b[j]);
    }
    return b;
}

Test

sourceCpp(code =
'
#include <Rcpp.h>

inline int randWrapper(const int n) { return floor(unif_rand()*n); }

// [[Rcpp::export]]
Rcpp::NumericVector randomShuffle_1(Rcpp::NumericVector a) {  // Currently on Rcpp Gallery

    // clone a into b to leave a alone
    Rcpp::NumericVector b = Rcpp::clone(a);

    std::random_shuffle(b.begin(), b.end(), randWrapper);

    return b;
}

// [[Rcpp::export]]
Rcpp::NumericVector randomShuffle_2(Rcpp::NumericVector a) {

    // clone a into b to leave a alone
    Rcpp::NumericVector b = Rcpp::clone(a);
    int n = b.size();
    int j;

    // Fisher-Yates Shuffle Algorithm
    for (int i = 0; i < n - 1; i++)
    {
      j = i + randWrapper(n - i);
      std::swap(b[i], b[j]);
    }
    return b;
}
'
)

a <- 1:8
set.seed(42)
randomShuffle_1(a)
#> [1] 8 1 4 2 7 5 3 6
set.seed(42)
randomShuffle_2(a)
#> [1] 8 1 4 2 7 5 3 6

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions