google竞赛题SecretSum的另一种C++解法, 使用递归生成代替循环 -- 2

完整代码, VS2005 & g++通过

 

//FILE: SecretSum.cpp

//(c) DGU, 自由软件

//全文转载需要保留以上说明

//如有建议或讨论请email: gdyxgzy@hotmail.com

//

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>

using namespace std;

typedef std::map<char, char> Status;

std::set<char> leading_chars;

// find all the unique values in [start_value -- end value]
vector<char> find_available_choices(const Status& c_st, char start_value, char end_value)
{
 vector<char> result;

 for(char ch=start_value; ch<=end_value; ++ch)
 {
  bool not_found=true;
  for(Status::const_iterator itr=c_st.begin(); itr!=c_st.end(); ++itr) // using 'find' instead?
  {
   if(itr->second == ch)
   {
    not_found = false;
    break;
   }
  }
  if(not_found)
   result.push_back(ch);
 }

 return result;
}

 

vector<string> gen_num(Status curr_state, const string& pattern)
{
 vector<string> result;

 if(pattern.length()==1)
 {
  if(pattern[0]>='0' && pattern[0]<='9') //pattern is a number, just use it
   result.push_back(string(1, pattern[0]));
  else if(curr_state[pattern[0]] < '0')
  {
   if(leading_chars.find(pattern[0])!= leading_chars.end()) //a leading char, ranging from '1'-'9'
   {
    vector<char> availables = find_available_choices(curr_state, '1', '9');
    for(int i=0; i<availables.size(); ++i)
     result.push_back(string(1, availables[i]));
   }
   else //not a leading char, can be '0'-'9'(if it's unique)
   {
    vector<char> availables = find_available_choices(curr_state, '0', '9');
    for(int i=0; i<availables.size(); ++i)
     result.push_back(string(1,availables[i]));
   }
  }
  else
   result.push_back(string(1, curr_state[pattern[0]]));

  return result;
 }

 vector<char> available_choices;
 if(pattern[0]>='0' && pattern[0]<='9')
  available_choices.push_back(pattern[0]);
 else if(curr_state[pattern[0]] < '0') //it's empty, could be assigned to any legal value
 {
  if(leading_chars.find(pattern[0])!= leading_chars.end()) 
  {
   vector<char> availables = find_available_choices(curr_state, '1', '9');
   for(int i=0; i<availables.size(); ++i)
    available_choices.push_back(availables[i]);
  }
  else //not a leading char, can be '0'-'9'
  {
   vector<char> availables = find_available_choices(curr_state, '0', '9');
   for(int i=0; i<availables.size(); ++i)
    available_choices.push_back(availables[i]);
  }
 }
 else //the value is already set, the only choice
  available_choices.push_back(curr_state[pattern[0]]);

 //prepare to start the loop(and recursion), find the sub patterns!
 string sub_pattern = pattern.substr(1, pattern.length()-1);

 for(int idx=0; idx<available_choices.size(); ++idx)
 {
  string leading(1, available_choices[idx]);
  curr_state[pattern[0]] = available_choices[idx];

  vector<string> temp = gen_num(curr_state, sub_pattern);

  for(int i=0; i<temp.size(); ++i)
   result.push_back(leading+temp[i]);
 }

 return result;
}

string init(Status& state, const string& num1, const string& num2, const string& sum)
{
 for(int i=0; i<num1.length(); ++i)
  if(num1[i]>'9' || num1[i]<'0')
   state.insert(make_pair(num1[i], '0'-1));
 for(int i=0; i<num2.length(); ++i)
  if(num2[i]>'9' || num2[i]<'0')
   state.insert(make_pair(num2[i], '0'-1));
 for(int i=0; i<sum.length(); ++i)
  if(sum[i]>'9' || sum[i]<'0')
   state.insert(make_pair(sum[i], '0'-1));
 if(sum.length()-max(num1.length(), num2.length()) == 1)
  if(sum[0]>'9' || sum[0]<'0')
   state[sum[0]] = '1'; //if sum is longer, then the first digit MUST be '1'

 if(state.size()>10)
  return string("More than 10 pattern characters, absolutely no solution!");

 if(num1[0]>'9' || num1[0]<'0')
  leading_chars.insert(num1[0]);
 if(num2[0]>'9' || num2[0]<'0')
  leading_chars.insert(num2[0]);
 if(sum[0]>'9' || sum[0]<'0')
  leading_chars.insert(sum[0]);

 return string("OK");
}

