0

I am stuck with this challenge, any help would be great.

'Create a function that takes both a string and an array of numbers as arguments. Rearrange the letters in the string to be in the order specified by the index numbers. Return the "remixed" string. Examples

remix("abcd", [0, 3, 1, 2]) ➞ "acdb"'

My attempt -

package edabitChallenges;

//Create a function that takes both a string and an array of numbers as arguments.
//Rearrange the letters in the string to be in the order specified by the index numbers.
//Return the "remixed" string.

public class RemixTheString {

    public static String remix(String word, int[] array) {
        char[] wordArray = word.toCharArray();

        for (int i = 0; i < array.length; i++) {        
                char ch = ' ';
                ch = wordArray[i];
                wordArray[i] = wordArray[array[i]];
                wordArray[array[i]] = ch;
        }

        String newString = new String(wordArray);
        return newString;
    }

    public static void main(String[] args) {
        System.out.println(remix("abcd", new int[] { 0, 3, 1, 2 }));

    }
}
Turing85
  • 18,217
  • 7
  • 33
  • 58
taha
  • 11
  • 1
    Are you sure `remix("abcd", [0, 3, 1, 2]) ➞ "acdb"` is correct? Shouldn't it return `adbc`? My rationale is that since indexes of original characters are `a-0 b-1 c-2 d-3` so sequence 0 3 1 2 corresponds to `a d b c`. – Pshemo Jul 18 '21 at 06:40

1 Answers1

5

I would suggest just iterating the indices passed in the array[] input, and then building out the output string:

public static String remix(String word, int[] array) {
    char[] wordArray = word.toCharArray();
    StringBuilder output = new StringBuilder();

    for (int i=0; i < array.length; i++) {
        output.append(wordArray[array[i]]);
    }

    return output.toString();
}

public static void main(String[] args) {
    System.out.println(remix("abcd", new int[] { 0, 3, 1, 2 }));  // adbc
}

Here we use StringBuilder which exposes a handy append(char) method for adding one character at a time to the string in progress.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360