Created
September 29, 2024 12:55
-
-
Save SpiralOutDotEu/66ee81563ee39a65836cb47ad9cd97d2 to your computer and use it in GitHub Desktop.
Solidity Library Use
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "./ArrayLib.sol"; | |
contract ArrayContract { | |
using ArrayLib for uint256[]; // Import the library for use with uint256[] arrays | |
uint256[] private arr; // The array to store uint256 elements | |
/// @notice Adds an element to the array. | |
/// @param element The element to be added. | |
function addElement(uint256 element) public { | |
arr.push(element); | |
} | |
/// @notice Calls the library to shuffle the array using a random seed. | |
/// @param seed A random seed used to shuffle the array. You can use block timestamp or other data. | |
function shuffleArray(uint256 seed) public { | |
arr.shuffle(seed); // Calls the `shuffle` function from the ArrayLib library | |
} | |
/// @notice Returns the array. | |
/// @return The current array of uint256 elements. | |
function getArray() public view returns (uint256[] memory) { | |
return arr; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
library ArrayLib { | |
/// @notice Shuffles an array of uint256 using the Fisher-Yates algorithm. | |
/// @param arr The array of uint256 to be shuffled. | |
/// @param seed A random seed to ensure the shuffle result is non-deterministic. | |
function shuffle(uint256[] storage arr, uint256 seed) internal { | |
uint256 n = arr.length; | |
if (n <= 1) return; // No need to shuffle if the array has 1 or 0 elements | |
for (uint256 i = n - 1; i > 0; i--) { | |
// Generate a pseudo-random index between 0 and i | |
uint256 j = uint256(keccak256(abi.encode(seed, i))) % (i + 1); | |
// Swap arr[i] and arr[j] | |
(arr[i], arr[j]) = (arr[j], arr[i]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment