'how to check one value exist in array - Solidity
i need to check if all the values in X array exist in Y array do something. how to can i check this? (Order does not matter)
contract test {
uint[] numbers1;
uint[] numbers2;
function push1(uint num1, uint num2, uint num3) public {
numbers1.push(num1);
numbers1.push(num2);
numbers1.push(num3);
}
function push2(uint num1, uint num2, uint num3) public {
numbers2.push(num1);
numbers2.push(num2);
numbers2.push(num3);
}
}
how can i check all numbers in numbers1 exist in numbers2 or not?
Solution 1:[1]
There are two approaches.
You can create a view function (docs) that loops through the array and returns true if the item is found. Mind that a view function can be invoked using a gas-free read-only call instead of a (read-write) transaction costing gas fees.
function exists1(uint num) public view returns (bool) {
for (uint i = 0; i < numbers1.length; i++) {
if (numbers1[i] == num) {
return true;
}
}
return false;
}
This approach has a linear complexity. So if you need to validate the value existence during a transaction, it might be costly depending on the total amount of items in the array.
So there's a second approach - duplicate the values as keys of a mapping (docs) that can be accessed directly through its key. There's a constant complexity to search the value but it costs double to store the value.
uint[] numbers1;
mapping(uint => bool) public exists1; // default value for each key is false
function push1(uint num1, uint num2, uint num3) public {
numbers1.push(num1);
numbers1.push(num2);
numbers1.push(num3);
exists1[num1] = true;
exists1[num2] = true;
exists1[num3] = true;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Petr Hejda |
