Algorithm to guess the number

Little A and Little B are playing guessing numbers. Little B randomly chooses one from 1, 2, 3 each time, and Little A also chooses one guess from 1, 2, 3 each time. They played this game three times in total. Please go back to Little A. How many times did you guess it right?

The input guess array is the guess made by Little A each time, and the answer array is the choice made by Little B each time. The length of guess and answer are both equal to 3.

Example 1:

Input: guess = [1,2,3], answer = [1,2,3]

Output: 3

Explanation: Little A guessed right every time.

Example 2:

Input: guess = [2,2,3], answer = [3,2,1]

Output: 1

Explanation: Little A only guessed correctly the second time.

Algorithm 1: Traverse the arrays of small A and small B in turn, and compare whether the data is the same

int GuessNumber1(int arr[], int brr[])
{
    
    
	int count = 0;
	for (int i = 0;i < 3;i++)
	{
    
    
	if (arr[i] == brr[i])
			count++;
	}
}

Algorithm 2: Compared with the optimization of Algorithm 1, use vector array

int GuessNumber2(vector<int>& guess,vector<int>& answer)
{
    
    
	if (guess.size() != answer.size()) return 0;
	int cnt = 0;
	for (auto i: {
    
    0,1,2})		// i 取0,1,2
	{
    
    
		if (guess[i] == answer[i]) cnt++;
	}
	return cnt;
}

Test case:

int main()
{
    
    
	vector<int> guess1 = {
    
     1, 2, 3 };
	vector<int> answer1 = {
    
     1, 2, 3 };
	auto ret1 = GuessNumber2(guess1, answer1);

	vector<int> guess2 = {
    
     2,2,3 };
	vector<int> answer2 = {
    
     3,2,1 };
	auto ret2 = GuessNumber2(guess2, answer2);


	cout << ret1 << "  " << ret2 << endl;

	return 0;
}

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/109126486