Dmytro Chyzhykov
BAN USERHere is a possible algorithm:
public class ReverseWordsInString {
//
public static void main(String... args) {
String original = "i am a girl";
String reversed = reverse(original);
// print original string and reversed words
System.out.printf("original string: `%s`%n", original);
System.out.printf("reversed string: `%s`%n", reversed);
}
//
private static String reverse(String original) {
// not null precondition
if (original == null) {
throw new RuntimeException("A null string has been passed.");
}
// split by non-word characters
String[] words = original.split("\\W+");
// join words
StringBuilder out = new StringBuilder();
String separator = "";
for (int i = words.length - 1; i >= 0; i--) {
out.append(separator).append(words[i]);
separator = " ";
}
// produce out string
return out.toString();
}
//
}
//
program's output:
original string: `i am a girl`
reversed string: `girl a am i`
Here is a little piece of code from me:
import java.util.Arrays;
public class SortedMatrixToSortedArray {
public static void main(String... args) {
int[][] matrix = {
{2, 5, 7, 9, 14, 16},
{3, 6, 8, 10, 15, 21},
{4, 7, 9, 15, 22, 35},
{7, 8, 9, 22, 40, 58}
};
int[] result = mergeAndSort(matrix);
int[] expected = {2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15, 16, 21, 22, 35,
40, 58};
System.out.printf("result: %s%n", Arrays.toString(result));
System.out.printf("expected: %s%n", Arrays.toString(expected));
}
private static int[] mergeAndSort(int[][] matrix) {
int[] result = new int[]{};
for (int[] row : matrix) {
result = mergeAndSort(result, row);
}
return result;
}
private static int[] mergeAndSort(int[] x, int[] y) {
int n = findDistinctLength(x, y);
int[] result = new int[n];
for (int k = 0, i = 0, j = 0; k < n; k++) {
if (i == x.length) {
result[k] = y[j++];
} else if (j == y.length) {
result[k] = x[i++];
} else if (x[i] < y[j]) {
result[k] = x[i++];
} else if (x[i] > y[j]) {
result[k] = y[j++];
} else {
result[k] = x[i];
i++;
j++;
}
}
return result;
}
private static int findDistinctLength(int[] x, int[] y) {
int i = 0;
int j = 0;
int n = 0;
while (i < x.length && j < y.length) {
if (x[i] < y[j]) {
i++;
} else if (x[i] > y[j]) {
j++;
} else {
i++;
j++;
}
n++;
}
return n + x.length - i + y.length - j;
}
}
See with tests here - github.com/ffbit/just-for-fun/blob/master/src/test/java/com/ffbit/fun/array/SortedMatrixToSortedArray.java
- Dmytro Chyzhykov January 08, 2013
Here is a possible solution in Java and JUnit
- Dmytro Chyzhykov January 11, 2013