Skip to content

Instantly share code, notes, and snippets.

@edolopez
Created February 18, 2014 14:54
Show Gist options
  • Save edolopez/9072456 to your computer and use it in GitHub Desktop.
Save edolopez/9072456 to your computer and use it in GitHub Desktop.
This is a possible way to answer the methods for the Partial 1 in CS II class.
public class Partial1CSII {
public static void main(String[] args) {
// Calling exercise II
System.out.println(lowest(4,3,-45));
// Calling exercise III
int[] numbers = new int[]{4, 20, 35, 4, 6};
System.out.println(diff(numbers));
// Calling exercise IV
int[][] matrix = new int[][]{{1,2,3},{1,2,3},{1,2,3}};
int[] sums = new int[matrix[0].length];
sums = allColsSums(matrix);
for (int i = 0; i < sums.length; i++) {
System.out.println(sums[i]);
}
}
/*
* Exercise II, Partial 1 - CS II
* Method that receives 3 integers and returns the lowest among them.
*
* This method considers if numbers are the same, controlled in the conditionals
* with the '<=' statement.
*/
public static int lowest(int a, int b, int c) {
int lowest = a;
if (a <= b && a <= c)
lowest = a;
else if (b <= a && b <= c)
lowest = b;
else if (c <= a && c <= b)
lowest = c;
return lowest;
}
/*
* Exercise III, Partial 1 - CS II
* Method that receives an int array and returns the difference between the largest and
* the smallest number within the array.
*
* This method has been simplified in only 1 loop to inspect only one time for
* the largest and the smallest.
*/
public static int diff(int[] array) {
int largest = array[0], smallest = array[0];
for (int i = 0; i < array.length; i++) {
if (smallest > array[i])
smallest = array[i];
if (largest < array[i])
largest = array[i];
}
return largest - smallest;
}
/*
* Exercise IV, Partial 1 - CS II
* Method that receives an int 2D array and returns the sum of every column
* in an array format.
*
* The sum of column 0, will be stored in index 0 on the returned array and so forth for
* the other sums.
*/
public static int[] allColsSums(int[][] a) {
int[] array = new int[a[0].length];
int sum = 0;
for (int col = 0; col < a[0].length; col++) {
for (int row = 0; row < a.length; row++) {
sum += a[row][col];
}
array[col] = sum;
sum = 0;
}
return array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment