Skip to content

Instantly share code, notes, and snippets.

@fassko
Created July 26, 2023 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fassko/e0e195504e0e7aa538edde1bb9ad2bb2 to your computer and use it in GitHub Desktop.
Save fassko/e0e195504e0e7aa538edde1bb9ad2bb2 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.21+commit.d9974bed.js&optimize=false&runs=200&gist=
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
contract Set {
// holds items
// can enumerate over objects
uint256[] public items;
// holds ids
mapping(uint256 => uint256) private indexes;
// insert element in the set
function insert(uint256 value) public {
require(!contains(value), "Already containts value");
// if (indexes[value] == 0) {
// if (!contains(value)) {
items.push(value);
indexes[value] = items.length;
// }
}
// remove element from the set
function remove(uint256 value) public {
require(contains(value), "Set does not contain such value");
// find out the index
uint256 index = indexes[value];
// moves last element to the place of the value
// so there are no free spaces in the array
uint256 lastValue = items[items.length - 1];
items[index - 1] = lastValue;
indexes[lastValue] = index;
// delete the index
delete indexes[value];
// deletes last element and reduces array size
items.pop();
}
// check if the set containts the value
function contains(uint256 value) public view returns(bool) {
return indexes[value] != 0;
}
// length of the Set
function length() public view returns(uint256) {
return items.length;
}
// list all items in the Set
function values() public view returns(uint256[] memory) {
return items;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment