Submission 6280b5fa...

ChallengeRemove duplicate elements
Submitterhyszeth.eth
Submitted at2018-36-22
Gas used880488
/**
 * This file is part of the 1st Solidity Gas Golfing Contest.
 *
 * This work is licensed under Creative Commons Attribution ShareAlike 3.0.
 * https://creativecommons.org/licenses/by-sa/3.0/
 */

pragma solidity 0.4.24;

contract Unique {
    /**
     * @dev Removes all but the first occurrence of each element from a list of
     *      integers, preserving the order of original elements, and returns the list.
     *
     * The input list may be of any length.
     *
     * @param input The list of integers to uniquify.
     * @return The input list, with any duplicate elements removed.
     */


    function uniquify(uint[] input) public pure returns(uint[] ret) {
        if(input.length == 0) return ret;
        uint lookupLen = 2053;
        bool[] memory lookup = new bool[](lookupLen);
        uint[] memory uniqueList = new uint[](input.length);
        uint nDups;
        uint uniqueIndex;

        for(uint i = 0; i < input.length; ++i) {
            uint current = input[i];
            uint quickHash = /*uint(keccak256(*/current/*))*/ % lookupLen;
            if(lookup[quickHash]) {
                // maybe a dup. See if it exists in unique list.
                uint j;
                for(j = 0; j < uniqueIndex; ++j) {
                    if(current == uniqueList[j]) {
                        break;
                    }
                }
                if(j == uniqueIndex) {
                    // false positive
                    uniqueList[uniqueIndex++] = current;
                }
            } else {
                uniqueList[uniqueIndex++] = current;
                lookup[quickHash] = true;
            }
        }
        ret = new uint[](uniqueIndex);
        for(i = 0; i < uniqueIndex; ++i) {
            ret[i] = uniqueList[i];
        }

        return ret;
    }
}