Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Guess Number
/*32 Guess Number The system has a secret four digits number, in which each digit is in range of one to 6 [1, 6]. Given a four digital number, the system also provide a API that returns the number of correct matched digits. Design a method to guess this secret number. */ // 1) You first can determine what all the digits being used by calling all sequences like '1111', '2222', ..., => save all digits as a set<int> s; // 2) Then try to determin each position's potential digits, the return number can be = < >, other than the =, it provide YES, NO answer right away. // 3) using a map to save all the calling history. // 4) if you want to return the total number guessed, save another private member variable. /* string target = "1234", guess = "1111" => 1 guess = "2222" => 1 guess = "1234" => 1 guess = "0000" => 0 N = 4, M = 6 (1~6), n = N**M = 36*36 ~ 1K 1) find which digits are used ? map<char, int> m; // 6 + 4 + 4 + 4 + 4 = > 22 guess 6(1-6) 2) determin eacho position's letter */ #include <iostream> #include <string> #include <vector> #include <map> #include <set> using namespace std; class Game{ string target; int ct; int N; public: Game(string tg): target(tg), N((int)tg.size()), ct(0){} int guessOne(string guess){ ct++; int res =0; if(guess.size()!=4) return 0; for(int i =0; i<guess.size(); i++){ if(guess[i]==target[i]) res++; } return res; } string play(){ // try "1111",..."6666"; int res = 0; ct = 0; map<string, int> m; // function calling result set<char> s; vector<string> bases = {"1111", "2222", "3333", "4444", "5555","6666"}; for(auto guess: bases){ res = guessOne(guess); m[guess] = res; if(res==4) return guess; if(res>0) s.insert(guess[0]); } // try to determine each position string guess = "1111"; for(int i=0; i<N; i++) { int pre = m[guess]; for(auto x: s){ string old = guess; guess[i] = x; // new try if(m.count(guess)) res = m[guess]; else{ res = guessOne(guess); m[guess] = res; } if(res > pre){ // new break; } else if(res < pre) { guess = old; break; } else{ // contine with the next dig } } } return guess; } int totalGuess(){ return ct; } }; int main() { string target = "1456"; Game g(target); string guess = g.play(); cout << "Number = " << guess << endl; cout << "Total try = " << g.totalGuess() << endl; return 0; }
run
|
edit
|
history
|
help
0
Problema1
Zscore
sample1
QuickSort
integer division
proga2
single_digit
Bad code
DP on Trees: Type B (In/out Dp)
RegexMatch