// set state for current num1, use this state as a constraint to generate num2
void set_state(Status& state, const string& value, const string& pattern)
{
 for(int i=0; i<value.length(); ++i)
  if(pattern[i]>'9' || pattern[i]<'0')
   state[pattern[i]] = value[i];
}

string str_add(const string& num1_v, const string& num2_v)
{
 string sum_v;
 const string& s_longer = num1_v.length()>=num2_v.length() ? num1_v:num2_v;
 const string& s_shorter = num1_v.length()>=num2_v.length() ? num2_v:num1_v;
 int l_longer = max(num1_v.length(), num2_v.length());
 int l_shorter = min(num1_v.length(), num2_v.length());

 int carry=0;

 for(int i=0; i<l_longer; ++i)
 {
  int oprd1 = s_longer[l_longer-i-1]-'0';
  int oprd2 = i<l_shorter ? (s_shorter[l_shorter-i-1]-'0'):0;
  int result = oprd1+oprd2+carry;
  carry = result/10;
  sum_v += (char)(result%10+'0');
  
 }
 if(carry)
  sum_v += '1';

 reverse(sum_v.begin(), sum_v.end());
 return sum_v;
}

bool check_sum_pattern(Status state, const string& v_sum, const string& pattern)
{
 if(v_sum.length()!=pattern.length())
  return false;
 for(int i=0; i<pattern.length(); ++i)
 {
  if(pattern[i]>='0' && pattern[i]<='9') //pattern is a number, just use it
  {
   if(v_sum[i]!=pattern[i])
    return false;
  }
  else if(state[pattern[i]] < '0')
  {
   vector<char> availables;
   if(leading_chars.find(pattern[i]) != leading_chars.end())
    availables = find_available_choices(state, '1', '9');
   else //not a leading char, can be '0'-'9'(if it's unique)
    availables = find_available_choices(state, '0', '9');

   if(find(availables.begin(), availables.end(), v_sum[i]) != availables.end())
   {
    state[pattern[i]] = v_sum[i]; // shall I pass this change to the caller???
    continue;    // NO! it's only used to validate the
   }      // left digits in this v_sum
   else
    return false;
  }
  else if(state[pattern[i]] != v_sum[i])
   return false;
 }
 return true;
}

vector<vector<string> > get_all_results(const string& num1, const string& num2, const string& sum)
{
 vector<vector<string> > output;
 Status clean_state;

 string s =init(clean_state, num1, num2, sum);
 if(s.compare("OK")!=0)
 {
  cout<<s<<endl;
  return output;
 }

 vector<string> num1_vals = gen_num(clean_state, num1);
 if(num1_vals.size()==0)
  return output;

 for(int i=0; i<num1_vals.size(); ++i)
 {
  Status curr_state=clean_state;
  string v_num1 = num1_vals[i];

  set_state(curr_state, v_num1, num1);

  vector<string> num2_vals = gen_num(curr_state, num2);
  if(num2_vals.size()==0)
   continue;

  string v_sum;
  for(int j=0; j<num2_vals.size(); ++j)
  {
   string v_num2 = num2_vals[j];
   set_state(curr_state, v_num2, num2);

   v_sum = str_add(v_num1, v_num2);

   if(check_sum_pattern(curr_state, v_sum, sum)==true)
   {
    vector<string> temp;
    temp.push_back(v_num1);
    temp.push_back(v_num2);
    temp.push_back(v_sum);

    output.push_back(temp);
   }
   else
    continue;
  }
 }
 return output;
}

//to check if the input patterns are valid, or if the patterns are destined to have no solution
string check_validity(string& num1, string& num2, string& sum)
{
 if(num1[0]=='0' || num2[0]=='0' ||sum[0]=='0')
  return string("'0' not allowed as leading character!");

 for(int i=0; i<num1.length(); ++i)
 {
  if(num1[i]>='a' && num1[i]<='z')
   num1[i] -= ('a'-'A');
  else if(num1[i]>='0' && num1[i]<='9')
   continue;
  else if(num1[i]<'A' || num1[i]>'Z')
   return string("Only 'a'-'z', 'A'-'Z', and '0'-'9' are allowed in pattern, bad num1.");
 }
 for(int i=0; i<num2.length(); ++i)
 {
  if(num2[i]>='a' && num2[i]<='z')
   num2[i] -= ('a'-'A');
  else if(num2[i]>='0' && num2[i]<='9')
   continue;
  else if(num2[i]<'A' || num2[i]>'Z')
   return string("Invalid character in pattern string in num2.");
 }
 for(int i=0; i<sum.length(); ++i)
 {
  if(sum[i]>='a' && sum[i]<='z')
   sum[i] -= ('a'-'A');
  else if(sum[i]>='0' && sum[i]<='9')
   continue;
  else if(sum[i]<'A' || sum[i]>'Z')
   return string("Invalid character in pattern string in sum.");
 }

 if( sum.length() < max(num1.length(), num2.length()) )
  return string("sum's length less than the 2 oprand's length, no solution.");
 if( sum.length()-max(num1.length(), num2.length()) >= 2 )
  return string("sum's length too long, no solution.");
 if( sum.length()-max(num1.length(), num2.length()) ==1 )
  if(sum[0]>='0' && sum[0]<='9' && sum[0]!='1')
   return string("under current setting, sum's leading character must be '1', so there's no solution.");

 return string("OK");
}

