From 91b65c73f933bdc75f257d0ee4e94d4354b9e1f3 Mon Sep 17 00:00:00 2001 From: Phi Hung Le Date: Wed, 10 Jan 2024 05:13:00 +0000 Subject: [PATCH] Count up for Fisher Yates instead of counting down. --- src/main/cc/any_sketch/crypto/shuffle.cc | 5 +++-- src/main/cc/any_sketch/crypto/shuffle.h | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/cc/any_sketch/crypto/shuffle.cc b/src/main/cc/any_sketch/crypto/shuffle.cc index c4be185..81cd3b2 100644 --- a/src/main/cc/any_sketch/crypto/shuffle.cc +++ b/src/main/cc/any_sketch/crypto/shuffle.cc @@ -39,13 +39,14 @@ absl::Status SecureShuffleWithSeed(std::vector& 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(rand[i] % (i + 1)); + uint64_t index = i + static_cast(rand[i] % (num_elements - i)); // Swaps the element at current position with the one at position index. std::swap(data[i], data[index]); } diff --git a/src/main/cc/any_sketch/crypto/shuffle.h b/src/main/cc/any_sketch/crypto/shuffle.h index de4d04b..d447831 100644 --- a/src/main/cc/any_sketch/crypto/shuffle.h +++ b/src/main/cc/any_sketch/crypto/shuffle.h @@ -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& data, const any_sketch::PrngSeed& seed);