samedi 25 juin 2016

C game to guess a four digit number

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
  srand(time(NULL));
  int win[4],guess[4];
  char num[5];
  win[0]=rand()%9+1;
  int i,j,k,cows,bulls;
  for(i=1;i<4;i++)
  {
    win[i]=rand()%10;
  }
  printf("Guess a four digit number: <");
  for(i=0;i<4;i++)
  {
    printf("%d",win[i]);
  }
  printf(">n");

  do
  {
    cows=0;
    bulls=0;
    scanf("%s",num);
    for(i=0;i<4;i++)
    {
      char temp[2]={num[i],'�'};
      guess[i]=atoi(temp);
    }
    for(i=0;i<4;i++)
    {
      for(j=0;j<4;j++)
      {
        if(guess[i]==win[j] && j==i)
        {
          cows++;
        }
        else if(guess[i]==win[j] && j!=i)
        {
            bulls++;
        }
      }
    }
    printf("%d cows, %d bullsn",cows, bulls);
  } while(cows!=4);

  if(cows==4)
  {
    printf("Congratulations you won!n");
  }
}

Well this is the code I need help with. It's not so good I know, but I've just learned the baisics and about to start exploring other things. It's a game as you may have guessed. The basics are: you get a cow when you find the right digit in the right place and a bull for every digit you guessed correctly but found in the wrong place. So this seems nice until the winning number is let's say 2434 and I start guessing, 2432 gives me 3 cows and 2 bulls. That's what I want to avoid. I want the program to display 3 cows and 0 bulls, since there are three matches and there's no two twos in the winning number just one. I hope you understand what I have been trying to say, and I think this problem could be a bit more complex than I first thought. But I'm open for every other solution as well.

Aucun commentaire:

Enregistrer un commentaire