int main()
{
 vector<vector<string> > output;
 string num1, num2, sum;

 while(1)
 {
  output.clear();
  num1.clear();
  num2.clear();
  sum.clear();
  leading_chars.clear();

  cout<<"Please input the pattern of num1, num2, and sum:"<<endl;
  cin>>num1;
  cin>>num2;
  cin>>sum;
  cout<<endl;

  string s = check_validity(num1, num2, sum);

  if(s.compare("OK")!=0)
  {
   cout<<s<<endl;
   continue;
  }

  if(num1.length()>num2.length())
  {
   string temp = num1;
   num1 = num2;
   num2 = temp;
  }

  output = get_all_results(num1, num2, sum);

  for(int i=0; i<output.size(); ++i)
  {
   vector<string> temp = output[i];

   cout<<temp[0];
   for(int j=1; j<temp.size()-1; ++j)
    cout<<'+'<<temp[j];
   cout<<'='<<temp[temp.size()-1]<<endl;
  }
  cout<<"Pattern: "<<num1<<'+'<<num2<<'='<<sum<<endl;
  cout<<"---------- Altogether "<<output.size()<<" results ------------"<<endl;

  string answer;
  answer.clear();
  cout<<"continue?";
  cin>>answer;
  cout<<endl;

  if(answer[0]=='y' || answer[0]=='Y')
   continue;
  else
   break;
 }

 cout<<"Thanks for using, bye!"<<endl;
 return 0;
}

 

 

//
//Some testing strings
//
//string num1("AAA");
//string num2("BBB");
//string sum("CCC");

//string num1("AAB");
//string num2("BCA");
//string sum("CDC");

//string num1("ABC");
//string num2("CBA");
//string sum("DDD");

//string num1("ABB");
//string num2("DEE");
//string sum("TTT");

//string num1("ABC");
//string num2("ABA");
//string sum("ACC");

//string num1("AAA");
//string num2("CDD");
//string sum("BAA");

//string num1("TEF");
//string num2("FET");
//string sum("AAA");

//string num1("ABC");
//string num2("ABC");
//string sum("BCE");

//string num1("AAAAA");
//string num2("BBBBB");
//string sum("CCCCC");

//string num1("ABCD");
//string num2("DCBA");
//string sum("EEEE");

//string num1("AABB");
//string num2("CCDD");
//string sum("EEFF");

//string num1("A");
//string num2("B");
//string sum("C");

//string num1("A");
//string num2("B");
//string sum("A");

//string num1("A");
//string num2("B");
//string sum("B");

//string num1("AAAAAAAABBBBBBBBCCCCCCCC");
//string num2("BBBBBBBBCCCCCCCCDDDDDDDD");
//string sum("CCCCCCCCDDDDDDDDEEEEEEEE");

//string num1("ABCBA");
//string num2("AB");
//string sum("ABCCC");

//string num1("A");
//string num2("BB");
//string sum("CDC"); //there's only one solution for this:2+99=101

//string num1("A");
//string num2("BB");
//string sum("CDE");

//string num1("A");
//string num2("BC");
//string sum("DEF");

// a  bc  def

// a  bc  1e2

//string num1("ABCD");
//string num2("CDEF");
//string sum("EFGH");

// abcde cdefg efghi

// abcde cdefg efghi

// abcde bcdef cdefg -- only one result, 16853+68539=85392

 

Demo output:

 

a bb cde -- 3+99=102, 4+99=103, 5+99=104, 6+99=105, 7+99=106, 8+99=107

a bb cd5 -- 6+99=105

a bb 2cd -- no result

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值