Question: can you please help me write this code iteratively, (preferably using stacks): the code is in java, and it works to find all # characters
can you please help me write this code iteratively, (preferably using stacks):
the code is in java, and it works to find all "#" characters within a string and replace all occurrences of "#" by either "X" or "O", and then output all possible combinations.
i would like to make it so that when the user inputs a string with characters of either "X", "O" , or "#"... every instance of "#" is replaced by either "X" or "O" and then all possible permutations of that new string with only "X" or "O" is output.
in the recursive code below, the method UnHide is what converts every "#" into "X" or "O", and i would like this to be rewritten iteratively.
code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class V1{
public static void main(String[] args) {
// Ask the user to input a random string
System.out.print("Please enter a random string with a random number of crosses, noughts, and hashtags: ");
String userInput = new Scanner(System.in).next();
System.out.println(userInput);
try {
// Open out.txt for printing
PrintWriter p = new PrintWriter(new FileOutputStream("outv1.txt"));
// Save the start time of the method
long startTime = System.currentTimeMillis();
UnHide(userInput);
// Save the end time of the method
long endTime = System.currentTimeMillis();
// Close the file
p.close();
// Open time.txt file and print elapsed time to it
p = new PrintWriter(new FileOutputStream("timev1.txt", true));
p.println("Elapsed time: " + (endTime - startTime)/1000. + " seconds.");
p.close();
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
public static String change(String a, String b) {
String temporary = a.replaceFirst("#", b);
return temporary;
}
// UnHide method
public static void UnHide(String a){
if(a.contains("#")) {
UnHide(change(a, "X"));
UnHide(change(a, "O"));
}else {
System.out.println(a);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
