0

I'm trying to figure out how to make this function work in such a way that when you compile and interact with the hasDups function, it will print either TRUE or FALSE, depending on which array you wish to call. What else am I missing in my code?

pragma solidity ^0.8.9;

contract ReturnArrayBool {

    uint256[] arr1 = [1,2,3,4,5];
    uint256[] arr2 = [1,2,3,4,5,5];
    
    function hasDups(uint256[] memory arr) public pure returns(bool){

        for(uint256 i = 0; i < arr.length; i++) {
            uint256 digit = arr[i];

            for(uint256 j = i+1; j < arr.length; j++) {
                if(arr[j] == digit) {
                    return true;
                }
            }   
        }
        return false;
    }
}
2
  • 1
    Could you clarify your question? I tried that code and sent an array without duplicates and it returned false, then I sent an array with duplicates and it returned true, so it is working alright. Commented Aug 19, 2022 at 19:34
  • For example, I am trying to set it up in such a way where if I choose to index arr1 with the hardcoded values of [1,2,3,4,5] then I should get a return value of FALSE and TRUE for arr2. Does that help?
    – antharithm
    Commented Aug 19, 2022 at 19:44

1 Answer 1

0

To dynamically be able to select a state array to work on, you could put it in a mapping with a key to identify it:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;

contract ReturnArrayBool {

    mapping(uint256 => uint256[]) public hardCodedArrays;

    constructor() {
        hardCodedArrays[1] = [1,2,3,4,5];
        hardCodedArrays[2] = [1,2,3,4,5,5];
    }
    
    function hasDups(uint256 arrayIndex) public view returns(bool){
        uint256[] memory arr = hardCodedArrays[arrayIndex];
        for(uint256 i = 0; i < arr.length; i++) {
            uint256 digit = arr[i];

            for(uint256 j = i+1; j < arr.length; j++) {
                if(arr[j] == digit) {
                    return true;
                }
            }   
        }
        return false;
    }

    function addElements(uint256 toArray, uint256 element) public {
        hardCodedArrays[toArray].push(element);
    }

}

I put a simple example. You could dynamically add elements. You could write logic to remove elements, search for elements, etc.

Notice that I used a 1 as the key of the first array, and a 2 as the key of the second array.

You could then call like from Remix like:

enter image description here

And:

enter image description here

1
  • 1
    This is exactly what I was looking to do! Thank you so much
    – antharithm
    Commented Aug 19, 2022 at 20:13

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.