Submission 500e3b1f...

ChallengeRemove duplicate elements
Submitter0xea674fdde714fd9...
Submitted at2018-07-27
Gas used489795
/**
 * 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 len = input.length;
        uint lenny = len * 3 + 2;
        if (len <= 1) {
            return input;
        }

        uint ptr = 0;
        ret = new uint[](lenny);

        for(uint i = 0; i < len; i++) {
            uint value = input[i];
            uint valueMod = value % (lenny);
            uint storedValue = ret[valueMod];
            if (storedValue == 0) {
                ret[valueMod] = value + 1;
                input[ptr++] = value;
            } else if (storedValue != value + 1) {
                uint tempRet;
                while (true) {
                    valueMod = (valueMod + 1) % lenny;
                    tempRet = ret[valueMod];
                    if (tempRet == value + 1) break;
                    if (tempRet == 0) {
                        ret[valueMod] = value + 1;
                        input[ptr++] = value;
                        break;
                    }
                }
            }
        }

        ret = new uint[](ptr);

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

        return ret;
    }

}