Merge sort in ArrayList in Java - java

I am learning how to implement basic algorithms in Java, so i am a newbie in this environment. I am trying to implement Merge Sort algorithm using ArrayList where program will read data (Integer in each line) from file and produce sorting result using Merge Sort. However, my code is showing same result as it has not sorted anything out! I would be very glad if someone can identify where did I do my mistake. As i am a beginner, the code is very simple, not optimized and not very fast in performance probably.
Here is my code:
public class MergeSortExp1 {
public static void main(String[] args) {
ArrayList<Integer>number = new ArrayList<Integer>();
Scanner myScanner = null;
try {
myScanner = new Scanner(new File("/Users/Sabbir/Desktop/workload.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(myScanner.hasNextInt()){
number.add(myScanner.nextInt());
}
System.out.println("Before sorting" +number);
number=mergeSort(number);
System.out.println("Sorted Array =" +number);
}
public static ArrayList<Integer> mergeSort( ArrayList<Integer> Input)
{
if (Input.size() ==1){
return Input;
}
else {
int mid= Input.size()/2;
ArrayList<Integer> left= new ArrayList<Integer>(mid);
ArrayList<Integer> right=new ArrayList<Integer>(Input.size()-mid);
for (int i = 0; i < mid; i++) {
left.add(Input.get(i));
}
for (int i = 0; i < Input.size()-mid; i++) {
right.add(Input.get(i));
}
left=mergeSort(left);
right=mergeSort(right);
merge(left,right,Input);
}
return Input;
}
public static void merge (ArrayList<Integer>left,ArrayList<Integer>right,ArrayList<Integer>Input)
{
int i1=0;// left Index
int i2=0;// right Index
int InputIndex=0;
for (int i = 0; i < Input.size(); i++) {
if (i2>=right.size() || (i1<left.size() && left.get(i)<=right.get(i)))
{
Input.set(InputIndex,left.get(i1));
InputIndex++;
}
else {
Input.set(InputIndex, right.get(i2));
InputIndex++;
}
}
}
}

If your merge method is Ok (I don't test it), you forget to merge left and right to input, edit your code as shown below and re-try:
// This is called recursion. Calling a method again within the
//method until the value of left and right becomes 1.
left=mergeSort(left);
right=mergeSort(right);
merge(left,right,Input);
hope helped you!

One more variant:
private static <T extends Comparable<T>> List<T> mergeSort(List<T> unsortedList) {
if (unsortedList.size() <= 1) {
return unsortedList;
}
List<T> sortedList = new ArrayList<>(unsortedList.size());
List<T> leftList = mergeSort(unsortedList.subList(0, unsortedList.size() / 2));
List<T> rightList = mergeSort(unsortedList.subList(unsortedList.size() / 2, unsortedList.size()));
int leftIdx = 0;
int rightIdx = 0;
int resultIdx = 0;
while (leftIdx < leftList.size() && rightIdx < rightList.size()) {
if (leftList.get(leftIdx).compareTo(rightList.get(rightIdx)) <= 0) {
sortedList.add(resultIdx, leftList.get(leftIdx));
leftIdx++;
} else {
sortedList.add(resultIdx, rightList.get(rightIdx));
rightIdx++;
}
resultIdx++;
}
while (leftIdx < leftList.size()) {
sortedList.add(resultIdx, leftList.get(leftIdx));
leftIdx++;
resultIdx++;
}
while (rightIdx < rightList.size()) {
sortedList.add(resultIdx, rightList.get(rightIdx));
rightIdx++;
resultIdx++;
}
return sortedList;
}

import java.util.ArrayList;
import java.io.*;
import java.util.*;
public class Mergesort1 {
public static void main(String[] args) {
ArrayList<Integer> values = new ArrayList<Integer>();
int zeilen = 0;
try{
FileInputStream in = new FileInputStream(args[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = reader.readLine()) != null){
values.add(Integer.parseInt(line));
zeilen++;
}
try{
FileOutputStream out = new FileOutputStream(args[1]);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
sort(values); //sortien array list
for (int i=0; i<values.size(); i++){
writer.write("" + values.get(i));
writer.newLine();
}
writer.close();
}
catch(Exception e){
System.out.println(e);
}
}
catch(Exception e){
System.out.println(e);
}
}
public static ArrayList<Integer> sort( ArrayList<Integer> values)
{
if (values.size() ==1){
return values;
}
else {
int mid= values.size()/2;
ArrayList<Integer> left= new ArrayList<Integer>(mid);
ArrayList<Integer> right=new ArrayList<Integer>(values.size()-mid);
for (int i = 0; i < mid; i++) {
left.add(values.get(i));
}
for (int i = mid; i < values.size(); i++) {
right.add(values.get(i));
}
left=sort(left);
right=sort(right);
merge(left,right,values);
}
return values;
}
public static void merge (ArrayList<Integer>left,ArrayList<Integer>right,ArrayList<Integer>values)
{
int i1=0;// left Index
int i2=0;// right Index
int InputIndex=0;
for (int i = 0; i < values.size(); i++) {
if(i1==left.size()){
values.set(i, right.get(i2));
i2++;
}
else{
if (i2==right.size()){
values.set(i,left.get(i1));
i1++;
}
else{
if (left.get(i1)<=right.get(i2)) {
values.set(i,left.get(i1));
i1++;
}
else {
if (left.get(i1)>=right.get(i2)) {
values.set(i, right.get(i2));
i2++;
}
}
}
}
}
}
}

Related

BestSum memoization java

I have a function that receives a target and a numbers array, and the goal is to return the combination that uses less array numbers to achieve the target.
Example:
sum(8, [1,4,5]) should return [4,4]
sum(7, [5,3,4,7]) should return [7]`
sum(8, [2,3,5]) should return [3,5]
sum(100, [1,2,5,25]) should return [25, 25, 25, 25]
The function was working just fine before I attempted to do the memoization... Here is my code:
import java.util.ArrayList;
public class BestSum {
ArrayList<Integer> memoInt;
ArrayList<ArrayList<Integer>> memoList;
BestSum () {
memoList = new ArrayList<ArrayList<Integer>>();
memoInt = new ArrayList<Integer>();
}
public ArrayList<Integer> sum (int target, int nums[]) {
for(int i = 0; i < memoInt.size(); i++) {
if(memoInt.get(i) == target) {
return memoList.get(i);
}
}
if(target == 0) {
return new ArrayList<Integer>();
}
if(target < 0) {
return null;
}
ArrayList<Integer> shortestCombination = null;
for(int i = 0; i < nums.length; i++) {
int rest = target-nums[i];
ArrayList<Integer> currentCombination = sum(rest, nums);
if(currentCombination != null) {
currentCombination.add(nums[i]);
if(shortestCombination == null || currentCombination.size() < shortestCombination.size()){
shortestCombination = new ArrayList<Integer>();
shortestCombination = (ArrayList)currentCombination.clone();
}
}
}
memoInt.add(target);
memoList.add(shortestCombination);
return shortestCombination;
}
public static void main(String[] args) {
int target = 8;
int nums[] = {1,4,5};
BestSum bs = new BestSum();
System.out.println(bs.sum(target, nums).toString()); //[4,4]
}
}
However when I run this instead of [4,4], I get [4,1,4]... Any suggestions?
Ok So I fix the code :D
import java.util.ArrayList;
import java.util.*;
public class BestSum {
HashMap<Integer, ArrayList<Integer>> hp;
BestSum () {
hp = new HashMap<Integer, ArrayList<Integer>>();
}
public ArrayList<Integer> sum (int target, int nums[]) {
if(hp.containsKey(target)) {
return hp.get(target);
}
if(target == 0) {
return new ArrayList<Integer>();
}
if(target < 0) {
return null;
}
ArrayList<Integer> shortestCombination = null;
for(int i = 0; i < nums.length; i++) {
int rest = target-nums[i];
ArrayList<Integer> currentCombination = sum(rest, nums);
if(currentCombination != null) {
ArrayList<Integer> combination = new ArrayList<Integer>();
combination = (ArrayList)currentCombination.clone();
combination.add(nums[i]);
if(shortestCombination == null || combination.size() < shortestCombination.size()){
shortestCombination = new ArrayList<Integer>();
shortestCombination = (ArrayList)combination.clone();
}
}
}
hp.put(target, shortestCombination);
return shortestCombination;
}
public static void main(String[] args) {
int target = 8;
int nums[] = {1,4,5};
BestSum bs = new BestSum();
System.out.println(bs.sum(target, nums).toString()); //[4,4]
}
}
Tweaked the for loop a little,
for(int i = 0; i < nums.length; i++) {
int rest = target-nums[i];
ArrayList<Integer> currentCombination = sum(rest, nums);
if(currentCombination != null) {
ArrayList<Integer> tempCombination = new ArrayList<>(currentCombination);
tempCombination.add(nums[i]);
if(shortestCombination == null || tempCombination.size() < shortestCombination.size()){
shortestCombination = tempCombination;
}
}
}
It's an important step as the previous memory is being reassigned hence all the old values are pre-stored which caused the issue. I found out while debugging. Always a good idea to assign a new list while using recursion technique.

Recursion n over k Multi Thread (user input)

I tried to reprogramm this and fit it to my needs (calculating n^k with recursion). But something seems faulty, because I first got the txt files without any text in it; now after changing and trying to bugfix I get nothing at all :(
https://www.youtube.com/watch?v=br_TEuE8TbY
package Uebung3;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Hauptthread implements Runnable {
//int start;
//int stop;
boolean haupt=false;
String file;
static int n, k;
public Hauptthread(int startvalue, int stopvalue, String file, boolean h){
n= startvalue;
k=stopvalue;
this.file=file;
haupt=h;
}
public void run(){
ArrayList<Double> binominal=new ArrayList<>();
if (haupt=false) {
for (int i = n; i <= k; i++) {
binominal.add(binomial(n,k));
}
try{
PrintWriter print=new PrintWriter(new File(file));
for (int i = 0; i < binominal.size() ; i++) {
print.println("Test");
print.println(binominal.get(i));
}
}
catch(Exception e){
System.out.println("Error " + e.getMessage());
}
}
}
double binomial(int n, int k) {
if (k == 0) {
return 1; }
else {
return (((double)n/k) * binomial(n-1, k-1)); }
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
package Uebung3;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Uebung3 {
public static int threadcount=4;
public static int n, k;
public static int stop=k;
public static void main(String[] args) {
/*
int n = Integer.parseInt(JOptionPane.showInputDialog("n = "));
int k = Integer.parseInt(JOptionPane.showInputDialog("k = "));
if (n < 0 || k < 0 || k > n) {
JOptionPane.showMessageDialog(null, "Ungueltige Eingabe"); }
else {
JOptionPane.showMessageDialog(null, "Rechne" );
//JOptionPane.showMessageDialog(null, "n über k = " +binomial(n, k));
}
*/
System.out.println("Erstelle Threads...");
int erhoehe=20/threadcount;
int start=2;
ArrayList <Thread> threads = new ArrayList<>();
for (int i = 0; i < threadcount; i++) {
//if(!((i+1)==threadcount)){
if(start==10){
threads.add(new Thread(new Hauptthread(start, erhoehe, i+".txt",false)));
}
else {
threads.add(new Thread(new Hauptthread(start, erhoehe, i+".txt",true)));
}
}
for (int i = 0; i < threads.size(); i++) {
threads.get(i).start();
}
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (Exception e) {
System.out.println("Error" +e.getMessage());
}
}
}
}

Making a Program that Reads and Writes Data - Then Computes Min, Max, Average

I'm making a program that reads some data from a text file and then takes that data and finds the minimum, maximum, and average of the numbers. For some reason I'm getting a lot of ridiculous errors I've never seen before. Here is my code:
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
public class Lab1 {
static int count = 0;
static int[] newData2 = new int[count];
// Method for reading the data and putting it into different arrays
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
}
static int min(int[] newData2) {
int min = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] < min) {
min = newData2[i];
}
}
return min;
}
static int max(int[] newData2) {
int max = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] > max) {
max = newData2[i];
}
}
return max;
}
static double average(int[] newData2) {
double average = 0;
int sum = 0;
for (int i = 0; i < newData2.length; i++) {
sum = newData2[i];
}
average = sum / newData2.length;
return average;
}
/*
* static int stddev(int[] newData2) { int[] avgDif = new
* int[newData2.length]; for(int i = 0; i < newData2.length; i++) {
* avgDif[i] = (int) (average(newData2) - newData2[i]); }
*
* }
*/
void write(String newdata, int min, int max, double average, int stddev) {
try {
File file = new File("stats.txt");
file.createNewFile();
FileWriter writer = new FileWriter("stats.txt");
writer.write("Minimum: " + min + "Maximum: " + max + "Average: " + average);
writer.close();
}catch(Exception e) {
System.out.println("Unable to write to the file.");
}
public static void main(String[] args) {
}
}
}
I have an error in my readData method, and it tells me that:
This method must return a result type of int[].
I'm literally returning an int array so I don't understand what the problem here is.
Then in my main method it says void is an invalid type for the variable main.
Here are some pointers:
each exit point of a method returning something must return something, if the line new Scanner(f); throws an exception, the first return is not reached, so you need a default one, like this:
private int[] readData() {
File f = new File("data.txt");
int count = 0;
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt(); // maybe you should handle the case where your input is too large for the array "newData"
}
return Arrays.copyOf(newData, count);
} catch (Exception e) {
System.out.println("Could not read the file.");
}
return null;
}
To reduce the size of an array, you should use Arrays.copyOf (see below)
You should avoid static fields (and in your case none are required)
Your method min and max are assuming there are elements in the array (at least one), you should not do that (or test it with an if):
private int min(int[] data) {
int min = Integer.MAX_VALUE; // handy constant :)
for (int i = 0; i < data.length; i++) {
if (data[i] < min) {
min = data[i];
}
}
return min;
}
private int max(int[] data) {
int max = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
In your average method there are a few mistakes:
private double average(int[] data) {
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i]; // here if you want a sum it's += not =
}
return (1.0 * sum) / data.length; // you want a double division, local "average" was useless
}
arrays are iterables so you can use "new style" for loops:
for (int value : newData) {
// use value
}
Some reading:
Java Integer division: How do you produce a double?
“Missing return statement” within if / for / while
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
//TODO: return something here if there is some kind of error
}
Because of the try-catch block you need to account for every possibility that could occur. When you return the array when the program succeeds you are expecting a return, but when there is an exception the program still expects a return value, but you did not provide one.

Creating a new array element copies to the array index below it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
When I create a new array element, it gets stored into the array index, then the array index increments to the next.
However, I am getting a different result. The array element copies down to all previous array indexes.
import java.util.Scanner;
import java.io.*;
public class VectorOfContacts implements ProjTwo
{
private int size;
private int capacity;
private int incrementCapacity;
Contact[] contacts;
File file = new File("contacts.txt");
Scanner input = new Scanner(System.in);
public VectorOfContacts()
{
size = 0;
capacity = 10;
incrementCapacity = capacity;
contacts = new Contact[capacity];
}
public int getSize()
{
return size;
}
public int getCapacity()
{
return capacity;
}
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
//public VectorOfContacts(int inCapacity)
//{
//inCapacity = 100;
//incrementCapacity = inCapacity;
//}
public void readInitialFromFile()
{
Contact c = new Contact();
String temp = null;
try{
Scanner input = new Scanner(file);
for (int i = 0 ; i < size; i++)
{
temp = input.nextLine();
String[] part = input.nextLine().split(":");
System.out.println(part);
String name = part[0];
long number = Long.parseLong(part[1]);
String comment = part[2];
c.setName(name);
c.setPhoneNumber(number);
c.setComment(comment);
contacts[i] = c;
contacts[size] = contacts[i];
}
input.close();
}catch(FileNotFoundException e){
System.out.println("File not found.");
System.exit(0);
}
}
public void writeFinalToFile()
{
try{
PrintWriter output = new PrintWriter(file);
for (int i = 0; i < size; i++)
{
output.println(contacts[i]);
}
output.close();
}catch(FileNotFoundException a){
System.out.println("Something is wrong.");
System.exit(0);
}
System.exit(0);
}
public void addContact(Contact c)
{
addElement(c);
}
public void deleteContact(String nm)
{
System.out.println("Delete which name?");
nm = input.nextLine();
for(int i = 0; i < size; i++)
{
if(contacts[i].getName() == nm);
{
contacts[i] = contacts[i+1];
}
}
System.out.println("Deletion confirmed");
}
public void showByName(String nm)
{
nm = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (nm.startsWith(contacts[i].getName()))
{
System.out.println(contacts[i]);
}
}
}
public void showByPhoneNumber(long pN)
{
pN = input.nextLong();
for ( int i = 0; i < size; i++)
{
if (contacts[i].getPhoneNumber() == pN)
{
System.out.println(contacts[i]);
}
}
}
public void showByComment(String c)
{
c = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (c.startsWith(contacts[i].getComment()))
{
System.out.println(contacts[i]);
}
}
}
public boolean isFull()
{
if (size == capacity)
{
return true;
}
else
{
return false;
}
}
public boolean isEmpty()
{
if (size == 0)
return true;
else
return false;
}
public void addElement(Contact item)
{
if (isFull() == true)
incrementCapacity();
contacts[size] = item;
size++;
System.out.println("size" + size);
for (int i = 0; i < size; i++)
{
System.out.println(contacts[i]);
}
}
public void incrementCapacity()
{
Contact[] temp_contacts = new Contact[capacity + incrementCapacity];
for(int i = 0; i < size; i++)
{
temp_contacts[i] = contacts[i];
}
capacity = capacity + incrementCapacity;
contacts = temp_contacts;
}
}
These are the end results
size1
test:1234:1
size2
no:5555:2
no:5555:2
size3
jaja:1666:test
jaja:1666:test
jaja:1666:test
You print one object for all indexes, you need to use next:
for (int i = 0; i < size; i++){
System.out.println(contacts[i]);
}
You could improve a lof of things.
Don't expose everything as public
The class VectorOfContacts does a lot of things. You should split it into many classes.
Use the Java Framework (Array.copy(), ArrayList, ...)
Don't do if (true) return true else return false
Write tests
In readInitialFromFile you're creating the contact outside of the loop. So you reusing the same object of all contacts.
Those setters dont do anything, you missing an argument. But they shouldn't be public anyway so you don't need them.
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
isFull and isEmpty shouldn't be public and can be a lot shorter
private boolean isFull() {
return size == capacity;
}
private boolean isEmpty() {
return size == 0;
}
Please clean up your code first.

recursive method not properly executing

I have a programming assignment for an introductory level Java class (the subset sum problem) - for some reason, my recursive method isn't executing properly (it just goes straight to the end of the method and prints out the sorted list). Any help would be appreciated - I'm a newbie and recursive functions are really confusing to me.
package programmingassignment3;
import java.io.*;
import java.util.*;
public class ProgrammingAssignment3 {
static int TARGET = 10;
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
public static void main(String[] args) {
populateSortSet();
sumInt(list);
recursiveSS(list);
}//main
public static void populateSortSet() {
try {
File f = new File("set0.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !list.contains(ele)) {
list.add(ele);
}//if
}//while
Collections.sort(list);
}//try
catch (IOException e) {
e.printStackTrace();
}//catch
}//populateSet
public static void recursiveSS(ArrayList<Integer> Alist) {
if (Alist.size() == SIZE) {
if (sumInt(Alist) == TARGET) {
System.out.println("The integers that equal " + TARGET + "are: " + Alist);
} //if==TARGET
}//if==SIZE
else {
for (int i = 0; i < SIZE; i++) {
ArrayList<Integer> list1 = new ArrayList<>(Alist);
ArrayList<Integer> list0 = new ArrayList<>(Alist);
list1.add(1);
list0.add(0);
if (sumInt(list0) < TARGET) {
recursiveSS(list0);
}//if
if (sumInt(list1) < TARGET) {
recursiveSS(list1);
}//if
}//for
}//else
System.out.println("echo" + Alist);
}//recursiveSS
public static int sumInt(ArrayList<Integer> Alist) {
int sum = 0;
for (int i = 0; i < SIZE - 1; i++) {
sum += Alist.get(i);
}//for
if (Alist.size() == TARGET) {
sum += Alist.get(Alist.size() - 1);
}//if
return sum;
}//sumInt
}//class
This thing that you do at class level:
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
means that SIZE will be initiated to 0, and stay 0 (even if you add elements to the list.)
This means that the code inside the for-loop will be executed 0 times.
Try something like:
public class ProgrammingAssignment3 {
private static int initialSize;
//...
public static void populateSortSet() {
//populate the list
initialSize = list.size();
}
So you don't set the value of the size variable until the list is actually populated.
That being said, there a quite a few other strange things in your code, so I think you need to specify exactly what you are trying to solve here.
Here's how I'd do it. I hope it clarifies the stopping condition and the recursion. As you can see, static methods are not an issue:
import java.util.ArrayList;
import java.util.List;
/**
* Demo of recursion
* User: mduffy
* Date: 10/3/2014
* Time: 10:56 AM
* #link http://stackoverflow.com/questions/26179574/recursive-method-not-properly-executing?noredirect=1#comment41047653_26179574
*/
public class RecursionDemo {
public static void main(String[] args) {
List<Integer> values = new ArrayList<Integer>();
for (String arg : args) {
values.add(Integer.valueOf(arg));
}
System.out.println(String.format("input values : %s", values));
System.out.println(String.format("iterative sum: %d", getSumUsingIteration(values)));
System.out.println(String.format("recursive sum: %d", getSumUsingRecursion(values)));
}
public static int getSumUsingIteration(List<Integer> values) {
int sum = 0;
if (values != null) {
for (int value : values) {
sum += value;
}
}
return sum;
}
public static int getSumUsingRecursion(List<Integer> values) {
if ((values == null) || (values.size() == 0)) {
return 0;
} else {
if (values.size() == 1) { // This is the stopping condition
return values.get(0);
} else {
return values.get(0) + getSumUsingRecursion(values.subList(1, values.size())); // Here is recursion
}
}
}
}
Here is the case I used to test it:
input values : [1, 2, 3, 4, 5, 6]
iterative sum: 21
recursive sum: 21
Process finished with exit code 0
Thanks everyone. I really appreciate the help. I did figure out the problem and the solution is as follows (closing brace comments removed for the reading pleasure of #duffymo ):
public class ProgrammingAssignment3 {
static int TARGET = 6233;
static ArrayList<Integer> set = new ArrayList<>();
static int SIZE;
static int count = 0;
public static void populateSortSet() {
try {
File f = new File("set3.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !set.contains(ele)) {
set.add(ele);
}
}
Collections.sort(set);
SIZE = set.size();
System.out.println("The original sorted set: " + set + "\t subset sum = " + TARGET);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void recursiveSS(ArrayList<Integer> list) {
if (list.size() == SIZE) {
if (sumInt(list) == TARGET) {
System.out.print("The Bit subset is: " + list + "\t");
System.out.println("The subset is: " + getSubset(list));
count++;
}
}
else {
ArrayList<Integer> list1 = new ArrayList<>(list);//instantiate list1
ArrayList<Integer> list0 = new ArrayList<>(list);//instantiate list0
list1.add(1);
list0.add(0);
if (sumInt(list0) <= TARGET) {
recursiveSS(list0);
}
if (sumInt(list1) <= TARGET) {
recursiveSS(list1);
}
}
}
public static int sumInt(ArrayList<Integer> list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
sum += set.get(i);
}
}
return sum;
}
public static ArrayList<Integer> getSubset(ArrayList<Integer> list) {
ArrayList<Integer> l = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
l.add(set.get(i));
}
}
return l;
}
}

Categories