2014-04-09

猜數字小遊戲 using C++

這個有點類似軒轅劍三外傳天之痕中,
在雷夏澤跟小妹妹玩的猜數字遊戲。

1. 使用者輸入兩次4個數字,一次為Guess,另一次為Solution。
2. 我們要判斷Guess的「hit」以及「pseudo hit」的數量。
3. 當Guess[i]等於Solution[i]時,定義為hit。(i=0~3)
4. 當Guess[i]等於Solution[0..3]時,但不等於Solution[i]時定義為pseudo hit。
5. 不重複計算數量,也就是 hit + pseudo hit ≦ 4。

換句話說,
當Guess中,某個位置的數字恰好等於Solution該位置的數字,則稱為hit;
或是該數字雖然有在Solution中,但不在正確的位置上,則稱為pseudo hit。

舉幾個例子:
(1) Guess="2134"; Solution="1534";
=> hits=2, pseudo_hits=1
(2) Guess="1212"; Solution="2121";
=> hits=0, pseudo_hits=4
(3) Guess="1112"; Solution="2111";
=> hits=2, pseudo_hits=2

用C++來實作: MasterMindGame.cpp

因為這是管院OOP上機考的題目,
spec有格式限制,所以沒辦法寫得太漂亮,
知道方法怎麼做就好了。

值得注意的地方是,
在main()裡,guess[]和solution[]的字元陣列大小為5,
若只有4的話,在getline()時會產生一些問題。
(沒有地方存'\0',而且無法讀到'\n')
或是直接用String去宣告兩個字串是最好的寫法。



天之痕裡的solution是亂數產生,而不是由使用者輸入。(廢話XD)
他用「陰」、「陽」來分別表示「pseudo hit」與「hit」。
遊戲規則有一點點不一樣,
我們要猜4個數字,
如果數字猜對、而且位置也猜對的話,得一陽;
若數字猜對,但位置錯誤的話,得一陰。
我們猜的數字得到四陽就贏了。(可以得到不老之泉水 XD)



最後附上原本上機考的題目,
又臭又長,光要讀懂題目就花了不少時間 = =

The Game of Master Mind is played as follows:

1.
The computer has four slots containing balls
that are red (R), yellow (Y), green (G) or blue (B).
For example, the computer might have RGGB
(e.g., Slot 1 is red, Slots 2 and 3 are green, Slot 4 is blue).

2.
The user is trying to guess the solution.
He/she might, for example, guess YRGB.

3.
When the user guesses right color for the right slot,
he/she gets a “hit”.
If he/she guesses a color that exists but is in the wrong slot,
he/she gets a “psuedo-hit”.
For example, the guess YRGB has 2 hits and one pseudo-hit.

4.
For each guess, the user is told the number of hits and pseudo-hits.
We can use a struct to represent the numbers of hits and pseudo-hits as follows.

struct Result { 
    int hits;
    int pseudoHits; 
};  

Implement a method whose prototype looks like the following
using such struct Result that, given a guess and a solution,
returns

(a) the number of hits (15%), and
(b) the number of pseudo hits (20%).

By guess[i]/solution[i], you can access the (i + 1)th slot of guess/solution.
Notice that if a slot has already been counted as a hit,
it cannot be counted as a puedo-hit;
no random number is needed.
(This method estimate will be called to test its correctness when graded.)

Result estimate(char guess[], char solution[]); 

沒有留言:

張貼留言