Friday, April 13, 2012

Problem 29: Name That Number

Friday the 13th...

Another first-attempt! w00t again! This one is done differently then their analysis.
C++ allows you to use std::string, so you can check length. The length of the serial must be equal to the name.

Then I "serialize" or "hash" every name that has the same length, and check if it matches the number.

This is better than doing a binary search of each possible number upon the dictionary.
/*
ID: victor4
PROG: namenum
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string serializeName(const string &in){
 string ret = "";
 for(int i = 0; i < in.length(); ++i){
  if(in[i] == 'Q' || in[i] == 'Z')
   return "1";
  if(in[i] < 'Q')
   ret += ((in[i] - 'A') / 3) + '2';
  else
   ret += ((in[i] - 'Q') / 3) + '7';
 }
 return ret;
}

int main() {
 ofstream fout ("namenum.out");
 ifstream fin ("namenum.in"), fdict ("dict.txt");
 
 string serial;
 fin >> serial;
 
 bool found = false;
 string entry;
 while(fdict >> entry)
  if(entry.length() == serial.length() && serializeName(entry) == serial){
   found = true;
   fout << entry << endl;
  }
 
 if(!found)
  fout << "NONE" << endl;
 
 // fout
 return 0;
}

2 comments:

  1. Could you pls explain "serializeName()" function?

    ReplyDelete
    Replies
    1. The serializeName() converts a name (like AAAA) to a number string (like 2222)

      Delete