Submission 977fe230...

ChallengeRemove duplicate elements
Submitterricmoo.firefly.eth
Submitted at
Gas used3038223
/**
 * 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/
 *
 *  Author: Richard Moore <[email protected]>
 *  Date:   May 24, 2018
 */

pragma solidity 0.4.24;

contract Unique {
    function isUnique(uint[] input, uint len, uint value) private pure returns(bool) {
        for(uint i = 0; i < len; i++) {
            if(input[i] == value) return false;
        }
        return true;
    }

    /**
     * @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) {

        uint256 bloomFilter1 = 0;
        uint256 bloomFilter2 = 0;

        uint ptr = 0;
        for (uint256 i = 0; i < input.length; i++) {
            uint256 v = input[i];

            bool unique = false;

            uint256 filter1 = (uint256(1) << uint8(v * 7879));
            uint256 filter2 = (uint256(1) << uint8(v * 6661));
            if ((bloomFilter1 & filter1) != filter1 || (bloomFilter2 & filter2) != filter2 || isUnique(input, i, v)) {
                input[ptr++] = v;
                bloomFilter1 |= filter1;
                bloomFilter2 |= filter2;
            }
        }

        ret = new uint[](ptr);
        for(i = 0; i < ret.length; i++) {
            ret[i] = input[i];
        }

        return ret;
   }
}