Hash Without Collisions X10103


Statement
 

pdf   zip

html

We could consider the predefined function hash() from Python but, in order to ensure replicability, we define instead the following very simple hash function on strings. Given a positive integer MOD that we call, of course, the modulus,

h = lambda s, MOD: sum(ord(c) for c in s) % MOD

How many strings, among a given set of them, can we pick up without incurring in collisions under h? Which strings form the maximal set(s) with this property?

You must write a program that receives the value of MOD and a sequence of strings and finds sets of strings from the sequence within which the strings do not have any collision. These sets must be as large as possible. For instance, for MOD = 7, the words "No" and "seguinte" both hash to zero, so at most one of them can be chosen; likewise "dia" and "morreu" both hash to 1 whereas "ninguem" hashes to 6.

Input

First comes the positive integer MOD, then a sequence of words separated by spaces or newlines and distributed among lines in an unpredictable manner. There may be word repetitions in the input: these are to be ignored as we work with sets of words as we said.

Output

All the sets of the maximum possible size, made of words taken from the sequence, where the hash function h does not generate collisions at all inside each set.

Observation

The sets can be printed in any order and the elements inside them can be printed in any order too. Separate the set elements by a space and print each set in a line as in the examples.

Public test cases
  • Input

    7
    No dia seguinte ninguem morreu
    

    Output

    dia ninguem seguinte
    dia ninguem No
    ninguem seguinte morreu
    ninguem No morreu
    
  • Input

    10
    It was a QUEER sultry summer 
    the summer they electrocuted the Rosenbergs 

    Output

    electrocuted It QUEER summer a they sultry Rosenbergs
    electrocuted It QUEER summer a they Rosenbergs the
    electrocuted It QUEER summer a they Rosenbergs was
    
  • Input

    20
    shall I compare thee to a summers day
    thou art more lovely and more temperate

    Output

    I thou and compare summers shall thee day more a
    I thou compare to summers shall thee day more a
    I thou compare art summers shall thee day more a
    I thou compare summers temperate shall thee day more a
    I thou compare summers shall thee day more lovely a
    
  • Information
    Author
    José Luis Balcázar
    Language
    English
    Official solutions
    Python
    User solutions
    Python