Refactor this code by leaving the names of methods, variables and classes the same,…
- User
Refactor this code by leaving the names of methods, variables and classes the same, without adding or deleting existing methods, variables and classes, making the code different according to the following rules:
- Replace the use of imported library methods with alternative code that performs the same function
- If possible, rearrange the order of execution of functions, loops, and conditions so that they do not affect the result of execution
- if it is possible to import a new library and shorten long methods by using a library method, use it
- use alternative ways of storing data
- Group ungrouped data
- If data is grouped in this code, then distribute it throughout the code, ungroup it
- Identify standard algorithms and if possible use similar algorithm without performance loss. For example, replace bubble sorting with quick sorting
- If possible, ignore encapsulation by implementing the method inside the executable class rather than in another class
- Use encapsulation if it has been implemented for a method inside a class or interface when you can move it to another class
- Remove type generalization by making type specialization
- For implemented specialized types, do type generalization
- Instead of pull up and push down, implement methods locally in the class
- Use pull up and push down instead of already implemented local use of methods
- Remove overloading and polymorphism, rewrite methods without using these paradigms
- If possible, use overloading and polymorphism if it is possible but not implemented in the code
import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.ArrayList; import java.util.List; import java.lang.Math; public class Main { private static BufferedWriter writer; private static BufferedReader reader; private static InvalidBoardSizeException invBoardSize = new InvalidBoardSizeException(); private static InvalidNumberOfInsectsException invNumIns = new InvalidNumberOfInsectsException(); private static InvalidNumberOfFoodPointsException invNumFoodPts = new InvalidNumberOfFoodPointsException(); private static InvalidInsectColorException invInsClr = new InvalidInsectColorException(); private static InvalidInsectTypeException invInsType = new InvalidInsectTypeException(); private static InvalidEntityPositionException invInsPos = new InvalidEntityPositionException(); private static DuplicateInsectException dupIns = new DuplicateInsectException(); private static TwoEntitiesOnSamePositionException twoEntSamePos = new TwoEntitiesOnSamePositionException(); private static ArrayList<Insect> insects = new ArrayList<>(); private static Board gameBoard; public static void endProgramm(String exception) { try { writer.write(exception); writer.close(); reader.close(); System.exit(0); } catch (IOException e) { throw new RuntimeException(); } System.exit(0); } public static void main(String[] args) { try { reader = new BufferedReader(new FileReader("input.txt")); writer = new BufferedWriter(new FileWriter("output.txt")); // Scanner scanner = new Scanner(new File("input.txt")); // String boardSizeString = reader.readLine(); // int boardSize = Integer.parseInt(boardSizeString); // int lowerBoardBound = 4; // int upperBoardBound = 1000; // if (!(boardSize >= lowerBoardBound && boardSize <= upperBoardBound)) { // endProgramm(invBoardSize.getMessage()); // } // int numInsects = scanner.nextInt(); // int lowerInsBound = 1; // int upperInsBound = 16; // if (!(numberOfInsects >= lowerInsBound && numberOfInsects <= upperInsBound)) { // endProgramm(invNumIns.getMessage()); //kaif // } // int numFoodPoints = reader.readLine(); String boardSizeString = reader.readLine(); int boardSize = Integer.parseInt(boardSizeString); int lowerBoardBound = 4; int upperBoardBound = 1000; if (!(boardSize >= lowerBoardBound && boardSize <= upperBoardBound)) { endProgramm(invBoardSize.getMessage()); } String numberOfInsectsString = reader.readLine(); int numInsects = Integer.parseInt(numberOfInsectsString); int lowerInsBound = 1; int upperInsBound = 16; if (!(numInsects >= lowerInsBound && numInsects <= upperInsBound)) { endProgramm(invNumIns.getMessage()); } String numberOfFoodPointsString = reader.readLine(); int numFoodPoints = Integer.parseInt(numberOfFoodPointsString); int lowerFoodPointBound = 1; int upperFoodPointBound = 200; if (!(numFoodPoints >= lowerFoodPointBound && numFoodPoints <= upperFoodPointBound)) { endProgramm(invNumFoodPts.getMessage()); } gameBoard = new Board(boardSize); for (int i = 0; i < numInsects; i++) { String input = reader.readLine(); Scanner scanner = new Scanner(input); String colorStr = scanner.next(); if (!(colorStr.equals("Red") || colorStr.equals("Green") || colorStr.equals("Blue") || colorStr.equals("Yellow"))) { endProgramm(invInsClr.getMessage()); } String typeStr = scanner.next(); if (!(typeStr.equals("Butterfly") || typeStr.equals("Ant") || typeStr.equals("Spider") || typeStr.equals("Grasshopper"))) { endProgramm(invInsType.getMessage()); } int X = scanner.nextInt(); int Y = scanner.nextInt(); InsectColor color = InsectColor.valueOf(colorStr.toUpperCase()); InsectType type = InsectType.valueOf(typeStr.toUpperCase()); try { gameBoard.addEntity(createInsect(color, type, X, Y)); } catch (DuplicateInsectException e) { System.out.println("Duplicate insects"); System.exit(0); return; } catch (InvalidEntityPositionException e) { System.out.println("Invalid entity position"); System.exit(0); return; } } for (int i = 0; i < numFoodPoints; i++) { int foodAmount = scanner.nextInt(); int X = scanner.nextInt(); int Y = scanner.nextInt(); try { gameBoard.addEntity(new FoodPoint(new EntityPosition(X, Y), foodAmount)); } catch (InvalidEntityPositionException e) { System.out.println("Invalid entity position"); System.exit(0); return; } } simulateGame(); } catch (FileNotFoundException e) { System.out.println("Input file not found"); } } private static void simulateGame() { List<Insect> insects = gameBoard.getInsects(); for (Insect insect : insects) { try { int foodEaten = insect.getBestDirection(gameBoard.getBoardData(), gameBoard.getSize()); System.out.println(insect.getColor() + " " + insect.getType() + " " + insect.getDirection().textRepresentation() + " " + foodEaten); } catch (Exception e) { System.out.println(e.getMessage()); return; } } } private void createInsect(InsectColor color, InsectType type, int X, int Y) throws DuplicateInsectException, InvalidEntityPositionException { Insect insect; switch (type.toString().toUpperCase()) { case "ANT": insect = new Ant(new EntityPosition(X, Y), color); addEntity(insect); // InsectType tp = InsectType.ANT; // Insect.setType(tp); break; case "BUTTERFLY": insect = new Butterfly(new EntityPosition(X, Y), color); addEntity(insect); // InsectType tp = InsectType.BUTTERFLY; // Insect.setType(tp); break; case "SPIDER": insect = new Spider(new EntityPosition(X, Y), color); addEntity(insect); // InsectType tp = InsectType.SPIDER; // Insect.setType(tp); break; case "GRASSHOPPER": insect = new Grasshopper(new EntityPosition(X, Y), color); addEntity(insect); // InsectType tp = InsectType.GRASSHOPPER; // Insect.setType(tp); break; default: throw new IllegalStateException("Unexpected value: " + type);//change for bad names and for repeating entity+color } gameBoard.addEntity(insect); return insect; } } class Board { private Map<String, BoardEntity> boardData; private int size; public Board(int boardSize) { this.size = boardSize; this.boardData = new HashMap<>(); } public void addEntity(BoardEntity entity) throws DuplicateInsectException, InvalidEntityPositionException { if (boardData.containsKey(entity.getEntityPosition().toString())) { throw new DuplicateInsectException(); } EntityPosition position = entity.getEntityPosition(); if (position.X < 1 || position.X > size || position.Y < 1 || position.Y > size) { throw new InvalidEntityPositionException(); } boardData.put(position.toString(), entity); } public BoardEntity getEntity(EntityPosition position) { return boardData.get(position.toString()); } public List<Insect> getInsects() { List<Insect> insects = new ArrayList<>(); for (BoardEntity entity : boardData.values()) { if (entity instanceof Insect) { insects.add((Insect) entity); } } return insects; } public int getDirection(Insect insect){ throw new UnsupportedOperationException("Method not implemented yet"); return 0; } public int getDirectionSum(Insect insect){ throw new UnsupportedOperationException("Method not implemented yet"); return 0; } public Map<String, BoardEntity> getBoardData(){ return this.boardData; } public int getSize(){ return this.size; } } enum InsectType { ANT, BUTTERFLY, SPIDER, GRASSHOPPER } class EntityPosition { int X; int Y; protected EntityPosition entityPosition; public EntityPosition(int X, int Y) { this.X = X; this.Y = Y; } @Override public String toString() { return "(" + X + "," + Y + ")"; } } class BoardEntity { private EntityPosition position; public BoardEntity(EntityPosition position) { this.position = position; } public EntityPosition getEntityPosition() { return position; } } class Insect extends BoardEntity { private InsectColor color; private InsectType type; public Insect(EntityPosition position, InsectColor color) { super(position); this.color = color; } public InsectColor getColor() { return color; } public int getBestDirection(Map<String, BoardEntity> boardData, int size) throws Exception { throw new UnsupportedOperationException("Method not implemented yet"); return 0; } public Direction travelDirection(Direction dir, Map<String, BoardEntity> boardData, int boardSize) { throw new UnsupportedOperationException("Method not implemented yet"); return 0; } public InsectType getType(){ return this.type; } public void setType(InsectType type){ this.type = type; } } class Ant extends Insect implements OrthogonalMoving, DiagonalMoving { public Ant(EntityPosition position, InsectColor color) { super(position, color); } @Override public Direction getBestDirection(Map<String, BoardEntity> boardData, int boardSize) { EntityPosition position = getEntityPosition(); int verticalDownFoodAmount = 0; int x = position.X; for (int y = position.Y; y <= boardSize; y++) { BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if (entity instanceof FoodPoint && y!=position.Y) { verticalDownFoodAmount += ((FoodPoint) entity).getValue(); } } int verticalUpFoodAmount = 0; x = position.X; for (int y = position.Y; y > 0; y--) { BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if (entity instanceof FoodPoint && y!=position.Y) { verticalUpFoodAmount += ((FoodPoint) entity).getValue(); } } iint horizontalDownFoodAmount = 0; int y = position.Y; for (int x = position.X; x <= boardSize; x++) { BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if (entity instanceof FoodPoint && x!=position.X) { horizontalDownFoodAmount += ((FoodPoint) entity).getValue(); } } int horizontalUpFoodAmount = 0; y = position.Y; for (int x = position.X; x > 0; x--) { BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if (entity instanceof FoodPoint && x!=position.X) { horizontalUpFoodAmount += ((FoodPoint) entity).getValue(); } } int rightDiagonalUpFoodAmount = 0; x = position.X; y = position.Y; for(int i; i<boardSize; ++i){ x+=i; y+=i; BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if(x <= boardSize && y <= boardSize){ if (entity instanceof FoodPointb) { rightDiagonalUpFoodAmount += ((FoodPoint) entity).getValue(); } } } int rightDiagonalDownFoodAmount = 0; x = position.X; y = position.Y; for(int i; i<boardSize; ++i){ x-=i; y-=i; BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if(x > 0 && y > 0){ if (entity instanceof FoodPointb) { rightDiagonalDownFoodAmount += ((FoodPoint) entity).getValue(); } } } int leftDiagonalUpFoodAmount = 0; x = position.X; y = position.Y; for(int i; i<boardSize; ++i){ x+=i; y-=i; BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if(x > 0 && y <= boardSize){ if (entity instanceof FoodPointb) { leftDiagonalUpFoodAmount += ((FoodPoint) entity).getValue(); } } } int leftDiagonalDownFoodAmount = 0; x = position.X; y = position.Y; for(int i; i<boardSize; ++i){ x-=i; y+=i; BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if(x <= boardSize && y > 0){ if (entity instanceof FoodPointb) { leftDiagonalDownFoodAmount += ((FoodPoint) entity).getValue(); } } } int res = Math.max(Math.max(Math.max(verticalUpFoodAmount,horizontalUpFoodAmount),Math.max(verticalDownFoodAmount,horizontalDownFoodAmount)),Math.max(Math.max(rightDiagonalUpFoodAmount,leftDiagonalDownFoodAmount),Math.max(rightDiagonalDownFoodAmount,leftDiagonalUpFoodAmount))); if(res == verticalUpFoodAmount){ Direction result = Direction.NORTH; return result; }else if(res == horizontalUpFoodAmount){ Direction result = Direction.EAST; return result; }else if(res == verticalDownFoodAmount){ Direction result = Direction.SOUTH; return result; }else if(res == horizontalDownFoodAmount){ Direction result = Direction.WEST; return result; }else if(res == rightDiagonalUpFoodAmount){ Direction result = Direction.NORTH_EAST; return result; }else if(res == leftDiagonalDownFoodAmount){ Direction result = Direction.SOUTH_EAST; return result; }else if(res == rightDiagonalDownFoodAmount){ Direction result = Direction.SOUTH_WEST; return result; }else if(res == leftDiagonalUpFoodAmount){ Direction result = Direction.NORTH_WEST; return result; } } @Override public int travelDirection(Direction dir, Map<String, BoardEntity> boardData, int boardSize) { EntityPosition position = getEntityPosition(); InsectColor clr = getColor(); switch(dir.toString()){ case "SOUTH": int verticalDownFoodAmount = 0; int x = position.X; for (int y = position.Y; y <= boardSize; y++) { BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if (!(entity instanceof Insect)){ if (entity instanceof FoodPoint && y!=position.Y) { verticalDownFoodAmount += ((FoodPoint) entity).getValue(); } }else if(entity.getColor() == clr){ continue; }else{ break; } } return verticalDownFoodAmount; case "NORTH": int verticalUpFoodAmount = 0; x = position.X; for (int y = position.Y; y > 0; y--) { BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if (!(entity instanceof Insect)){ if (entity instanceof FoodPoint && y!=position.Y) { verticalUpFoodAmount += ((FoodPoint) entity).getValue(); } }else if(entity.getColor() == clr){ continue; }else{ break; } } return verticalUpFoodAmount; case "WEST": int horizontalDownFoodAmount = 0; y = position.Y; for (int x = position.X; x <= boardSize; x++) { BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if (!(entity instanceof Insect)){ if (entity instanceof FoodPoint && x!=position.X) { horizontalDownFoodAmount += ((FoodPoint) entity).getValue(); } }else if(entity.getColor() == clr){ continue; }else{ break; } } return horizontalDownFoodAmount; case "EAST": int horizontalUpFoodAmount = 0; y = position.Y; for (int x = position.X; x > 0; x--) { BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if (entity instanceof FoodPoint && x!=position.X) { if (!(entity instanceof Insect)){ horizontalUpFoodAmount += ((FoodPoint) entity).getValue(); }else if(entity.getColor() == clr){ continue; }else{ break; } } } return horizontalUpFoodAmount; case "NORTH_EAST": int rightDiagonalUpFoodAmount = 0; x = position.X; y = position.Y; for(int i; i<boardSize; ++i){ x+=i; y+=i; BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if(x <= boardSize && y <= boardSize){ if (!(entity instanceof Insect)){ if (entity instanceof FoodPointb) { rightDiagonalUpFoodAmount += ((FoodPoint) entity).getValue(); } }else if(entity.getColor() == clr){ continue; }else{ break; } } } return rightDiagonalUpFoodAmount; case "SOUTH_EAST": int rightDiagonalDownFoodAmount = 0; x = position.X; y = position.Y; for(int i; i<boardSize; ++i){ x-=i; y-=i; BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if(x > 0 && y > 0){ if (!(entity instanceof Insect)){ if (entity instanceof FoodPointb) { rightDiagonalDownFoodAmount += ((FoodPoint) entity).getValue(); } }else if(entity.getColor() == clr){ continue; }else{ break; } } } return rightDiagonalDowmFoodAmount; case "NORTH_WEST": int leftDiagonalUpFoodAmount = 0; x = position.X; y = position.Y; for(int i; i<boardSize; ++i){ x+=i; y-=i; BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if(x > 0 && y <= boardSize){ if (!(entity instanceof Insect)){ if (entity instanceof FoodPoint) { leftDiagonalUpFoodAmount += ((FoodPoint) entity).getValue(); } }else if(entity.getColor() == clr){ continue; }else{ break; } } } return leftDiagonalUpFoodAmount; case "SOUTH_WEST": int leftDiagonalDownFoodAmount = 0; x = position.X; y = position.Y; for(int i; i<boardSize; ++i){ x-=i; y+=i; BoardEntity entity = boardData.get(new EntityPosition(x, y).toString()); if(x <= boardSize && y > 0){ if (!(entity instanceof Insect)){ if (entity instanceof FoodPointb) { leftDiagonalDownFoodAmount += ((FoodPoint) entity).getValue(); } }else if(entity.getColor() == clr){ continue; }else{ break; } } } return leftDiagonalDownFoodAmount; } } } class Butterfly extends Insect implements OrthogonalMoving { public Butterfly(EntityPosition position, InsectColor color) { super(position, color); } @Override public int getBestDirection(Map<String, BoardEntity> boardData, int boardSize) { return 0; } @Override public int travelDirection(Direction dir, Map<String, BoardEntity> boardData, int boardSize) { return 0; } } class Spider extends Insect implements DiagonalMoving { public Spider(EntityPosition position, InsectColor color) { super(position, color); } @Override public int getBestDirection(Map<String, BoardEntity> boardData, int boardSize) { return 0; } @Override public int travelDirection(Direction dir, Map<String, BoardEntity> boardData, int boardSize) { return 0; } } class Grasshopper extends Insect implements OrthogonalMoving { public Grasshopper(EntityPosition position, InsectColor color) { super(position, color); } @Override public int getBestDirection(Map<String, BoardEntity> boardData, int boardSize) { return 0; } @Override public int travelDirection(Direction dir, Map<String, BoardEntity> boardData, int boardSize) { return 0; } } class FoodPoint extends BoardEntity { protected int foodAmount; public FoodPoint(EntityPosition position, int foodAmount) { this.foodAmount = foodAmount; this.entityPosition = position; } public int getValue() { return foodAmount; } } enum InsectColor { RED("Red"), GREEN("Green"), BLUE("Blue"), YELLOW("Yellow"); public static InsectColor toColor(String s) { switch (s) { case "Red": return InsectColor.RED; case "Green": return InsectColor.GREEN; case "Blue": return InsectColor.BLUE; default: return InsectColor.YELLOW; } } private String textRepresentation; private InsectColor(String text) { this.textRepresentation = text; } public String getTextRepresentation() { return textRepresentation; } } interface OrthogonalMoving { int getOrthogonalDirection(Direction dir, EntityPosition entityPosition, Map<String, BoardEntity> boardData, int boardSize); int travelOrthogonally(Direction dir, EntityPosition entityPosition, InsectColor color, Map<String, BoardEntity> boardData, int boardSize); } interface DiagonalMoving { int getDiagonalDirection(Direction dir, EntityPosition entityPosition, Map<String, BoardEntity> boardData, int boardSize); int travelDiagonally(Direction dir, EntityPosition entityPosition, InsectColor color, Map<String, BoardEntity> boardData, int boardSize); } enum Direction { NORTH, EAST, SOUTH, WEST, NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST; public String textRepresentation() { /*должен быть private*/ return switch (this) { case NORTH -> "N"; case SOUTH -> "S"; case EAST -> "E"; case WEST -> "W"; case NORTH_EAST -> "NE"; case SOUTH_EAST -> "SE"; case SOUTH_WEST -> "SW"; case NORTH_WEST -> "NW"; }; } private Direction direction; // - Direction(text: String) } class InvalidBoardSizeException extends Exception { public String getMessage() { return "Invalid board size"; } } class InvalidNumberOfInsectsException extends Exception { public String getMessage() { return "Invalid number of insects"; } } class InvalidNumberOfFoodPointsException extends Exception { public String getMessage() { return "Invalid number of food points"; } } class InvalidInsectColorException extends Exception { public String getMessage() { return "Invalid insect color"; } } class InvalidInsectTypeException extends Exception { public String getMessage() { return "Invalid insect type"; } } class InvalidEntityPositionException extends Exception { public String getMessage() { return "Invalid entity position"; } } class DuplicateInsectException extends Exception { public String getMessage() { return "Duplicate insects"; } } class TwoEntitiesOnSamePositionException extends Exception { public String getMessage() { return "Two entities in the same position"; } } - Assistant
- User
- Assistant