Submission e2cddbc4...

ChallengeRemove duplicate elements
Submitterhyszeth.eth
Submitted at2018-36-23
Gas used434690
/**
 * 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;
    uint constant RAND_OFFSET = 0x613c12789c3f663a544355053c9e1e25d50176d60796a155f553aa0f8445ee66;

    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 current;
        uint quickHash;
        for(uint i = 0; i < inputLength; ++i) {
            current = input[i];
            quickHash = current % HASH_TABLE_SIZE;
            uint currentCache;
            uint currentCacheOffset = current + RAND_OFFSET;
            if((currentCache=cache[quickHash]) > 0) {
                // Scan unique list for duplicates
                while(currentCache != currentCacheOffset) {
                    // Look for next spot
                    currentCache = cache[(quickHash=(quickHash ^ RAND_OFFSET) % HASH_TABLE_SIZE)];
                    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;
            }
        }

        // Copy unique elements from `input` to `ret`
        // Grouping together in this case saved about 10k gas.
        ret = new uint[](uniqueIndex);
        uint max = uniqueIndex/10 * 10;
        i = 0;
        while(i < max) {
            ret[i++] = input[i];
            ret[i++] = input[i];
            ret[i++] = input[i];
            ret[i++] = input[i];
            ret[i++] = input[i];
            ret[i++] = input[i];
            ret[i++] = input[i];
            ret[i++] = input[i];
            ret[i++] = input[i];
            ret[i++] = input[i];
        }
        while(i < uniqueIndex) ret[i++] = input[i];
        return ret;
    }
}