Submission ac6c8c5f...

ChallengeRemove duplicate elements
Submitter0xabcdef0db461f2f...
Submitted at2018-01-03
Gas used548138
/**
 * 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) {
        uint inLen = input.length;
        uint outLen;
        if (inLen < 2) {
            return input;
        } else if (inLen == 2) {
            outLen = input[0] == input[1] ? 1 : 2;
        } else if (inLen <= 32) {
            outLen = uniquifyFew(input);
        } else {
            outLen = uniquifyMore(input);
        }
        if (inLen == outLen) {
            return input;
        }
        else {
            uint[] memory output = new uint[](outLen);
            for (uint j = 0; j < outLen; j++) {
                output[j] = input[j];
            }
            return output;
        }
    }

    function uniquifyFew(uint[] input) internal pure returns(uint) {
        uint filter;
        uint outLen;
        for (uint i = 0; i < input.length; i++) {
            uint h = input[i] % 255;
            uint y = (1 << h);
            if (filter & y == 0) {
                filter = filter | y;
                input[outLen] = input[i];
                outLen += 1;
            }
        }
        return outLen;
    }

    function uniquifyMore(uint[] input) internal pure returns(uint) {
        uint filter;
        uint outLen;
        for (uint i = 0; i < input.length; i++) {
            uint y = (1 << input[i] % 241) & (1 << input[i] % 151);
            if (filter & y == 0) {
                filter = filter | y;
                input[outLen] = input[i];
                outLen += 1;
            }
        }
        return outLen;
    }
}