Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Write a method: public static int columnSum(int[][] a, int x) that returns th

ID: 3858038 • Letter: 1

Question

1. Write a method:

public static int columnSum(int[][] a, int x)
that returns the sum of the elements in Column x of a (careful with rows of different lengths!).

2. Write a method:

public static int[] allRowSums(int[][] a)
that calculates the row sum for every row and returns each of the values in an array.

3. Write a method change2 that changes the order of values in an ArrayList of Strings in a pairwise fashion.
Your method will change the order of the first two values, then change the order of the next two values, etc. You can assume the arrayList will always have data and its size will always be even.

Example: if the ArrayList had the following values
{"120", "130", "210", "330", "490", "491"}
then after running your method, the ArrayList values will be
{"130", "120", "330", "210", "491", "490"}


public void change2 (ArrayList<String> x) {

}

Explanation / Answer


// Array2D.java

import java.util.ArrayList;
import java.util.Arrays;
public class Array2D
{

public static int columnSum(int[][] array, int x){
int sum = 0;
for(int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length ; j++)
{
if(j == x)
sum = sum + array[i][j];
}
}
return sum;
}

public static int[] allRowSums(int[][] array){
int[] rowSum = new int[array.length];
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j< array[i].length; j++)
{

rowSum[i]= rowSum[i]+array[i][j];
}
}
return rowSum;
}

public static void change2(ArrayList<Integer> list)
{   
for (int i = 0; i < list.size() ;i=i+2)
{
int t = list.get(i);
list.set(i,list.get(i+1));
list.set(i+1, t);
}

}
public static void main(String[] args)
{
// TODO Auto-generated method stub
int[][] array = new int[][] { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
  
System.out.println(Arrays.toString(allRowSums(array)));
//output: [10, 26, 42]   
  
System.out.println(columnSum(array,1));
// output: 18

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);

System.out.print("Original List: ");
for (Integer number : list)
{
System.out.print(" " + number);
}

change2(list);

System.out.print(" Updated List: ");
for (Integer number : list)
{
System.out.print(" " + number);
}

// output:

// Original List: 1 2 3 4 5 6
// Updated List: 2 1 4 3 6 5
  
}

}