Submission 197bad0d...

ChallengeRemove duplicate elements
Submitterhyszeth.eth
Submitted at2018-21-23
Gas used452470
/**
 * 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 {
    //event E(uint);
    /**
     * @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.
     */

// TRY THESE http://www.cse.yorku.ca/~oz/hash.html

    uint constant HASH_TABLE_SIZE = 733;
    uint constant HASH_TABLE_MOD = HASH_TABLE_SIZE - 1;

    function uniquify(uint[] input)
    public
    pure
    returns(uint[] ret) {
        uint inputLength = input.length;
        if(inputLength == 0) return ret;
        uint uniqueIndex;
        uint[HASH_TABLE_SIZE] memory cache;

        uint nDups;
        uint miss;
        for(uint i = 0; i < inputLength; ++i) {
            uint current = input[i];
            uint16 quickHash = uint16(current % HASH_TABLE_SIZE);
            uint currentCache;
            uint currentCacheOffset = current + 1;
            if((currentCache=cache[quickHash]) > 0) {
                // Scan unique list for duplicates
                while(currentCache != currentCacheOffset) {
                    // Look for next spot
                    if(quickHash < HASH_TABLE_SIZE) currentCache = cache[++quickHash];
                    else currentCache = cache[(quickHash = 0)];
                    if(currentCache == 0) {
                        if(uniqueIndex != i) input[uniqueIndex] = current;
                        uniqueIndex++;
                        cache[quickHash] = currentCacheOffset;
                        break;
                    }
                }
            } else {
                if(uniqueIndex != i) input[uniqueIndex] = current;
                uniqueIndex++;
                cache[quickHash] = currentCacheOffset;
            }
        }
        //emit E(miss);
        ret = new uint[](uniqueIndex);
        for(i = 0; i < uniqueIndex; ++i) {
            ret[i] = input[i];
        }
        return ret;
    }
}