You are here:

C++/mastermind game

Advertisement


Question
the objective of the game is to guess the 4digit secret code of the computer.B is for a correct digit in the correct position and W is printed for every correct but misplaced digit.
example:the secret code is 1234
input: 8245 output:BW
i tried doing the program with the ff segments but i can't fully complete it.

for the random combination:
for(j=1;j<=4;j++)
a[j]=random(10)

since it is only allowed to guess 10 times:

for(int attempt=0;attempt<10;attempt++)
{ for(j=0;j<4;j++)
    a[j]=random(10)

      for(i=0;i<4;i++)
       {
       if (a[j]==b[i]& j!=i)
       cout<<"W"
       if (a[j]==b[i]& j==i)
        cout<<"B"
       }
}
variables:
a is the array where the secret code is stored
b is the array where the guess is stored
j is the index for array a
i is the index for array b

sorry for the disturbance and thank you for your time and patience!

Answer
1. you have missed semicolons
2. your "&" should be replaced by "&&"

for(j=1;j<=4;j++)
a[j]=random(10);

for(int attempt=0;attempt<10;attempt++)
{ for(j=0;j<4;j++)
   a[j]=random(10);

     for(i=0;i<4;i++)
      {
      if (a[j]==b[i]& j!=i)
      cout<<"W";
      if (a[j]==b[i]& j==i)
       cout<<"B";
      }
}

For learning C++, please see Bruce Eckel's book which has both an online and print versions.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Amit Kumar

Expertise

I can answer Cplusplus language and library questions, including STL, ACE, Boost. I have a good background in Mathematics.

Experience

Programming in CPP for about 8 years. Industry experience of 4 years.

Education/Credentials
Bachelors and Masters in Computer Science from Indian Institute of Technology Delhi.

©2016 About.com. All rights reserved.