Submission 2013178b...

ChallengeRemove duplicate elements
Submittersggc.yuetloo.eth
Submitted at2018-44-24
Gas used1026084
/**
 * Author: Yuet Loo Wong
 * 
 * This is a modified version of the original contract from
 *   https://github.com/arachnid/sggc.git
 * 
 * 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 {
    function isUnique(uint[] input, uint len, uint lo, uint hi, uint value) private pure returns(bool) {
         
        if( value > hi || value < lo ) return true;

        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) {
        if( input.length < 2 ) return input;

        uint ptr = 1;
        uint lo = input[0];
        uint hi = lo;
        for(uint i = ptr; i < input.length; i++) {
            if( isUnique(input, ptr, lo, hi, input[i]) )
            {
                input[ptr++] = input[i];
                if( input[i] > hi ) hi = input[i];
                if( input[i] < lo ) lo = input[i];
            }
        }

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

        return ret;
    }
}