Sort Words by Position Index in Java

The challenge

Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.

Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.

Examples

"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est" "4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople" "" --> ""
Code language: JavaScript (javascript)

The solution in Java code

Option 1:

public class Order { public static String order(String words) { String[] _words = words.split(" "); String[] out = new String[_words.length]; for (int i=0; i<_words.length; i++) { for (Character c : _words[i].toCharArray()) { if (Character.isDigit(c)) { out[Character.getNumericValue(c)-1] = _words[i]; } } } if (out.length<=1) return ""; return java.util.Arrays.stream(out).collect(java.util.stream.Collectors.joining(" ")); } }
Code language: Java (java)

Option 2:

import java.util.Arrays; import java.util.Comparator; public class Order { public static String order(String words) { return Arrays.stream(words.split(" ")) .sorted(Comparator.comparing(s -> Integer.valueOf(s.replaceAll("\\D", "")))) .reduce((a, b) -> a + " " + b).get(); } }
Code language: Java (java)

Option 3:

public class Order { public static String order(String words) { String[] arr = words.split(" "); StringBuilder result = new StringBuilder(""); for (int i = 0; i < 10; i++) { for (String s : arr) { if (s.contains(String.valueOf(i))) { result.append(s + " "); } } } return result.toString().trim(); } }
Code language: Java (java)

Test cases to validate our solution

import static org.junit.Assert.*; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; public class OrderTest { @Test public void test1() { assertThat(Order.order("is2 Thi1s T4est 3a"), equalTo("Thi1s is2 3a T4est")); } @Test public void test2() { assertThat(Order.order("4of Fo1r pe6ople g3ood th5e the2"), equalTo("Fo1r the2 g3ood 4of th5e pe6ople")); } @Test public void test3() { assertThat("Empty input should return empty string", Order.order(""), equalTo("")); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments