Zubair
Zubair

Reputation: 726

How to store and change values for 2D lists?

I have a function that would sum up the rows of an array and have it displayed in one column at the beginning/end. It was initially done with a 2D array(int[][]) and it works fine. I would now like to change the input to 2D lists(List<List<Integer>>) instead of arrays. This is the function that uses int[][] that currently works:

public static void sumLeft(int[][] numbers) {
    for (int i = 0; i < numbers.length; i++) {
        for (int j = 1; j < numbers[i].length; j++) {
            numbers[i][0] += numbers[i][j];
            numbers[i][j] = 0;
        }
    }
}

So if I take in this array:

10  15  30  40  
15  5   8   2   
20  2   4   2   
1   4   5   0

This would be the result:

95  0   0   0   
30  0   0   0   
28  0   0   0   
10  0   0   0

Now I want to do the same thing, but with 2D lists, or List<List<Integer>>.

This is what I currently have:

public static void listLeft(List<List<Integer>> list) {
    int sum = 0;
    for (int i = 0; i < list.size(); i++) {
        List<Integer> innerList = list.get(i);
        for (int j = 0; j < list.get(i).size(); j++) {
            sum += list.get(i).get(j);
            innerList.set(0, sum);
            innerList.set(j, 0);
        }
    }
}

If I take in the same set of numbers, it would output this:

95  0   0   0   
125 0   0   0   
153 0   0   0   
163 0   0   0

*Notice that rows 2-4 have the wrong values.

Upvotes: 0

Views: 474

Answers (1)

stackoverflowuser2010
stackoverflowuser2010

Reputation: 40889

Move sum into the for loop that spans the lists. Also, you don't need to set the first list item to sum with every item in the list; you can set it once at the end.

public static void listLeft(List<List<Integer>> list) {

    for (int i = 0; i < list.size(); i++) {
        int sum = 0;
        List<Integer> innerList = list.get(i);
        for (int j = 0; j < list.get(i).size(); j++) {

            sum += list.get(i).get(j);
            innerList.set(j, 0);
        }
        innerList.set(0, sum);
    }
}

Upvotes: 2

Related Questions