List Addition does not work the way it should

Viewed 23

I am trying to create the subsets of the given array {1,2,3,4,5} in an iterative way. hence, I am using this code:

import java.util.ArrayList;
import java.util.Scanner;

public class Subsets {
public static void main(String[] args) {
    int [] weights = new int[] {1,2,3,4,5};
    ArrayList<ArrayList<Integer>> subsets = new ArrayList<>();
    subsets.add(new ArrayList<>());

    for(int i =0; i<weights.length;i++){
        System.out.println("New loop");
        ArrayList<ArrayList<Integer>> temp;
        System.out.println("in subsets");
        for(int k = 0;k<subsets.size();k++)
        {
            System.out.println(subsets.get(k));
        }
        temp = subsets;
        for(int j=0;j<temp.size();j++){
            System.out.println("dsdf"+ temp.get(j));
            (temp.get(j)).add(weights[i]);
            //subsets.add(temp.get(j));
            System.out.println("After adding:" + temp.get(j));
        }
        System.out.println("In temp");
        for(ArrayList<Integer> a: temp){
            System.out.println(a);

        }
        subsets.addAll(temp);

I start with subset = [] for each element in array: I do temp = subset //[] do another loop with j till the size of temp = 1 Addarray[i] to temp[j] == [[1]] add this temp to subset = [[],[1]]instead my subset becomes = [[1],[1]] Also in another run for i = array[1] = 2 temp should traverse each element of subset; so add arra[i] to each element of temp making it [1], [1,2], instead it is [1,2,2],[1,2,2] changing the entire temp in one insertion

Can anyone tell me where am I wrong"

Thank you

1 Answers

From what I understand you want to create two dim array from the main array, for example the expected output should like this

[0] -> [1]
[1] -> [1,2]
[2] -> [1,2,3]

and so on, to achieve this please check the code below

public static void main(String[] args) {
    int [] weights = new int[] {1,2,3,4,5};
    ArrayList<ArrayList<Integer>> subsets = new ArrayList<>();
    
    for(int i =0; i<weights.length;i++){
        ArrayList<Integer> temp = new ArrayList<>();
        for(int j = 0 ; j <= i;j++){
            temp.add(weights[j]);
        }
        subsets.add(temp);
    }
    
    // Print
    for (ArrayList<Integer> arr : subsets) {
        System.out.println(Arrays.toString(new ArrayList[]{arr}));
    }
}

Please don't forget to thumb up if this answer your question

Related