Your goal is to write a hash function, that accepts morse code character and returns a hash code that you get to define.
You can be sure, passed string will be:
- One of the Latin characters (A-Z) encoded into Morse Code using
.
and-
, or - One of the digits (0-9) encoded into Morse Code using
.
and-
, or - Empty
So, there could be any of 37 different strings passed to you.
Requirements:
- The returned number should be unique for all 37 strings
- For empty string the function should return 0
Score:
- Initially, you have a 100 points.
- You will lose
- 1 point for every bitwise operator in your code
- 2 points for every addition (subtraction) operator in your code (operators in loop clauses (e.g. inside
for(;;)
orwhile()
don't count) - 4 points for every multiplication (division, modulo, etc) operator
- 6 points for every if (else) statement
- 8 points for every loop statement (including loops in the called functions. You can presume that any called function has no more than one loop)
- 12 points for every conditional operator
- 200 points for using a built-in hash function
Bonuses:
- If all numbers, produced by your function are less than
N
, you will get additional137 - N
points (of course, if the bonus is positive)
Winners:
Score matters, but be creative!
Example:
Score: 100 - 5*2 - 3*4 - 8 + (137 - 134) = 73
I know, this could be improved by removing modulo operator and make a loop starts from 1, but this is just an example
#include <iostream>
#include <map>
#include <set>
std::size_t hash_morse(const std::string& s)
{
std::size_t ans = 0;
for(std::size_t i = 0; i < s.size(); ++i)
{
ans += (s.at(i) - '-' + 2) * (i + 1) * (i + 1);
}
return ans % 134;
}
int main()
{
std::map<std::string, char> m
{
{"", 0},
{".-", 'A'},
{"-...", 'B'},
{"-.-.", 'C'},
{"-..", 'D'},
{".", 'E'},
{"..-.", 'F'},
{"--.", 'G'},
{"....", 'H'},
{"..", 'I'},
{".---", 'J'},
{"-.-", 'K'},
{".-..", 'L'},
{"--", 'M'},
{"-.", 'N'},
{"---", 'O'},
{".--.", 'P'},
{"--.-", 'Q'},
{".-.", 'R'},
{"...", 'S'},
{"-", 'T'},
{"..-", 'U'},
{"...-", 'V'},
{".--", 'W'},
{"-..-", 'X'},
{"-.--", 'Y'},
{"--..", 'Z'},
{".----", '1'},
{"..---", '2'},
{"...--", '3'},
{"....-", '4'},
{".....", '5'},
{"-....", '6'},
{"--...", '7'},
{"---..", '8'},
{"----.", '9'},
{"-----", '0'}
};
std::map<std::size_t, std::string> hashes;
for(const auto& elem: m)
{
auto hash = hash_morse(elem.first);
if(hashes.find(hash) != hashes.end())
{
std::cout << "Collision" << std::endl;
std::cout << '"' << hashes[hash] << R"(" and ")" << elem.first << '"' << std::endl;
std::cout << "Hash: " << hash << std::endl;
std::cout << std::endl;
}
else
{
hashes[hash] = elem.first;
}
}
std::cout << "Total amount of collisions: " << (m.size() - hashes.size()) << std::endl;
return 0;
}