-1
\$\begingroup\$

I'm trying to find the most efficient algorithm for solving Hangman. For those who are not familiar, it's a game where people need to guess the correct letters in a word.

I've written the following function:

string solveWord='Hangman';
string guessWord='-------';
char letter = 'l';
int index;

public void guessLetter(char letter) {
     if (!guessWord.equals(solveWord)) { 

        if (solveWord.contains(String.valueOf(letter))) {   

            index = solveWord.indexOf(letter); 

            while (index >= 0) {
                guessWord = replace(guessWord, index, letter); 
                index = solveWord.indexOf(letter, index + 1); 
            }
        }
    }
}

public String replace(String string, int index, char replace) {
    if (string == null) {
        return string;
    } else if (index < 0 || index >= string.length()) {
        return string;
    }
    char[] chars = string.toCharArray();
    chars[index] = replace;
    return String.valueOf(chars);
}

I'm looking for ways to improve upon it to decrease execution time and increase the readibility of the code.

\$\endgroup\$
  • \$\begingroup\$ please post the whole code. it's hard to review just a fragment with so much missing. \$\endgroup\$ – Emily L. Jun 19 '17 at 22:16
  • \$\begingroup\$ @EmilyL. it looks good to me am I missing something? Is replace custom method? \$\endgroup\$ – Denis Jun 19 '17 at 22:19
  • \$\begingroup\$ Emily is right, I'm adding the replace method. Not seeing anything else of relevance missing though. \$\endgroup\$ – Fang Jun 19 '17 at 22:20
  • 1
    \$\begingroup\$ The first four lines is not your real code. Please add the real way you are using this code. \$\endgroup\$ – Simon Forsberg Jun 19 '17 at 22:24
  • 3
    \$\begingroup\$ @Fang Everything you put in the question is relevant to us. We do expect the code you post here to be your exact real code, otherwise how can we know what's real and what's not? Unfortunately it has happened to us way too many times that the advice we give gets the response "Yeah, well, that's not helping me because that's not really how my code is". You don't need to show us your entire application, but we do expect that you show us real code. \$\endgroup\$ – Simon Forsberg Jun 19 '17 at 23:20
1
\$\begingroup\$

I don't do java so I can't comment on the syntax, but one obvious improvement would be to avoid calling solveWord.contains(String.valueOf(letter)) but instead obtain the solveWord.indexOf(letter) right away and than test if it's greater than 0 (I assume if it doesn't exist it will return -1).

Besides that, the way C#'s string.Replace(string oldValue, string newValue) works is that it will replace all (if any) occurrences of the old value with the new one.

If there isn't one already defined in java (which I doubt) you might try writing your own this way.

|improve this answer|||||
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.