3
I made this code from a game called Bulls and Cows (bulls and cows) where it’s a guessing game, but it’s a little different, I’ll give you an example:
Hidden numbers are 1 2 3 4.
If you put 1 2 6 7, you have Two Bulls (right numbers in the right positions)
If you put 3 2 4 5, you have 3 cows and 0 bulls (cows are right numbers in the wrong positions) so that 1 2 3 4 is 4 bulls.
Four bulls = match ended.
It’s one of the primary exercises of Bjarne’s first book.
To the point: I need to give an optimized code, I know there are easier ways to do this, I don’t want to optimize is necessarily to have less code, just something simpler and still be maintainable and do your duty, someone has some idea? (:
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <ctime>
using namespace std;
int main()
{
int touro = 0;
int vaca = 0;
int num1 = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
srand(time(0)); // Pega o tempo do PC para gerar a seed
int segredo[4] = {rand()%25,rand()%25,rand()%25,rand()%25};
cin >> num1 >> num2 >> num3 >> num4;
for(int x = 0; x<4; x++){
if(num1 == segredo[x]||num2 == segredo[x]||num3 == segredo[x]||num4 ==segredo[x]) // se for o numero (Não necessariamente a ordem) vaca++
vaca++;
}
int tourosVec[4] = {num1,num2,num3,num4};
for(int y = 0; y<4; y++){
if(tourosVec[y] == segredo[y]) // compara exatamente números e posições
touro++;
}
cout << "vacas: " << vaca << endl;
cout << "touros: " << touro<<endl;
if(touro == 4){
cout << "Ganhou!" << endl;
}
return 0;
}
It is because I do not know how I compare within a for ONE number with the rest of the vector, usually in the same way that it sums 1 to the comparator, also sums 1 to what will be compared.. I do not know these functions but I will research, thanks. (:
– Marv