Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8771569
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T17:49:18+00:00 2026-06-13T17:49:18+00:00

I am writing a program that simulates the game Mastermind, but I am struggling

  • 0

I am writing a program that simulates the game Mastermind, but I am struggling with how to compare guessed pattern to key pattern.
The game conditions are a little bit changed:

  • patterns consist of letters.
  • if an element of guessed pattern is equal to element of key pattern, and also index is equal, then print b.
  • if an element of guessed pattern is equal to element of key pattern, but index is not, then print w.
  • if an element of guessed pattern is not equal to element of key pattern, print dot.
  • in feedback about guessed pattern, ‘b’s come first, ‘w’s second, ‘.’s last.

Original key vs guess pattern match code

    for (i=0; i<patternlength; i++)
    {
        for (x=0; x<patternlength; x++)
        {
           if (guess[i]==key[x] && i==x)
                printf("b");
            if (guess[i]==key[x] && i!=x)
                printf("w");
            if (guess[i]!=key[x])
                printf(".");
        }   
    }

Revised code

This is using some of the answer provided by Jonathan Leffler. Unfotunately, it isn’t working correctly yet; can you help me?

The functions length() and guessnum() are defined already.

#include<stdio.h>
#include<string.h>
int length()
{
  int length;
  printf("Enter the pattern length: ");
  scanf("%d", &length);
  return length;
}
int guessnum()
{
  int guessnum;
  printf("Enter the number of guesses: ");
  scanf("%d", &guessnum);
  return guessnum;
}
int main(void)
{
  int patternlength = length();
  char key[patternlength+1];      
  char keyc[patternlength+1];    
  int numguess = guessnum();
  char guess[patternlength+1];    
  printf("Input the key pattern with no spaces: ");
  scanf("%s", key);
  int i,j,count = 1;
  int bcount = 0, wcount = 0;
  char guessc[patternlength+1];
  guessc[0] = '\0';            
  int ind;
  char output[patternlength];
  for (ind=0; ind<(patternlength+1); ind++)
    output[ind]='\0';
  char outputc[patternlength+1];
  char guessold[patternlength+1];
  for (ind=0; ind<(patternlength+1); ind++)
  guessold[ind]='\0';
  while (strcmp(key, guess) !=0 && count<=numguess)
    {
      if(count>1)
    strcpy(guessold, guess);
      strcpy(keyc, key);          
      printf("Input a guess pattern with no spaces: ");
      scanf("%s", guess);
      if (count>1)
    printf("%d: %s %s\n", count-1, output, guessold);
      strcpy(guessc, guess);
      wcount = 0;    
      bcount = 0;     
      printf("%d: ", count);
      for (i = 0; i < patternlength; i++)
    {
      if (keyc[i] == guessc[i])
        {
          putchar('b');
          keyc[i] = guessc[i] = '.';
          bcount++;
          for (ind=0; ind<patternlength; ind++)
        output[ind]='b';
        }
    }
      if (bcount != patternlength)
    {
      for (i = 0; i < patternlength; i++)
        {
          if (guessc[i] != '.')
        {

          for (j = 0; j < patternlength; j++)
            {

              if (guessc[i] == keyc[j])
            {
              wcount++;
              putchar('w');
              for (ind=0; ind<patternlength; ind++)
                if (output[ind]!='b')
                  output[ind]='w';

              keyc[j] = guessc[i] = '.';
              break;
            }
            }
        }
        }
      for (i = bcount  +  wcount; i < patternlength; i++)
        putchar('.');
      for (ind=bcount+wcount; ind<patternlength; ind++)
        output[ind]='.';
    }
      count++;
      printf(" %s\n", guess);
      strcpy(outputc, output);
    }
  if (strcmp(key, guess) != 0)
    {
      printf("You did not guess the pattern!\n");
    }
  else 
    {
      printf("You guessed the pattern!\n");
    }
  return 0;
}

output of code above:

Enter the pattern length: 3
Enter the number of guesses: 3
Input the key pattern with no spaces: abc
Input a guess pattern with no spaces: acb
1: bww acb
Input a guess pattern with no spaces: abb
1: bbb acb
2: bb. abb
Input a guess pattern with no spaces: abc
2: bb. abb
3: bbb abc
You guessed the pattern!

