0

How to check if number is not in array and then push it

function randomnumber() public returns (uint){
    for(uint i=1; i< 50; i++){
    uint random = uint(keccak256(block.blockhash(block.number -1 ),RandomNum)) % 50 ;

        Numbers.push(random); 
        RandomNum += random;
   }

     }

function getnumbers() public view returns(uint[]){
    return  Numbers;
}
1

With arrays. only options is to iterate over the array and check if number is present. This will become expensive as array size grows.

Another options is to maintain an array as well as a mapping.

You can check cost of maintaining and array and a mapping for numbers.

  • Array provides capability of iteration
  • With mapping, you can check presence of a number in O(1)

It does increase storage cost by 2X, so you have to implement it and compare with iteration to estimate cost for your usecase.

Example of iteration :

pragma solidity ^0.5.2;


contract ArrayTest {
    uint [] public numbers;
    function getNumberCount() public view returns(uint count) {
        return numbers.length;
    }
    function addIfNotPresent(uint num) public{
        uint arrayLength = numbers.length;
        bool found=false;
        for (uint i=0; i<arrayLength; i++) {
            if(numbers[i]==num){
                found=true;
                break;
            }
        }
        if(!found){
            numbers.push(num);
        }
    }
}
| improve this answer | |
  • i dont care about the gas fees for the moment but do you know how to implement it on the code? – Bandock Dec 25 '18 at 23:29
  • Added example of iteration – Shamit Verma Dec 26 '18 at 3:49

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.