Solution - Battleship Field Validator
unknown
java
14 days ago
3.3 kB
2
Indexable
Never
import java.util.Arrays; public class BattleField { public static boolean fieldValidator(int[][] field) { int [][]grid = new int[12][12]; for(int i =0;i<field.length;i++){ for(int j=0;j<field[0].length;j++){ grid[i+1][j+1] = field[i][j]; } } //System.out.println(Arrays.deepToString(grid).replace("], ", "]\n").replace("[[", "[").replace("]]", "]")); int shipCount = 0; int xx,yy; int arr[] = {0,0,0,0,0}; for(int y=1;y<11;y++){ // Traversing 2D Array for(int x=1;x<11;x++){ // Traversing 2D Array if(grid[y][x]==1){ // Checking each cell if its equal to 1 if(grid[y][x+1]==1){ // Checking if the ship is horizontal shipCount++; if(grid[y+1][x-1]==1||grid[y+1][x]==1||grid[y+1][x+1]==1){ //Checking if the border below horizontal ship return false; //returns false when border is occupied }//if(grid[y+1][x-1]==1||grid[y+1][x]==1) xx = x + 1; while(grid[y][xx]==1){ //while the horizontal ship continues if(grid[y+1][xx+1]==1){ return false; }//if(grid[y+1][xx+1]==1) xx+=1; shipCount++; }//while(grid[y][xx]==1 if(shipCount>4){ return false; }//if(shipCount>4) if(shipCount>1){ arr[shipCount]++; x = xx; shipCount = 0; continue; }//if(shipCount>1) }//if(grid[y][x+1]==1) if(grid[y+1][x]==1){ // Checking if the ship is vertical shipCount++; if(grid[y+1][x-1]==1||grid[y+1][x+1]==1){ //Checking if the border below vertical ship return false; //returns false when border is occupied }//if(grid[y+1][x-1]==1||grid[y+1][x+1]==1) yy = y + 1; while(grid[yy][x]==1){ //while the vertical ship continues if(grid[yy+1][x+1]==1||grid[yy+1][x-1]==1){ return false; }//if(grid[yy+1][x+1]==1||grid[yy+1][x-1]==1) grid[yy][x]=2; yy+=1; shipCount++; }//while(grid[y][xx]==1 if(shipCount>4){ return false; }//if(shipCount>4) if(shipCount>1){ arr[shipCount]++; shipCount = 0; continue; }//if(shipCount>1) }//if(grid[y][x+1]==1) arr[shipCount+1]++; continue; }//if(grid[y][x]==1) }//for(int x=1;x<11;x++) }//for(int y=1;y<11;y++) System.out.println(Arrays.toString(arr)); System.out.println(Arrays.deepToString(grid).replace("], ", "]\n").replace("[[", "[").replace("]]", "]")); if(arr[1]==4&&arr[2]==3&&arr[3]==2&&arr[4]==1){ return true; } return false; }//public static boolean fieldValidator(int[][] field) }//public class BattleField
Leave a Comment