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
Related
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);
I've searched about everywhere but I just can't find anything very concrete. I've been working on this code for awhile now but it keeps stumping me.
public static void main(String[] args) {
System.out.println(palindrome("word"));
}
public static boolean palindrome(String myPString) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
String reverse = "";
int startIndex = 0;
int str = word.length() -1;
while(str >= 0) {
reverse = reverse + word.charAt(i);
}
}
There's a lot of ways to accomplish this using a while loop.
Thinking about simplicity, you can imagine how could you do this if you had a set of plastic separated character in a table in front of you.
Probably you'll think about get the second character and move it to the begin, then get the third and move to begin, and so on until reach the last one, right?
0123 1023 2103 3210
WORD -> OWRD -> ROWD -> DROW
So, you'll just need two code:
init a variable i with 1 (the first moved character)
while the value of i is smaller than total string size do
replace the string with
char at i plus
substring from 0 to i plus
substring from i+1 to end
increment i
print the string
The process should be:
o + w + rd
r + ow + d
d + row +
drow
Hope it helps
Here is an piece of code I write a while back that uses almost the same process. Hope it helps!
String original;
String reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
for(int x = original.length(); x > 0; x--)
{
reverse += original.charAt(x - 1);
}
System.out.println("The reversed string is " +reverse);
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.
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.
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..