c++ – Bulls and Cows Game Optimization

Question:

I made this code for 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:

The hidden numbers are 1 2 3 4.

If you put 1 2 6 7, you have Two Bulls (right numbers in 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 1 2 3 4 is 4 bulls.

Four bulls = game over.

It's one of the primary exercises in Bjarne's first book.

To the point: I need to optimize the code, I know there are easier ways to do this, I don't want to optimize it necessarily to have less code, just something simpler and that doesn't stop being maintainable and doing its duty, does anyone have any ideas ? (:

#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;
     }

Answer:

What you can do is improve the organization of the code, don't cram everything together and don't write every hour in one way.

Other than that, it can do little, as far as I understand.

You can turn num 1 to 4 in an array and maybe make for internal to compare and simplify if . Then tourosVec would tourosVec longer be needed (or I could use it instead of these 4 variables). This isn't exactly a simplification, and many programmers would even think they're making code worse on something so short.

This is more C and not much C++. Using a vector in place of an array seems to me to be a goal of the exercise. Then you could use other algorithms like random_shuffle or find .

Scroll to Top