0

I am making a Mastermind program.

I generate a random String with 4 numerical characters (characters cannot repeat themselves). For testing purposes, it's always 1234.

The user is then asked to guess the String by inputing 4 numbers.

I am making a method called PerfectMatches that checks how many guessed numbers are correct AND in the right position.

Here is my code :

public static int perfectMatches (String x, String y){
    int i = 0;
    int perfectmatches = 0;

    for (i=0; i < 4; i++){
        if ((x.charAt(i)) == (y.charAt(i))){
            perfectmatches++;
        }

I tried using if statements but I felt it wasn't efficient and took longer to process for the program.

Dennis Meng
  • 5,109
  • 14
  • 33
  • 36

3 Answers3

0

Since the length is 4, then performance doesn't matter in this case. I think perfectMatches() method should return a boolean:

public static boolean perfectMatches(String x, String y) {...}

Also, avoid magic numbers:

for (int i = 0; i < x.length(); i++)

And at the end you could compare perfectmatches with 4, and return the boolean (true or false):

return (perfectmaches == 4);

But if you would like to return the numbers of matches, then the way you did your method is fine. Just return perfectmatches. As and advice, you can change the name of perfectmatches since it is very similar to the name of the method perfectMatches()

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • "checks how many guessed numbers are correct AND in the right position." . Maybe he will give a score based on number of right guesses. He could do it in the perfectMatches() itself . But its better to do it in the parent, seperate calculating and dsplaying. right? – TheLostMind Feb 28 '14 at 05:33
  • 1
    Yes, or make another method, that uses the `int` returned by `perfectMatches() to compare with the length of the `String` and return a `boolean`. – Christian Tapia Feb 28 '14 at 05:34
0

I don't think this could create any performance problem..

BTW, irrelevant to the question:

I have written the MasterMind application. You have to consider having the "numbers can't repeat" condition removed. It makes the game/puzzle easier, as well as the implementation.

If you want challenging puzzle as well the coding, allow duplication numbers. In that case, you will have to calculate both the perfect match and (match, but not in the same location) in a single method.

Amudhan
  • 696
  • 8
  • 18
0

There's no really a problem at it... it just check your code...

public int perfectMatches (String x, String y){ 
   int i = 0; 
   int perfectmatches = 0;

   for(i = 0; i < x.length(); i++){
      if(x.charAt(i) == y.charAt(i)){
          perfectmatches++;
      }
   }

   return perfectmatches;
}

another... remove the static...