i need Given a set of numbers on the command line (partition an array)
It should check whether a solution exists and if so print the two sets
upto now the code i have seems to parttion each integer, what i need is for it to partition the array as a whole, for example lets take the array[1,2,3] this can be divided as [1,2] and [3], we can see that these two subsets have an equal sum.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication2;
import java.util.ArrayList;
import java.util.Collection;
public class Partition {
private static int arrayNumber = 0;
private static Collection<Integer> s1 = new ArrayList<Integer>();
private static Collection<Integer> s2 = new ArrayList<Integer>();
public static void partition(int n) {
partition(n, n, "");
}
public static void partition(int n, int max, String prefix) {
if (n == 0) {
arrayNumber++;
String[] s = prefix.split(" ");
if (arrayNumber == 2) {
addtoArray(s, s1);
} else if(arrayNumber == 3) {
addtoArray(s, s2);
}
//System.out.println("--------------");
//System.out.println(prefix);
return;
}
for (int i = Math.min(max, n); i >= 1; i--) {
partition(n-i, i, prefix + " " + i);
}
}
private static void addtoArray(String s[], Collection<Integer> col) {
for (int i = 0; i < s.length; i++) {
String numStr = s[i];
if (numStr.equals("")) {
continue;
}
int num = Integer.parseInt(numStr);
col.add(num);
}
}
public static void main(String[] args1) {
String[] args = {"6", "2", "4"};
for (int i = 0; i < args.length; i++) {
arrayNumber = 0;
String str = args[i];
int n = Integer.parseInt(str);
partition(n);
}
for (int number : s1) {
System.out.print(number + " ");
}
System.out.println("");
for (int number : s2) {
System.out.print(number + " ");
}
System.out.println("");
}
}
PLEASE HELP