Optimization game Bulls and Cows

3

I made this code from a game called Bulls and Cows where it's a guessing game, but it's a bit 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 the right positions)

If you put 3 2 4 5, you have 3 cows and 0 bulls (cows are certain numbers in the wrong positions) so that 1 2 3 4 are 4 bulls.

Four bulls = game closed.

It is 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 do not want optimization to be necessarily have less code, just something simpler and that is not maintainable and do your duty, someone do you have any 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;
     }
    
asked by anonymous 09.03.2016 / 00:26

1 answer

2

What you can do is improve the organization of the code. Do not pile everything up. Do not write every hour one way.

Outside this can do little, as far as I understand.

You can transform num from 1 to 4 into an array and who knows how to% internal% to compare and simplify for . Thus,% w / w would no longer be necessary (or could use it instead of those 4 variables). This is not exactly a simplification and many programmers would even find it worsening the code in something so short.

This is more C and less C ++. Using a if instead of an array seems to me to be a goal of the year. Then you could use other algorithms like tourosVec or vector .

    
09.03.2016 / 00:42