Skip to content

Commit

Permalink
Count up for Fisher Yates instead of counting down.
Browse files Browse the repository at this point in the history
  • Loading branch information
ple13 committed Jan 10, 2024
1 parent f0c4f39 commit 91b65c7
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 4 deletions.
5 changes: 3 additions & 2 deletions src/main/cc/any_sketch/crypto/shuffle.cc
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,14 @@ absl::Status SecureShuffleWithSeed(std::vector<uint32_t>& data,
prng->GeneratePseudorandomBytes(data.size() * sizeof(absl::uint128)));

absl::uint128* rand = (absl::uint128*)arr.data();
for (int64_t i = data.size() - 1; i >= 1; i--) {
int64_t num_elements = data.size();
for (int64_t i = 0; i < num_elements - 1; i++) {
// Ideally, to make sure that the sampled permutation is not biased, rand[i]
// needs to be re-sampled if rand[i] >= 2^128 - (2^128 % (i+1)). However,
// the probability that this happens with any i in [1; data.size() - 1] is
// less than (data.size())^2/2^{128}, which is less than 2^{-40} for any
// input vector of size less than 2^{43}.
uint64_t index = static_cast<uint64_t>(rand[i] % (i + 1));
uint64_t index = i + static_cast<uint64_t>(rand[i] % (num_elements - i));
// Swaps the element at current position with the one at position index.
std::swap(data[i], data[index]);
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/cc/any_sketch/crypto/shuffle.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ namespace wfa::measurement::common::crypto {

// Shuffles the vector data using Fisher-Yates approach. Let n be the size of
// data, the Fisher-Yates shuffle is as below.
// For i = (n-1) to 1:
// Draws a random value j in the range [0; i]
// For i = 0 to (n-2):
// Draws a random value j in the range [i; n-1]
// Swaps data[i] and data[j]
absl::Status SecureShuffleWithSeed(std::vector<uint32_t>& data,
const any_sketch::PrngSeed& seed);
Expand Down

0 comments on commit 91b65c7

Please sign in to comment.