Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

java - Replace each “#” with an “X” or an “O” iteratively

I've been asked to generate all possible combinations of a row where the hidden # squares can be either X or O. I did it recursively but now I have to do an iterative version.

I tried replacing UnHide(strChar, i+1) with strChar = strChar.substring(0, i+1), but that doesn't work.

public static void main(String[] args) {
    String str = new String("XOXX#OO#XO");
    UnHide(str, 0);
}
public static void UnHide(String str, int i) {
    char[] charArr = str.toCharArray();
    String strChar = new String(charArr);
    if (i == charArr.length) {
        System.out.println(charArr);
        return;
    }
    //Replace masked "#" at each specified index by O or X
    if (charArr[i] == '#') {
        for (int j = 0; j < 2; j++) {
            //Replace masked "#" by O
            if (j == 0) {
                charArr[i] = 'O';
                strChar = String.copyValueOf(charArr);
                UnHide(strChar, i + 1); //Call UnHide with an incremented index
                strChar = strChar.substring(0, i + 1);
                charArr[i] = '#';
            }
            //Replace masked "#" by X
            else {
                charArr[i] = 'X';
                strChar = String.copyValueOf(charArr);
                UnHide(strChar, i + 1);
                charArr[i] = '#';
            }
        }
        return;
    }
    UnHide(strChar, i + 1);
}
question from:https://stackoverflow.com/questions/65893938/replace-each-with-an-x-or-an-o-iteratively

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am not sure where your code goes wrong, but you can try the following:

private static final char toReplace = '#';
private static final Set<Character> replacements = new HashSet<>(Arrays.asList('X', 'O'));

private static Set<String> UnHide(String s) {
    Set<String> result = new HashSet<>();
    result.add("");
    for (char c : s.toCharArray()){
        Set<String> updatedResult = new HashSet<>();
        for (String temp : result) {
            if (toReplace == c) {
                for (Character replacement : replacements) {
                    updatedResult.add(temp + replacement);
                }
            } else {
                updatedResult.add(temp + c);
            }
        }
        result = updatedResult;
    }
    return result;
}

Then calling:

String str = "XOXX#OO#XO";
System.out.println(UnHide(str));

outputs:

[XOXXOOOXXO, XOXXXOOOXO, XOXXOOOOXO, XOXXXOOXXO]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...