Hallo,
kann mir einer von euch vielleicht bei der folgenden Aufgabe helfen:
Wie wurde der folgende Code mit der Methode Merger aussehen?
Code:
Methode Merger:
kann mir einer von euch vielleicht bei der folgenden Aufgabe helfen:
Wie wurde der folgende Code mit der Methode Merger aussehen?
Code:
Java:
public class Merge {
public static long[] merge(long[] ns, int i, Merger m) {
m.merge();
if (i >= ns.length) {
return new long[0];
}
if (i < 0) {
return merge(ns, 0,m);
}
long[] sub = new long[ns.length - i];
System.arraycopy(ns, i, sub, 0, ns.length - i);
if (sub.length >= 2) {
long[] common = getCommons(sub);
long res = multiply(common);
return mergeLongArray(new long[]{res}, merge(sub, common.length, m));
} else {
return new long[]{sub[0]};
}
}
public static long multiply(long[] arr) {
long sum = 1;
for (long x : arr) {
sum *= x;
}
return sum;
}
public static long[] getCommons(long[] arr) {
int count = 1;
for (int i = 0; i < arr.length - 1 && arr[i] == arr[i + 1]; i++) {
count++;
}
long[] result = new long[count];
System.arraycopy(arr, 0, result, 0, count);
return result;
}
public static long[] mergeLongArray(long[] arr1, long[] arr2) {
long[] result = new long[arr1.length + arr2.length];
System.arraycopy(arr1, 0, result, 0, arr1.length);
System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
return result;
}
}
Java:
public interface Merger {
/**
* Appends {@code newLast} to the array {@code old}, e.g. append({0, 1, 2, 3}, 42) gives the new array {0, 1, 2, 3, 42}.
*
* @param old
* - the array to which {@code newLast} is to be appended
* @param newLast
* - the value to be appended to the array {@code old}
* @return a new array containing the values from {@code old} preserving their order as of {@code old} followed by {@code newLast} as last element
*/
public long[] append(long[] old, long newLast);
/**
* Prepends {@code newFirst} to the array {@code old}, e.g. prepend(42, {0, 1, 2, 3}) gives the new array {42, 0, 1, 2, 3}.
*
* @param newFirst
* - the value to be prepended to the array {@code old}
* @param old
* - the array to which {@code newFirst} is to be prepended
* @return a new array containing {@code newFirst} as first element at position 0 followed by the values from {@code old} preserving their order as of {@code old}
*/
public long[] prepend(long newFirst, long[] old);
/**
* Used to log and check your recursion. YOU MUST CALL THIS METHOD IMMEDIATELY AT THE BEGINNING OF YOUR METHOD.
*/
public void merge();
}