Skip to content

Instantly share code, notes, and snippets.

@slava-konashkov
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save slava-konashkov/9291329 to your computer and use it in GitHub Desktop.

Select an option

Save slava-konashkov/9291329 to your computer and use it in GitHub Desktop.
Итеративно уменьшить массив до массива из 2-3 элементов
package cycles;
import java.util.Arrays;
public class Reduce {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9};
while (a.length > 3) {
a = reduce(a);
}
System.out.println(Arrays.toString(a));
}
private static int[] reduce(int[] orig) {
int iLength = (orig.length + 1) >> 1;
int[] a = new int[iLength];
for (int i = 0; i < iLength; i++) {
if (i + iLength < orig.length) {
a[i] = orig[i] + orig[i + iLength];
} else {
a[i] = orig[i];
}
}
return a;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment