-
Notifications
You must be signed in to change notification settings - Fork 0
/
UNIT 8
15 lines (8 loc) · 2.54 KB
/
UNIT 8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//8.1.1
public class U8_L1_Activity_One{public static int diagSum(int[][] arr){int sum=0;for(int i=0;i<arr.length;i++){for(int j=0;j<arr[i].length;j++){if(j==i){sum+=arr[i][j];}}}return sum;}}
//8.1.2
public class U8_L1_Activity_Two{public static int[][] multTable(int height,int width){int[][] table=new int[height][width];for(int i=0;i<height;i++){for(int j=0;j<width;j++){table[i][j]=i*j;}}return table;}}
//8.2
public class TemperatureMonth{private double[][] temperatures;public TemperatureMonth(double[][] t){temperatures=t;}public double getMaxTemp(){double max=-200000000;for(double[] row:temperatures){for(double cell:row){if(cell>max){max=cell;}}}return max;}public double getMinTemp(){double lowest=Double.MAX_VALUE;for(double[] row:temperatures){for(double cell:row){if(cell<lowest){lowest=cell;}}}return lowest;}public double getMonthlyAverage(){double sum=0;for(double[] row:temperatures){for(double cell:row){sum+=cell;}}return sum/(temperatures.length*temperatures[0].length);}public double[] getWeeklyAverages(){double[] averages=new double[temperatures.length];double sum=0;for(int i=0;i<temperatures.length;i++){sum=0;for(int j=0;j<temperatures[i].length;j++){sum+=temperatures[i][j];}averages[i]=sum/(temperatures[i].length);}return averages;}}
//Battleship
import java.util.ArrayList;public class Board{private String[][] squares;private ArrayList<Integer> lengths=new ArrayList<Integer>();public Board(){squares=new String[10][10];for(int i=0;i<10;i++){for(int j=0;j<10;j++){squares[i][j]="-";}}}public String toString(){String board="";for(String[] row:squares){for(String cell:row){board+=cell+" ";}board+="\n";}return board;}public boolean addShip(int row,int col,int len,boolean horizontal){if(row<0||col<0||len<=0||row>9||col>9){return false;}if(horizontal&&col+len-1>9){return false;}if(!horizontal&&row+len-1>9){return false;}if(horizontal){for(int i=0;i<len;i++){if(squares[row][col+i].equals("b")){return false;}}for(int i=0;i<len;i++){squares[row][col+i]="b";lengths.add(len);}}else{for(int i=0;i<len;i++){if(squares[row+i][col].equals("b")){return false;}}for(int i=0;i<len;i++){squares[row+i][col]="b";lengths.add(len);}}return true;}public boolean foundShip(int len){return lengths.contains(len);}public int shoot(int row,int col){if(row>9||row<0||col>9||col<0){return -1;}else if(squares[row][col].equals("-")){squares[row][col]="m";return 0;}else if(squares[row][col].equals("b")){squares[row][col]="x";return 1;}else{return 2;}}public boolean gameOver(){for(String[] row:squares){for(String cell:row){if(cell.equals("b")){return false;}}}return true;}}