Submission 2acfe537...

ChallengeRemove duplicate elements
Submitterricmoo.firefly.eth
Submitted at2018-06-28
Gas used357352
pragma solidity 0.4.24;

contract Unique {
    function uniquify(uint[] input) public pure returns(uint[] ret) {
        uint256 length = input.length;
        if (length <= 1) { return input; }

        uint[256] memory filter;

        uint256 outputIndex = 0;
        for (uint256 i = 0; i < length; i++) {
            uint v = input[i];

            if (v <= 0xff) {
                if (filter[v] & 0x01 == 0x01) { continue; }
                filter[v] |= 0x01;
                input[outputIndex++] = v;

            } else {
                uint index = uint(v & 0xff);
                uint check = uint(v & 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe);
                if (uint(filter[index]) & check != check) {
                    // Unique!
                    filter[index] |= check;
                    input[outputIndex++] = v;
                } else {
                    for (uint j = 0; j < outputIndex; j++) {
                        if (input[j] == v) {
                            // Unique!
                            filter[index] |= check;
                            input[outputIndex++] = v;
                            break;
                        }
                    }
                }
            }

        }

        if (outputIndex == input.length) { return input; }

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