Not able to understand string permutation Java code - java

I have this working code to print string permutations without repetitions, but not able to wrap my head around how is it working as in logic. Any suggestions will be really helpful.
private static void permutation(String input, String sofar) {
if (input.equals("")) {
System.out.println(count + " " + sofar);
count++;
}
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (input.indexOf(c, i + 1) != -1)
continue;
permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
}
}
Function call:
String input = "ABBCD";
permutation(input, "");

for (int i = 0; i < input.length(); i++) {
The above for loop is doing the magic
Input ABCD
Iterations
input: BCD sofar: A .... recursion goes on
input: ACD sofar: B ....
input: ABD sofar: C ....
input: ABC sofar: D .....
Hope this helps

Just remember that recursion is usually a stop condition, and an attempt to solve a smaller problem using the recursive call, under the assumption that the recursion works.
I've commented the code so you can replace that with your copy to keep track of what it's doing when you get back to it. Add your own comments once you understand as they'll help you follow what happens:
Part 1: The basic condition / stop condition:
if (input.equals("")) {
System.out.println(count + " " + sofar);
count++;
}
This part stops the recursion and returns a result, the base case being an empty string, which has a single permutation that is also an empty string.
Part 2: Iterating smaller problems.
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
// ...
permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
}
This part uses the recursive call on a smaller (by one character) string, to solve the problem. It calls the same string omitting a character it prepends to whatever following results it generates. We know the call generates all permutations (that's our assumption). So we now know what the recursion does.
Part 2.1: The de-duplicating "if":
This is probably the trickiest part here...
if (input.indexOf(c, i + 1) != -1)
continue;
Let's figure this out. What it means, is: "try and find a character the same as the one selected, and if one exists, skip this iteration and it's generated solutions".
Think of a word like "ABBA" it will skip the first "A" and "B", but not the last ones. Why? Well, since order of similar characters does not matter (if we tag the character A1 B1 B2 A2, and now replace them: A2 B2 B1 A1, this is still the same word, so there is only one permutation for words like "AA", since A1 A2 is the same as A2 A1.
Taking the last characters is easier, since we don't need to maintain a list of the characters we already used in this iteration.
The full code with basic comments:
private static void permutation(String input, String sofar) {
if (input.equals("")) {
// this is the stop condition
// the only permutation of "" is ""
System.out.println(count + " " + sofar);
// this counts how many permutations were outputted.
count++;
}
for (int i = 0; i < input.length(); i++) {
// this loop basically means "take every
// possible character, and append permutations of all
// other characters to it.
char c = input.charAt(i);
if (input.indexOf(c, i + 1) != -1)
// this makes sure we only take a single "A" or "B"
// character in words like "ABBA", since selecting
// the same character would create duplicates
continue;
// this creates a new string without the selected character
// and under the assumption the recursion works
// appends all permutations of all other characters
// to it
permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
}
}

if (input.equals("")) {
System.out.println(count + " " + sofar);
count++;
}
This step is passed as the input is not "". Note that you could simply use input.empty() here. The only thing to remember here is that count have not been incremented.
for (int i = 0; i < input.length(); i++) {
This will, loop over all character of the input
char c = input.charAt(i);
if (input.indexOf(c, i + 1) != -1)
This check if the next character is equal to the current one, if it does then it will jump directly to the next iteration(the next character) using the continue keyword.
If it does not, then it will recall the method (We call that recursivity), passing in the string without the current char. But giving it back to sofar.
permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
Now in the case where input is empty,
The count of non-distinct character will be printed + all these character.

Related

Could someone explain how revWord is printed in reverse?

String word = "elephant";
String revWord = "";
for (int i = 0; i < word.length(); i++) {
revWord = word.charAt(i) + revWord;
}
System.out.println("Word: " + word + " in reverse is " + revWord);
I know how for loops word and charAt and incrementation
I just don't understand how it reverses it
This is the output:
Word: elephant in reverse is tnahpele
The best way to understand your code is to take a piece of paper and work out each iteration of the loop, until it "clicks" in your own head. Let's take a three character string input of ABC to see what happens:
after first iteration:
revWord = A + "" = A
after second iteration:
revWord = B + A = BA
after third iteration:
revWord = C + BA = CBA
Basically, at each step of the loop it tags on the next letter to the front of the running reverse string. As you can see above, this has the effect to flip the order of characters in the input word.
it's because of this line:
revWord = word.charAt(i) + revWord;
each time your loop goes pick a char and place it in begining of the revWord.
it mwans the for each time step forward and near to end of String characters place them in first of revWord String

Split a string in java according to characters with even or odd order

You input a word which is a string. What I want to do is to put the letters in an odd position in a variable and those on an even position in another variable...
But I have been reading online and all I can find is how to split by a specific character like: "/", "-" or "". But I dont have one.. show what should I use...
Should I solve this in an other way....
EX:
String S = "alfabet";
and I want to print out:
odd = "afbl";
even = "lae";
System.out.println(odd + " " + even);
I used two strings called odd and even and set both of them to be empty then i iterate throught all the letters of the string s and add the even characters to even and odd characters to odd like the following:
String S = "alfabet";
String odd="";String even="";
for(int c=0;c<S.length();c++)
{
if(c%2==0)odd+=S.charAt(c);
else even+=S.charAt(c);
}
Please do the following:
int i = 0;
StringBuilder oddString = new StringBuilder();
StringBuilder evenString = new StringBuilder();
while(i++ < S.length())
{
if(i & 1){
oddString.append(S.charAt(i));
}else{
evenString.append(S.charAt(i));
}
}
System.out.println("Even String: " + evenString);
System.out.println("Odd String: " + oddString);

Making a list of all combinations of 2 letters and 4 numbers

I have been trying to create a code that can make a list of all combinations of 2 letters and 4 numbers
EX: aa1111, ab1111
the only thing that i can come up with are programs that print combinations that are against my outline
EX: aatc9e, gj3ru7
What can I do that makes it so it stops at two letters and goes to the four numbers?
I'd do it as 3 while loops, and add each one.
It's also useful that Characters can be both letters and numbers.
Given you haven't added any code, here's some dirty pseudo code:
Output = New Array[]
char characterOne = 'A'
while characterOne < 26:
char characterTwo = 'A'
while characterTwo <26:
char Number = '0000'
while Number < 9999:
Output.add (CharacterOne + CharacterTwo + Number.toString)
Number ++
characterTwo++
characterOne++
Remember; stack overflow likes specificity, include your code next time.
This process is rather involved as you are going to generate combinations of strings from
aa0000 - zz9999.
It can be done with one while loop, an Array of two Strings, and one int. You'll have to know when your number > 9999 so you can increment the second letter (letters[1]), then you have to know when the second letter is about to pass "z" so you can increment the first letter (letters[0]) and start the second letter back at "a".
public static void main(String[] args) throws Exception {
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String[] letters = new String[] { "a", "a" };
int number = 0;
String combination = letters[0] + letters[1] + String.format("%04d", number);
while (!combination.contentEquals("zz9999")) {
// Output the combination
System.out.println(combination);
number++;
if (number > 9999) {
int letterIndex = alphabet.indexOf(letters[1]) + 1;
if (letterIndex < alphabet.length()) {
// Get the next letter in the alphabet
letters[1] = String.valueOf(alphabet.charAt(letterIndex));
} else {
// We've passed z, so we need to increment the first letter
letterIndex = alphabet.indexOf(letters[0]) + 1;
if (letterIndex < alphabet.length()) {
// Get the next letter in the alphabet
letters[0] = String.valueOf(alphabet.charAt(letterIndex));
}
// Start back at letter a
letters[1] = "a";
}
// Start back at zero
number = 0;
}
// Format the next combination
combination = letters[0] + letters[1] + String.format("%04d", number);
}
// Print the last combination
System.out.println(combination);
}
Seeing that this is your first question on SO, next time post code that shows an actual attempt to your question. Don't just post a question without giving an effort to solve it yourself, and expect SO to solve it for you.

Loop is not resetting?

Belowe is code that checks for matching parentheses to see if they are nested properly. It seems really simple, but I don't understand why i does not reset to 0 once a nested match is found. Any guidance would be much appreciated.
String testString = "{}()[] ";
char [] openParenthesis = {'(','{','['};
char [] closeParenthesis = {')','}',']'};
ArrayList<Character> characterList = new ArrayList<Character>();
for(char c : testString.toCharArray())
{
characterList.add(c);
System.out.println("This is what is added to the list Arraylist: " + c);
}
System.out.println();
for(int i = 0; i < characterList.size()-1; i++)
{
System.out.println("1st Loop: " +characterList.get(i));
System.out.println("1st Loop: " + characterList.get(i + 1));
System.out.println("1st Loop: " + i);
System.out.println();
for(int j = 0; j < openParenthesis.length; j++)
{
if (characterList.get(i) == openParenthesis[j])
{
if(characterList.get(i + 1) == closeParenthesis[j])
{
System.out.println("Nested Match");
System.out.println(characterList.get(i));
System.out.println(characterList.get(i + 1));
System.out.println();
characterList.remove(i);
characterList.remove(i + 1);
i = 0;
}
}
}
}
First off all you are removing the wrong spots in the ArrayList.
Because it is an ArrayList characterList.remove(i); will move everything over to the left one spot, so then the next like characterList.remove(i+1); removes the one to the right of where you want.
You also need to add a break in the openParenthesis loop so you can start the search over at the beginning of the array if you find a match.
You also need to change the i = 0 to i = -1 because it increments it to one BEFORE it starts the next iteration of the for loop.
Finally, you should be using .equals() instead of == because the ArrayList returns a Character object instead of a char.
Here is what I came up with:
for (int i = 0; i < characterList.size() - 1; i++) {
System.out.println("1st Loop: " + characterList.get(i));
System.out.println("1st Loop: " + characterList.get(i + 1));
System.out.println("1st Loop: " + i);
System.out.println();
for (int j = 0; j < openParenthesis.length; j++) {
if (characterList.get(i).equals(openParenthesis[j])) {
if (characterList.get(i + 1).equals(closeParenthesis[j])) {
System.out.println("Nested Match");
System.out.println(characterList.get(i));
System.out.println(characterList.get(i + 1));
System.out.println();
characterList.remove(i);
characterList.remove(i);
i = -1;
break;
}
}
}
}
This code has fixed all the errors mentioned above and should run correctly.
Obviously because of the i++ in for loop i equal to 1. if you really want to set 0 for i again. use i=-1;
Your for loop increments i by one AFTER the body of the loop is completed.
Thus, you set i=0, you exit the body of the loop, i++ is called, and you enter the loop body once more with i ==1.
Well it depends on what your testString is. I tested it with value foo() and loop did go inside if(characterList.get(i + 1) == closeParenthesis[j]) condition.
However there is a problem in your code where you have:
characterList.remove(i);
characterList.remove(i + 1);
Which will result in java.lang.IndexOutOfBoundsException since i+1 location has become invalid (out of range) after deleting ith element. It should be other way round:
characterList.remove(i + 1);
characterList.remove(i);
Also instead of i=0; you need to set it to: i = -1;
And more importantly break out of inner for loop by calling break.
So your code in the end should look like this:
i = -1;
break;
See working demo: http://ideone.com/DfGJ2m
I guess you could have used a stack data structure and using a process similar to http://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/
When you store a character in a list, java autoboxes it to a Character. You cannot use the == operator to compare two Characters for equality, but must use the .equals() method, as this code demonstrates:
Character aOne = new Character('a');
Character aTwo = new Character('a');
if(aOne == aTwo)
{
System.out.println("aOne and aTwo == operator says they are equal");
}
else
{
System.out.println("aOne and aTwo == operator says they are NOT equal");
}
if(aOne.equals(aTwo))
{
System.out.println("aOne and aTwo .equals operator says they are equal");
}
Code prints out:
aOne and aTwo == operator says they are NOT equal
aOne and aTwo .equals operator says they are equal

Compare two Strings letter by letter

Well, I have two strings to compare and check letter by letter if they match, and if hits a '-' i need to count how many '-' there's in sequence and put them in a group as if they were only one char and count how many T and C there in this group of '-'. The output should be like 2.1T and 2.2C and the other one 5.2C.
String dna1 = "TC---CA--";
String dna2 = "TCTCCCACC";
char[] dnaChar = dna1.toCharArray(), dna2Char = dna2.toCharArray();
int cont = 0;
int letters = 0;
for (int i = 0; i < dnaChar.length; i++) {
if (dnaChar[i] != dna2Char[i]) {
int mut = i + 1;
if (dna1.charAt(i) == '-') {
cont++;
mut -= cont;
if (dna2.charAt(i) == 'C') {
letters++;
}
System.out.println(mut + "." + letters + dna2.charAt(i));
} else {
letters = 0;
cont = 0;
mut += 1;
System.out.println("" + dna1.charAt(i) + " " + mut + " " + dna2.charAt(i));
}
}
}
The output
2.0T
2.1C
2.2C
4.3C
4.4C
And what i want 2.1T 2.2C 5.2C
The output that you expect will never be obtained from your above code.. Because in your if construct will be executed every time you encounter a '-' in your first string.. And hence you will have 5 outputs, not 3..
Second, to get what you need, you will have to do some extra work here..
First When you encounter a '-' in your 1st String, you need to store the corresponding character from your second String into some variable.. Because you need it to check for continuous characters.
Second, each time to get a '-', check the current character with the last character matched for the previous '-'. If it is the same, increase the count by 1,
If it is not the same, just print what you want.. and reset your count to 0
As soon as you encounter the character which not '-' in your first string, print the current character and the count value, and reset them..
You can try to code according to the steps I have mentioned..
*PS: - For any problem you get to code, you should first write down the steps you should follow to solve it on paper. Then convert it to code step-by-step. It will be easier to understand the problem and solve it also..

Categories

Resources