I am trying to create an anagram generating program in Java.
I am using String.toCharArray();
to store the word character by character.
To get the anagrams done, I need to invert the values between two array positions. How do I do this?
Asked
Active
Viewed 101 times
-2

Nikaido
- 4,443
- 5
- 30
- 47

Riccardo Testa
- 1
- 2
-
Do you simply want to reverse the string? – lexicore Mar 21 '18 at 14:08
-
You are aware that the number of anagrams is exponential, right? – Giulio Franco Mar 21 '18 at 14:09
-
1You're looking for a `swap`. Try reading this: https://stackoverflow.com/questions/13766209/effective-swapping-of-elements-of-an-array-in-java – Giulio Franco Mar 21 '18 at 14:10
-
Yes, I am aware of the formula involving factorial! Thank you for the link, it solved the problem! – Riccardo Testa Mar 21 '18 at 14:15
-
PS : Welcome on StackOverflow, this is your first question, I hope you took the small [tour] of SO. I suggest you to check [ask]. Remember that you can always [edit] your question to improve it. – AxelH Mar 21 '18 at 14:22
1 Answers
0
Create a temp variable and store the first value of the array in it. Then set the value of the first element to the value of the last element and then set the last element to the temp variable, then repeat for each index of the array until the middle
char[] chars = char[]{a,b,c}
char temp;
for (int i=0; i < (int)char.length; i++) {
char temp = chars[i];
chars[i] = chars[chars.length - i];
chars[chars.length - i] = temp;
}

Euclidian
- 17
- 4
-
2First, you put a typo in `(int)char.length` and then why the need to cast ? array length is an already an `int`. PS : The resulting array will be the same at the end with that loop... – AxelH Mar 21 '18 at 14:18
-
First that's not what he ask for : he wants to swap only two char. Second you mispelled `chars` by `char` in your if statement so it won't work. Third as mentionned by @AxelH `chars.length` is already a int and does not need cast. Finally you said "repeat until the middle" and you made a loop over the whole array so the result will be the same as the input. – vincrichaud Mar 21 '18 at 14:26