1

I want to make a utility contract (or more precisely a library) that can calculate the mode (max occurring) string from the given array of strings.

Here's my approach for the same:

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

contract CalculateStringsMode {

    mapping(string => uint256) public stringCountMapping;

    string public mode = "";

    function findMostOccurringString(string[] memory arr)
        public
        returns (string memory)
    {

        // string memory mode = "";

        uint256 maxCount = 0;

        uint256[] memory countList = new uint256[](arr.length);

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

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

        for (uint256 i = 0; i < countList.length; i++) {
            if (countList[i] > maxCount) {
                maxCount = countList[i];
            }
        }

        for (uint256 i = 0; i < arr.length; i++) {
            if (maxCount == stringCountMapping[arr[i]]) {
                mode = arr[i];
                break;
            }
        }

        return mode;
    }
}

So, if anyone can further modify this in a way to avoid the use of mapping or to make the function as transaction-less by making that of type view or pure, so that this contract can be converted or used in the form of a library, then I'll really appreciate that.

1 Answer 1

1

You can do it using this code

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

contract CalculateStringsMode {


function findMostOccurringString(string[] memory arr)
    public
    pure
    returns (string memory)
{
    
    string memory mode = "";

    uint256 maxCount = 0;

    for (uint256 i = 0; i < arr.length; i++) {
        uint256 count = getCount(arr,arr[i]);
        if(count>maxCount){
            maxCount=count;
            mode = arr[i];
        }
    }

    return mode;
}

function getCount(string[] memory arr,string memory element) private pure returns(uint256 count){
    for(uint256 i=0;i<arr.length;i++){
        if(compareStrings(arr[i],element)){
            count++;
        }
    }
}

function compareStrings(string memory a, string memory b)
    private
    pure
    returns (bool)
{
    return (keccak256(abi.encodePacked((a))) ==
        keccak256(abi.encodePacked((b))));
}

}

1

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.