Problem of the Day
A new programming or logic puzzle every Mon-Fri

Month Hash

A programmer has created a hash function to map a month to a number. See if you can figure out the pattern and fill in the rest of the months of the year.

  • January - 7110
  • February - 826
  • March - 5313
  • April - 541
  • May - 3513
  • June - 4610

Permalink: http://problemotd.com/problem/month-hash/

Comments:

  • March boy - 10 years, 4 months ago

    july - 4710 august - 681 september - 9919 october - 71015 november - 81114 december - 8124

    reply permalink

  • Anonymous - 10 years, 4 months ago

    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    const char * MONTHS[] = { "January","February","March","April","May","June","July","August","Septempber","October","November","December"};
    
    /* return the hash of the month */
    unsigned long hash(const char * name) 
    {
    int index;
    unsigned long ret =  strlen(name); /* length of the month */
    
    /* find the ordinal of the month */
    for(index=0; index<12; ++index)
      if(strcmp(MONTHS[index],name) == 0)
         break;
    if (index >= 12) return 0; /* unknown month */
    ret = ret * (index >= 9 ? 100:10) + index + 1;
    /* get the ordinal of the first letter of the month */
    index = tolower(MONTHS[index][0]) + 1 - 'a';
    ret = ret * (index > 9 ? 100:10) + index;
    return ret;
    }
    
    int main() {
    for  (int i=0;i<12;++i)
            cout << MONTHS[i] <<"-" <<hash(MONTHS[i])<<endl;
    return 0;   
    }
    

    reply permalink

  • Nick - 10 years, 4 months ago

    Solution in plain English is that the pattern is 3 concatenated numbers, the first number is the number of letters in the month's name, the second number is the month's number, and the third number is the place in the alphabet of the month's first letter.

    Nice one!

    reply permalink

  • Patrick - 10 years, 4 months ago

    This is it in Ruby.(Sorry about the indentation)

    @@alphabet = ("A".."Z").to_a
        def self.to_numbers(months_array)
          result = {}
          months_array.map.with_index do |m, i|
            number = "#{ m.to_s.length }" << "#{ i+1 }" << "#{ @@alphabet.index(m[0])+1 }"
            result[m.to_sym] = number.to_i
          end
          result
        end
    

    {:January=>7110, :February=>826, :March=>5313, :April=>541, :May=>3513, :June=>4610, :July=>4710, :August=>681, :October=>7915, :November=>81014, :December=>8114}

    reply permalink

Content curated by @MaxBurstein