2

I have the following array of uint8s in Solidity:

[8, 1253, 54, 777, 553]

There needs to be a function that gets one input uint8 number and checks to see whether or not the input number matches with any of the uint8 numbers in the array above.

What would be the best way to implement such a function?

1

The easiest way would be to write a for loop:

function check(uint8 n) public returns (bool) {
    for (uint256 i = 0; i < arr.length; i++) {
        if (arr[i] == n) {
            return true;
        }
    }
    return false;
}

But if you're concerned about gas costs, have the client tell you exactly where in the array the number is. (The client can find this position offline.)

function check(uint8 n, uint256 position) public returns (bool) {
    return arr[position] == n;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.