Skip to content

Commit

Permalink
Add random element selection functions to PseudoRandomX module
Browse files Browse the repository at this point in the history
  • Loading branch information
Gekctek committed Jan 14, 2024
1 parent dc9e892 commit 129a07c
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/PseudoRandomX.mo
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,24 @@ module Module {
return randomValue <= trueCount;
};

public func nextBufferElement<T>(buffer : Buffer.Buffer<T>) : T {
let bufferSize = buffer.size();
if (bufferSize == 0) {
Debug.trap("Cannot get random element from empty buffer");
};
let randomIndex = nextNat(0, bufferSize - 1);
buffer.get(randomIndex);
};

public func nextArrayElement<T>(array : [T]) : T {
let arraySize = array.size();
if (arraySize == 0) {
Debug.trap("Cannot get random element from empty buffer");
};
let randomIndex = nextNat(0, arraySize - 1);
array[randomIndex];
};

public func shuffleBuffer<T>(buffer : Buffer.Buffer<T>) {
let bufferSize = buffer.size();
if (bufferSize == 0) {
Expand All @@ -75,10 +93,10 @@ module Module {
var i : Nat = bufferSize;
for (item in buffer.vals()) {
i -= 1;
let randIdx = nextNat(0, i);
let randomIndex = nextNat(0, i);
let temp = buffer.get(i);
buffer.put(i, buffer.get(randIdx));
buffer.put(randIdx, temp);
buffer.put(i, buffer.get(randomIndex));
buffer.put(randomIndex, temp);
};
};
};
Expand Down

0 comments on commit 129a07c

Please sign in to comment.