Kurze Beschreibung zum Code:
4 Algorithmen zur Maximalen Summenbestimmung innerhalb eines Arrays von bestimmter Länge. Mein Problem ist das mit Randomzahlen gefüllte Array.
Warum erhalte ich eine NullPointerException? Anders.
Wieso akzeptiert der Compiler das leere Array nicht, das ja in der fillArray() mit Randomzahlen gefüllt wird und demnach vorher leer ist bzw. ungefüllt ist?
Liegt es daran, weil ich dem Array keine Größe gebe?
4 Algorithmen zur Maximalen Summenbestimmung innerhalb eines Arrays von bestimmter Länge. Mein Problem ist das mit Randomzahlen gefüllte Array.
Code:
import java.io.*;
import java.util.*;
public class MaxSum {
// static int[] a = {31, -41, 59, 26, -53, 58, 97, -93, -23, 84};
// static int[] a = new int[10000];
static int[] a;
static Random r = new Random();
public static int fillArray(int[] a) {
int i = 0;
for(i=0; i<10000; i++) {
a[i] = r.nextInt(200)-100;
}
return a[i];
}
static int left = 0;
static int right = 0;
static Writer fw = null;
/*
* MaxSum1
*/
public static int maxSum1(int[] a) {
int maximum = 0;
for (int left = 0; left<a.length; left++) {
for (int right = left; right<a.length; right++) {
int sum = 0;
for (int k = left; k<right; k++) {
sum += a[k];
if (sum>maximum) maximum = sum;
}
}
}
return maximum;
}
/*
* MaxSum2
*/
public static int maxSum2a(int[] a) {
int maximum = 0;
for (int left = 0; left<a.length; left++) {
int sum = 0;
for (int right = left; right<a.length; right++) {
sum += a[right];
if (sum>maximum) maximum = sum;
}
}
return maximum;
}
/*
* MaxSum3
*/
public static int maxSum3(int[]a) {
maxSum3_(left, right);
return maxSum3_(0,right-1);
}
public static int maxSum3_(int left, int right) {
if (left>right) return 0;
if (left==right) return a[right];
int middle = (left+right)/2;
//links
int lmidmax = 0;
int suml = 0;
for (int pos = middle; pos>=left; pos--) {
suml += a[pos];
lmidmax = Math.max(lmidmax,suml);
}
//rechts
int rmidmax = 0;
int sumr = 0;
for (int pos = middle; pos<right; pos++) {
sumr += a[pos];
rmidmax = Math.max(rmidmax, sumr);
}
//linker Teil
int leftmax = maxSum3_(left,middle);
//rechter Teil
int rightmax = maxSum3_(middle,right);
return Math.max(lmidmax+rmidmax,Math.max(leftmax,rightmax));
}
/*
* MaxSum4
*/
public static int maxSum4(int a[]) {
int maximum = 0;
int maxright = 0;
for (int pos = 0; pos<right; pos++) {
maxright = Math.max(maxright+=a[pos],0);
maximum = Math.max(maximum,maxright);
}
return maximum;
}
public static void main (String[]args) {
fillArray(a);
right = a.length;
System.out.println(maxSum1(a) + "\n");
System.out.println(maxSum2a(a) + "\n");
// System.out.println(maxSum3(a) + "\n");
System.out.println(maxSum4(a));
}
}
Warum erhalte ich eine NullPointerException? Anders.
Wieso akzeptiert der Compiler das leere Array nicht, das ja in der fillArray() mit Randomzahlen gefüllt wird und demnach vorher leer ist bzw. ungefüllt ist?
Liegt es daran, weil ich dem Array keine Größe gebe?