Optimization game Bulls and Cows

Asked

Viewed 833 times

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

1 answer

2


What you can do is improve code organization, don’t lump it all together and don’t write every hour in a way.

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

Can transform num from 1 to 4 in a array and who knows how to make a for internal to compare and simplify the if. There tourosVec would no longer be necessary (or could use it in place of these 4 variables). This is not exactly a simplification and many programmers would even find that it is worsening the code in something so short.

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

  • 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. (:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.