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 ;

        RandomNum += random;


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

1 Answer 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++) {
  • i dont care about the gas fees for the moment but do you know how to implement it on the code?
    – Bandock
    Commented Dec 25, 2018 at 23:29
  • Added example of iteration Commented Dec 26, 2018 at 3:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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