Solidity

任何人都可以將 findMostOccurringString 的這個功能設為無事務(視圖或純)嗎?

  • July 3, 2022

我想製作一個實用程序contract(或更準確地說是 a library),它可以從給定的字元串數組中計算模式(最大出現)字元串。

這是我的方法:

//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;
   }
}

因此,如果任何人都可以進一步修改它,以避免使用mapping或通過將函式設為 or 來使該函式成為無事務,以便可以轉換或以 a 的形式使用該合約view,那麼我’我真的很感激。pure``library

您可以使用此程式碼執行此操作

//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))));
}

}

引用自:https://ethereum.stackexchange.com/questions/131110