tags:

views:

307

answers:

1

I am writing aa mastermind guessing game, but in the “White Check”, I need to remember (know) the positions of all the position “Blacks”. These positions are not required checking again. Then for “each” non-black player “guess” array compare it against “each” non-black computer “answer” array. To find a match. If find any number in the “answer” array matched with the “guess” array, i.e. correct number but wrong position, mark it as a “White”.Also have to mark the position “Used”, and not be check again by other sun-sequence non-black player “guess” array numbers, to avoid “double” counting of the same number.

How can I modify my program to do it?

#include "stdafx.h"
#include "stdlib.h" 
#include "time.h"


int _tmain(int argc, _TCHAR* argv[])
{


 int answer[4];
 int guess[4];
    int count = 0;

 srand(time(NULL)); 
 answer[0] = (rand() % 6)+1;
 answer[1] = (rand() % 6)+1;
 answer[2] = (rand() % 6)+1;
 answer[3] = (rand() % 6)+1;

 printf("%d %d %d %d\n", answer[0],  answer[1],  answer[2],  answer[3]);

 do
 {
 int black = 0;
 int white = 0;
 printf("Enter 4 numbers: ");
 scanf("%d %d %d %d", &guess[0], &guess[1], &guess[2], &guess[3]);
 printf("\n%d %d %d %d\n", guess[0], guess[1], guess[2], guess[3]);

    count++;

 if (answer[0]==guess[0])
  black++;
 if (answer[1]==guess[1])
  black++;
 if (answer[2]==guess[2])
  black++;
 if (answer[3]==guess[3])
  black++;

 if (answer[1]==guess[0] || answer[2]==guess[0] || answer[3]==guess[0])
  white++;
 if (answer[0]==guess[1] || answer[2]==guess[1] || answer[3]==guess[1])
  white++;
 if (answer[0]==guess[2] || answer[0]==guess[2] || answer[3]==guess[2])
  white++;
 if (answer[0]==guess[3] || answer[1]==guess[3] || answer[2]==guess[3])
  white++;


 printf("b:%d w:%d\n",black, white); 
 }
 while (answer[0]!=guess[0] || answer[1]!=guess[1] || answer[2]!=guess[2] || answer[3]!=guess[3]);


 printf("count: %d\n", count);


 return 0;
}
A: 

Some tips:

  1. Instead of comparing every position against every other, consider sorting both arrays first.
  2. After sorting the arrays, loop through both in parallel to find matching values. Increment a counter for each. This will be the trickiest part of the program. It might help to study a merge sort implementation.
  3. The result from step 2 will be the sum of the white and black scores. So subtract the black score from that to get the white score.
  4. The final 'while' clause at the end could be simplified. Try while (black < 4);
finnw
Sort from the largest to the smallest or the smallest to the largest?
Programme Newbie
@Programme Newbie: It doesn't matter, either way is fine because you're just looking for matching values.
jk