Solidity 솔리디티 강좌 24강 : 반복문 응용 - linear search

flowing1ife·2023년 7월 7일
0

[ Solidity 깨부수기 ]

목록 보기
24/29
post-thumbnail

Solidity 솔리디티 강좌 24강 : 반복문 응용 - linear search

이번엔 반복문을 응용하여 solidity에서 linear search를 구현해보자.


linear search

// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;

contract lec24{
    event CountryIndexName(uint256 indexed _index, string _name);
    string[] private countryList = ["South Korea", "North Korea", "USA", "China","Japan"];

    function linearSearch(string memory _search) public view returns (uint256, string memory){
        for(uint256 i=0; i < countryList.length; i++){
          
            if(keccak256(bytes(countryList[i]))==keccak256(bytes(_search))){
                return (i, countryList[i]);
            }
        }
        return (0, "Nothing");
    }
}

linearSearch 함수는 인자로 받은 _search 값을 받아 반복문을 돌며 이 값과 같은 값이 존재하는지 찾는다. 그리고 찾으면 i, countryList[i] 를, 찾지 못하면 (0, "Nothing")을 return 한다.

📍 이때 주의할 점은 다른 프로그래밍 언어와 다르게 solidity 내에서는 string을 비교할 수 없다는 것이다. 따라서 위처럼 string을 bytes화 한 후, keccak256을 통해 해시화 하여 비교하여야 한다.


🎉  Result

USA를 인자로 넘겨서 linearSearch를 호출하면 countryList 안에 USA가 존재하기 때문에 그에 해당하는 index와 값을 return 한다.

hello를 인자로 넘겨서 linearSearch를 호출하면 countryList 안에 hello가 존재하지 않기 때문에 (0, "Nothing")을 return 한다.


출처 및 참고 자료

profile
👩🏻‍💻 Backend Engineer, Contract Developer

0개의 댓글