Submission 1c4acd2b...

ChallengeRemove duplicate elements
Submitter0xff3c2241cd767b7...
Submitted at2018-52-24
Gas used1426409
/**
 * 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 {

    struct Slot {
      uint256 value;
      bool occupied;
    }
    /**
     * @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) {
      // Oh, we can't have mappings in memory? Then we're going to make our own rubbish one! :D
      Slot[] memory processed = new Slot[](input.length+1);
      uint slot;
      uint nuniques;
      for (uint i =0; i<input.length; i+=1){
        slot = input[i] % input.length;
        while (processed[slot].occupied == true && processed[slot].value != input[i]){
          slot +=1;
          if (slot > input.length){
            slot=0;
          }
        }
        if (processed[slot].occupied==false){
          // Then we've not seen it before
          processed[slot] = Slot(input[i], true);
          input[nuniques] = input[i];
          nuniques += 1;
        }
      }
      // create output array
      ret = new uint[](nuniques);
      for (i = 0; i<ret.length; i+=1){
        ret[i] = input[i];
      }
      return ret;
    }

}