1

I am trying to split a list of integers into 2 lists of approximately equal length if my main list can't be evenly divided

My code so far is covering the "even split":

@Override
public Set<Bin> pack(int capacity, List<Integer> values) {
    /**
     * Divide the list into 2 equal parts if it can be Divided evenly
     * Else, divide the List into 2 parts of roughly the same length
     */
    int temp =values.size();
    if(temp % 2 == 0)
    {
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();

        for(int i = 0; i < temp / 2;i++)
        {
            list1.add(i);
        }
        for(int i = temp / 2; i < values.size();i++)
        {
            list1.add(i);
        }
    }else //divide the list into 2 approximately equal parts
    {


    }
    return null;
}

How do I implement the rest of this method?

javatarz
  • 1,174
  • 16
  • 30
Lore
  • 17
  • 5
  • If your requirement is just that the list must be split in two "approximately" equal parts, there's no reason to not do the exact same thing as in the even case. Note that List has a subList method. – JB Nizet Nov 10 '18 at 13:53
  • If you no longer use the original list after this operation, you may wish to consider using `List#subList(from, to)` to create a *view* on the original list, rather than a new list entirely. – MTCoster Nov 10 '18 at 13:55
  • 2
    what's with the return type `Set`? and I hope you're aware that you're adding indices and not the values in the input `List` in your even size case as well... and that `capacity` variable is unused. – Naman Nov 10 '18 at 13:59

2 Answers2

2

You may do it like so,

List<Integer> firstHalf = values.subList(0, values.size()/2);
List<Integer> secondHalf = values.subList(values.size()/2, values.size());
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
0

If you only need a view of the 2 parts of the initial List you can use List.subList(), but remember that this you made any change on the initial list, they will be seen on list1 and list2 as they are only views :

int middle = values.size() / 2;
List<Integer> list1 = values.subList(0, middle);
List<Integer> list2 = values.subList(middle, values.size());

To make news List with the same elements, you need to :

int middle = values.size() / 2;
List<Integer> list1 = new ArrayList<>(values.subList(0, middle));
List<Integer> list2 = new ArrayList<>(values.subList(middle, values.size()));
azro
  • 53,056
  • 7
  • 34
  • 70
  • 3
    how is this different [from an existing answer](https://stackoverflow.com/a/53239668/1746118) ? – Naman Nov 10 '18 at 14:03
  • @nullpointer hum really ? First know that lot of posts have answer talking about the same just because they answers the same question / Second notice I pointed out a warning for a use of subList ;) – azro Nov 10 '18 at 14:08