required output:

    Enter the pattern length: 3
    Enter the number of guesses: 3
    Input the key pattern with no spaces: abc
    Input a guess pattern with no spaces: acb
    1: bww acb
    Input a guess pattern with no spaces: abb
    1: bww acb
    2: bb. abb
    Input a guess pattern with no spaces: abc
    1: bww acb
    2: bb. abb
    3: bbb abc
    You guessed the pattern!

I tried to use one more string, which will store in it feedback of the guess, but when there are several guesses, i think i should use some kind of loop to print feedback of all previous guesses each time new guess is made. but it is difficult to me figure out how should i write this loop with the structure suggested by Jonathan Leffler.

I added my last correction to the code, so I almost reached the desired output. does anyone have an idea what is possible to do here?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T17:49:19+00:00Added an answer on June 13, 2026 at 5:49 pm

    I assume that there is a structure (for easy copying of the array contained within it), and that the input validation ensures that the key and the guess are the same length, and that the key and the guess only contain alphabetic characters.

    typedef struct pattern
    {
        char pattern[8];
    } pattern;
    
    size_t print_scoring(pattern key, pattern guess)
    {
        size_t n = strlen(key.pattern);
        assert(n == strlen(guess.pattern));
        size_t bcount = 0;
        for (size_t i = 0; i < n; i++)
        {
            if (key.pattern[i] == guess.pattern[i])
            {
                putchar('b');
                key.pattern[i] = guess.pattern[i] = '.';
                bcount++;
            }
        }
        if (bcount != n)
        {
            size_t wcount = 0;
            for (size_t i = 0; i < n; i++)
            {
                if (guess.pattern[i] != '.')
                {
                    for (size_t j = 0; j < n; j++)
                    {
                        if (guess.pattern[i] == key.pattern[j])
                        {
                            wcount++;
                            putchar('w');
                            guess.pattern[i] = key.pattern[j] = '.';
                            break;
                        }
                    }
                }
            }
            for (size_t i = bcount + wcount; i < n; i++)
                putchar('.');
        }
        return bcount;
    }
    

    The function works on copies of the key and the pattern (the structures are passed by value, not by pointer). It returns the number of correct guesses in the correct position; it assumes the calling code knows how long the pattern is, so the calling code can tell when the pattern is correct. It marks guess and key characters as ‘used’ by replacing them with a ‘.’. This is important to prevent a key of "aba" and a guess of "aaa" being incorrectly marked as bbw rather than correctly as bb.. This would be more important in keys/guesses of length 4 or more.

    Test Harness

    #include <assert.h>
    #include <string.h>
    #include <stdio.h>
    
    int main(void)
    {
        enum { NUM_KEYS = 3, NUM_GUESSES = 5 };
        pattern k[] = { { "abc" }, { "aba" }, { "aaa" } };
        pattern g[] = { { "aaa" }, { "aab" }, { "abc" }, { "cba" }, { "bab" } };
        for (int i = 0; i < NUM_KEYS; i++)
        {
            for (int j = 0; j < NUM_GUESSES; j++)
            {
                printf("Key: %s; Guess %s; Score: ", k[i].pattern, g[j].pattern);
                size_t n = print_scoring(k[i], g[j]);
                if (n == 3)
                    printf(" -- Correct!");
                putchar('\n');
            }
        }
        return(0);
    }
    

    Test Output

    Key: abc; Guess aaa; Score: b..
    Key: abc; Guess aab; Score: bw.
    Key: abc; Guess abc; Score: bbb -- Correct!
    Key: abc; Guess cba; Score: bww
    Key: abc; Guess bab; Score: ww.
    Key: aba; Guess aaa; Score: bb.
    Key: aba; Guess aab; Score: bww
    Key: aba; Guess abc; Score: bb.
    Key: aba; Guess cba; Score: bb.
    Key: aba; Guess bab; Score: ww.
    Key: aaa; Guess aaa; Score: bbb -- Correct!
    Key: aaa; Guess aab; Score: bb.
    Key: aaa; Guess abc; Score: b..
    Key: aaa; Guess cba; Score: b..
    Key: aaa; Guess bab; Score: b..
    

    From the comments

    Why is my code not working? Can you have a look at it please?
    The problem is that I cannot go the next step after entering a guess pattern. Maybe I don’t see some mistakes in my code.

    Instant response:

    One of the key points in my answer is that the comparison code is working on copies of the data entered. It is a destructive comparison algorithm, writing dots over the data. Your attempt to merge my code into your program did not retain the separate function working on separate copies of the data which were a crucial part of this answer. The use of a structure was there to make it easy to pass copies of the data around (it’s the one time C copies arrays for you automatically). The comparison code should be in a function of its own, not inline in main().

    However, we can get the code given to work. There were some transcription errors (marked BUG below), and some other problems (also identified below).

    Working version of revised code in question

    This is a working version of your program annotated with the crucial changes. Non-crucial changes include spacing around operators and using an indent level of 4 spaces.

    #include <string.h>
    #include <stdio.h>
    
    static int length(void) { return 3; }    // Dummy function
    static int guessnum(void) { return 5; }  // Dummy function
    
    int main(void)
    {
        int patternlength = length();
        char key[patternlength+1];      // Buffer overflow
        char keyc[patternlength+1];     // Copy of key
        int numguess = guessnum();
        char guess[patternlength+1];    // Buffer overflow
        printf("Input the key pattern with no spaces: ");
        scanf("%s", key);
        int i,j,count = 1;
        int bcount = 0, wcount = 0;
        char guessc[patternlength+1];   // Buffer overflow
        guessc[0] = '\0';               // Initialize!
        while (strcmp(key, guess) != 0 && count <= numguess)
        {
            strcpy(keyc, key);          // Copy key too
            printf("Input a guess pattern with no spaces: ");
            scanf("%s", guess);
            strcpy(guessc, guess);
    
            wcount = 0;     // Reinitialize
            bcount = 0;     // Reinitialize
            printf("%d: ", count);
            for (i = 0; i < patternlength; i++)
            {
                if (keyc[i] == guessc[i])
                {
                    putchar('b');
                    keyc[i] = guessc[i] = '.';
                    bcount++;
                }
            }
            if (bcount != patternlength)    // Extraneous semi-colon excised! ;
            {
                for (i = 0; i < patternlength; i++)
                {
                    if (guessc[i] != '.')
                    {
                        //for (j = 0; i < patternlength; j++) BUG
                        for (j = 0; j < patternlength; j++)
                        {
                            //if (guessc[i] == keyc[i]) BUG
                            if (guessc[i] == keyc[j])
                            {
                                wcount++;
                                putchar('w');
                                //guessc[i] = keyc[i];  BUG
                                keyc[j] = guessc[i] = '.';
                                break;
                            }
                        }
                    }
                }
                for (i = bcount  +  wcount; i < patternlength; i++)
                    putchar('.');
            }
            count++;
            printf(" %s\n", guess);
        }
        if (strcmp(key, guess) != 0)
        {
            printf("You did not guess the pattern!\n");
        }
        else 
        {
            printf("You guessed the pattern!\n");
        }
        return 0;
    }
    

    The compiler told me about the stray semi-colon:

    ss2.c: In function ‘main’:
    ss2.c:36:37: warning: suggest braces around empty body in an ‘if’ statement [-Wempty-body]
    

    If your compiler didn’t tell you about that, you aren’t using enough warnings (or you need a better compiler). I routinely use:

    gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
        -Wold-style-definition ss2.c -o ss2
    

    The working code passes that without a whimper.

    Sample output

    Input the key pattern with no spaces: abc
    Input a guess pattern with no spaces: aaa
    1: b.. aaa
    Input a guess pattern with no spaces: bbb
    2: b.. bbb
    Input a guess pattern with no spaces: ccc
    3: b.. ccc
    Input a guess pattern with no spaces: cab
    4: www cab
    Input a guess pattern with no spaces: abc
    5: bbb abc
    You guessed the pattern!
    

    Final debug-laden code

    This is mainly to show the level of printing that I used to see what was going wrong. Using stderr for the diagnostic output meant the diagnostics did not interfere with the buffering of stdout as the output line was built up. That and the use of no indentation on the debug code also meant it was easy to strip the debug code out.

    #include <string.h>
    #include <stdio.h>
    
    static int length(void) { return 3; }
    static int guessnum(void) { return 5; }
    
    int main(void)
    {
        int patternlength = length();
        char key[patternlength+1];      // Buffer overflow
        char keyc[patternlength+1];     // Copy of key
        int numguess = guessnum();
        char guess[patternlength+1];    // Buffer overflow
        printf("Input the key pattern with no spaces: ");
        scanf("%s", key);
        int i,j,count = 1;
        int bcount = 0, wcount = 0;
        char guessc[patternlength+1];   // Buffer overflow
        guessc[0] = '\0';               // Initialize!
        while (strcmp(key, guess) != 0 && count <= numguess)
        {
            strcpy(keyc, key);          // Copy key too
            printf("Input a guess pattern with no spaces: ");
            scanf("%s", guess);
            strcpy(guessc, guess);
    
    fprintf(stderr, "B1: (%s) vs (%s)\n", key, guess);
    fprintf(stderr, "B2: (%s) vs (%s)\n", keyc, guessc);
            wcount = 0;     // Reinitialize
            bcount = 0;     // Reinitialize
            printf("%d: ", count);
            for (i = 0; i < patternlength; i++)
            {
    fprintf(stderr, "L1a: %d\n", i);
                if (keyc[i] == guessc[i])
                {
    fprintf(stderr, "L1b: B (%c = %c)\n", keyc[i], guessc[i]);
                    putchar('b');
                    keyc[i] = guessc[i] = '.';
                    bcount++;
                }
            }
    fprintf(stderr, "M1: (%s) vs (%s)\n", keyc, guessc);
            if (bcount != patternlength)    // Extraneous semi-colon excised! ;
            {
    fprintf(stderr, "L2a: b = %d (%s) vs (%s)\n", bcount, keyc, guessc);
                for (i = 0; i < patternlength; i++)
                {
    fprintf(stderr, "L2b: %d (%c)\n", i, guessc[i]);
                    if (guessc[i] != '.')
                    {
    fprintf(stderr, "L2c: %d (%c)\n", i, guessc[i]);
                        //for (j = 0; i < patternlength; j++) BUG
                        for (j = 0; j < patternlength; j++)
                        {
    fprintf(stderr, "L2d: %d (%c) vs %d (%c)\n", i, guessc[i], j, keyc[j]);
                            //if (guessc[i] == keyc[i]) BUG
                            if (guessc[i] == keyc[j])
                            {
    fprintf(stderr, "L2e: W %d (%c) vs %d (%c)\n", i, guessc[i], j, keyc[j]);
                                wcount++;
                                putchar('w');
                                keyc[j] = guessc[i] = '.';
                                //guessc[i] = keyc[i];  BUG
                                break;
                            }
                        }
                    }
                }
    fprintf(stderr, "L3a: %d + %d vs %d\n", bcount, wcount, patternlength);
                for (i = bcount  +  wcount; i < patternlength; i++)
    fprintf(stderr, "L3b: D %d\n", i),
                    putchar('.');
            }
            count++;
            printf(" %s\n", guess);
        }
        if (strcmp(key, guess) != 0)
        {
            printf("You did not guess the pattern!\n");
        }
        else 
        {
            printf("You guessed the pattern!\n");
        }
        return 0;
    }
    

    Note the trick with the comma operator after the last fprintf() function call.

    Keeping a record of previous guesses and marks

    #include <stdarg.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    static void err_exit(const char *msg, ...);
    static void prompt_str(const char *prompt, int bufsiz, char *buffer);
    static int  prompt_int(const char *prompt);
    
    int main(void)
    {
        int  patternlength = prompt_int("Length of key");
        int  numguess = prompt_int("Number of guesses");
        char key[patternlength+1];
        char guesses[numguess][patternlength+1];
        char marks[numguess][patternlength+1];
        int  count = 0;
    
        prompt_str("Input the key pattern with no spaces", patternlength, key);
    
        while (count < numguess)
        {
            char guess[patternlength+1];
            char keyc[patternlength+1];
            char mark[patternlength+1];
            char *marker = mark;
            int wcount = 0;
            int bcount = 0;
    
            strcpy(keyc, key);
            prompt_str("Input a guess pattern with no spaces", patternlength, guess);
            strcpy(guesses[count], guess);
    
            for (int i = 0; i < patternlength; i++)
            {
                if (keyc[i] == guess[i])
                {
                    *marker++ = 'b';
                    keyc[i] = guess[i] = '.';
                    bcount++;
                }
            }
            if (bcount == patternlength)
                break;
            for (int i = 0; i < patternlength; i++)
            {
                if (guess[i] == '.')
                    continue;
                for (int j = 0; j < patternlength; j++)
                {
                    if (guess[i] == keyc[j])
                    {
                        wcount++;
                        *marker++ = 'w';
                        keyc[j] = guess[i] = '.';
                        break;
                    }
                }
            }
            for (int i = bcount  +  wcount; i < patternlength; i++)
                *marker++ = '.';
            *marker = '\0';
            strcpy(marks[count], mark);
            count++;
            for (int i = 0; i < count; i++)
                printf("Guess: %d [%s] marks [%s]\n", i, guesses[i], marks[i]);
        }
        if (count >= numguess)
            printf("You did not guess the pattern (which was [%s])!\n", key);
        else 
            printf("You guessed the pattern!\n");
        return 0;
    }
    
    static void prompt_str(const char *prompt, int bufsiz, char *buffer)
    {
        char fmt[8];
        int  c;
    
        sprintf(fmt, "%%%ds", bufsiz);
        printf("%s: ", prompt);
        if (scanf(fmt, buffer) != 1)
            err_exit("Unexpected input failure\n");
        while ((c = getchar()) != EOF && c != '\n')
            ;
    }
    
    static int prompt_int(const char *prompt)
    {
        int number;
        printf("%s: ", prompt);
        if (scanf("%d", &number) != 1)
            err_exit("Unexpected input failure\n");
        if (number <= 0 || number > 9)
            err_exit("Number should be in the range 1..9 (not %d)\n", number);
        return(number);
    }
    
    static void err_exit(const char *fmt, ...)
    {
        va_list args;
        va_start(args, fmt);
        vfprintf(stderr, fmt, args);
        va_end(args);
        exit(1);
    }
    

    Introduced functions prompt_int() and prompt_str() to get data. The prompt_str() function is reasonably resilient against overflows. There’s an error reporting function. The dummy functions are replaced. Here is some sample output. From here on, you’re on your own!

    Length of key: 4
    Number of guesses: 8
    Input the key pattern with no spaces: abcd
    Input a guess pattern with no spaces: aaaa
    Guess: 0 [aaaa] marks [b...]
    Input a guess pattern with no spaces: dcba
    Guess: 0 [aaaa] marks [b...]
    Guess: 1 [dcba] marks [wwww]
    Input a guess pattern with no spaces: cdba
    Guess: 0 [aaaa] marks [b...]
    Guess: 1 [dcba] marks [wwww]
    Guess: 2 [cdba] marks [wwww]
    Input a guess pattern with no spaces: abcd
    You guessed the pattern!
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm writing a program that simulates a lottery game, and I'm stuck at a
I'm writing a program in WPF application that simulates the game of life. How
I'm writing a program that simulates a snake, and the values of each section
I'm writing a program in C#, that have to simulate keyboard's key press commands.
I have tried writing program that plays a sound file but have been unsuccessful
I am writing a program that needs to do a bit of arithmetic. Here's
I'm new to C but trying some system calls. I'm writing program that iterates
I am writing a command line C program that simulates the Monty Hall Problem
I'm writing a program that connects to a servlet thanks to a HttpURLConnection but
Im writing a program that saves images from the Internet, but some of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.