javabeginner :
I'm trying to switch the elements in the letters array to the corresponding positions in the positions array. The elements are getting swapped but not to the right position. Am I doing this completely wrong or is there just a problem in my logic?
public class Words
{
public static void main (String args[])
{
char letters[] = {'l', 'o', 'e', 'h', 'l'};
int positions[] = {2, 4, 1, 0, 3};
int limit1 = letters.length;
int temp1;
char temp2;
for(int i = 0; i < letters.length; i++)
{
limit1--;
for(int j = 0; j < limit1; j++)
{
temp1 = positions[j];
temp2 = letters[temp1];
letters[temp1] = letters[j];
letters[j] = temp2;
}
}
for(int i = 0; i < letters.length; i++)
{
System.out.print(letters[i] + " ");
}
}
}
Andreas :
If you don't have to do this in-place, it would be a lot easier to just create a new array.
char[] letters = {'l', 'o', 'e', 'h', 'l'};
int[] positions = {2, 4, 1, 0, 3};
char[] result = new char[letters.length];
for (int i = 0; i < letters.length; i++)
result[positions[i]] = letters[i];
System.out.println(result);
Output
hello
For an in-place solution, the following will do. Same output as above.
char letters[] = {'l', 'o', 'e', 'h', 'l'};
int positions[] = {2, 4, 1, 0, 3};
for (int i = 0, j; i < letters.length; i++) {
while ((j = positions[i]) != i) {
char tempLetter = letters[i];
letters[i] = letters[j];
letters[j] = tempLetter;
int tempPosition = positions[i];
positions[i] = positions[j];
positions[j] = tempPosition;
}
}
System.out.println(letters);
That can easily be written using only one loop.
for (int i = 0, j; i < letters.length; ) {
if ((j = positions[i]) == i) {
i++;
} else {
char tempLetter = letters[i];
letters[i] = letters[j];
letters[j] = tempLetter;
int tempPosition = positions[i];
positions[i] = positions[j];
positions[j] = tempPosition;
}
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=356197&siteId=1