SmnVadik

Lab 6.6 (magic square) Java

Sep 10th, 2023
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.85 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileWriter;
  4. import java.io.IOException;
  5. import java.util.Arrays;
  6. import java.util.Scanner;
  7.  
  8. public class Main {
  9.     static Scanner scanner = new Scanner(System.in);
  10.     public static int size = 0;
  11.     public static int[][] magicSquare;
  12.  
  13.     public static void main(String[] args) throws IOException {
  14.         task();
  15.         int num;
  16.         do {
  17.             getInfo();
  18.             num = getNum();
  19.             getUserChoice(num);
  20.         } while (num != 0);
  21.         scanner.close();
  22.     }
  23.  
  24.     private static void task() {
  25.         System.out.println("Разработать программу, которая генерирует магический квадрат чётно-нечётной степени (6, 10, 18, …).");
  26.     }
  27.  
  28.     private static void getInfo() {
  29.         System.out.println("""
  30.                1 - Показать магический квадрат\s
  31.                2 - Сохранить квадрат в файл\s
  32.                0 - Нажмите чтобы выйти""");
  33.     }
  34.  
  35.     private static int getNum() {
  36.         int num = 0;
  37.         boolean isCorrect;
  38.         do {
  39.             isCorrect = true;
  40.             System.out.print("Введите число: ");
  41.             try {
  42.                 num = Integer.parseInt(scanner.nextLine());
  43.             } catch (NumberFormatException e) {
  44.                 isCorrect = false;
  45.                 System.out.println("Проверьте корректность введенных данных");
  46.             }
  47.             if (isCorrect && (num < 0 || num > 3)) {
  48.                 isCorrect = false;
  49.                 System.out.println("Диапазон ввода размера от 0 до 2");
  50.             }
  51.         } while (!isCorrect);
  52.         return num;
  53.     }
  54.  
  55.     private static int getSize() {
  56.         boolean isCorrect;
  57.         do {
  58.             isCorrect = true;
  59.             System.out.print("Введите размер квадрата: ");
  60.             try {
  61.                 size = Integer.parseInt(scanner.nextLine());
  62.             } catch (Exception e) {
  63.                 isCorrect = false;
  64.                 System.out.println("Проверьте корректность введенных данных");
  65.             }
  66.             if (isCorrect && size <= 50) {
  67.                 if ((size % 2 == 0) && (size % 4 != 0)) {
  68.                 } else {
  69.                     System.out.println("Число должно быть четно-нечетной степени");
  70.                     isCorrect = false;
  71.                 }
  72.             } else {
  73.                 System.out.println("Максимальный размер квадрата равен 50");
  74.             }
  75.         } while (!isCorrect);
  76.         return size;
  77.     }
  78.  
  79.     private static int[][] magicSquareOfOddOrder(int n) {
  80.         int[][] matrix = new int[n][n];
  81.         for (int i = 0; i < n; i++) {
  82.             Arrays.fill(matrix[i], 0);
  83.         }
  84.         int count = 1, y = 0, x = matrix.length/2;
  85.         do {
  86.             matrix[y][x] = count;
  87.             count++;
  88.             if (((y == 0) && (x >= n - 1)) && (matrix[n - 1][0] != 0)) {
  89.                 y++;
  90.             } else {
  91.                 y--;
  92.                 if (y < 0) {
  93.                     y = n - 1;
  94.                 }
  95.                 x++;
  96.                 if (x == n) {
  97.                     x = 0;
  98.                 }
  99.                 if (matrix[y][x] != 0) {
  100.                     y += 2;
  101.                     x--;
  102.                 }
  103.             }
  104.  
  105.         } while (count != n * n + 1);
  106.         return matrix;
  107.     }
  108.  
  109.     private static int[][] magicSquareOfEvenOddOrder(int n) {
  110.         int half = n/2;
  111.         int[][] matrix = new int[n][n];
  112.         int[][] tempMatrix;
  113.         tempMatrix = magicSquareOfOddOrder(half);
  114.  
  115.         // 1/4 матрицы
  116.         for (int i = 0; i < half; i++) {
  117.             for (int j = 0; j < half; j++) {
  118.                 matrix[i][j] = tempMatrix[i][j];
  119.             }
  120.         }
  121.         // 2/4 матрицы
  122.         for (int i = 0; i < half; i++) {
  123.             for (int j = half; j < n; j++) {
  124.                 int x = j-half;
  125.                 matrix[i][j] = (tempMatrix[i][x]+2*half*half);
  126.             }
  127.         }
  128.         // 3/4 матрицы
  129.         for (int i = half; i < n; i++) {
  130.             for (int j = 0; j < half; j++) {
  131.                 int x = i-half;
  132.                 matrix[i][j] = (tempMatrix[x][j]+3*half*half);
  133.             }
  134.         }
  135.         // 4/4 матрицы
  136.         for (int i = half; i < n; i++) {
  137.             for (int j = half; j < n; j++) {
  138.                 int x = i-half, y = j-half;
  139.                 matrix[i][j] = (tempMatrix[x][y]+half*half);
  140.             }
  141.         }
  142.         int move = 0;
  143.         for (int i = 6; i < n; i++) {
  144.             if((i%4!=0)&&(i%2==0)) move++;
  145.         }
  146.         for (int j = matrix.length/2-move; j <= matrix.length/2+move-1; j++) {
  147.             for (int i = 0; i < tempMatrix.length; i++) {
  148.  
  149.                 int key = matrix[i][j];
  150.                 matrix[i][j] = matrix[half+i][j];
  151.                 matrix[half+i][j] = key;
  152.             }
  153.         }
  154.         for (int j = 0; j <= 1; j++) {
  155.             if (j == 0) {
  156.                 int key = matrix[0][0];
  157.                 matrix[0][0] = matrix[half][0];
  158.                 matrix[half][0] = key;
  159.             }
  160.             if (j == 1) {
  161.                 int key = matrix[half - 1][0];
  162.                 matrix[half - 1][0] = matrix[n - 1][0];
  163.                 matrix[n - 1][0] = key;
  164.             }
  165.         }
  166.         for (int j = half+1; j < n-1; j++) {
  167.             for (int i = 1; i < half-1; i++) {
  168.                 int key = matrix[i][1];
  169.                 matrix[i][1] = matrix[half+i][1];
  170.                 matrix[half+i][1] = key;
  171.             }
  172.         }
  173.         return matrix;
  174.     }
  175.  
  176.     private static int readingSelection() {
  177.         boolean isCorrect;
  178.         int number = 0;
  179.         do {
  180.             isCorrect = true;
  181.             System.out.println("Хотите получить размер из файла - введите 0, ввести в консоли - 1");
  182.             try {
  183.                 number = Integer.parseInt(scanner.nextLine());
  184.             } catch (Exception  e) {
  185.                 isCorrect = false;
  186.                 System.out.println("Проверьте корректность введенных данных");
  187.             }
  188.             if (isCorrect && (number < 0) || (number > 1)) {
  189.                 System.out.println("Введите 0 или 1");
  190.             }
  191.         } while (!isCorrect);
  192.         return number;
  193.     }
  194.  
  195.     private static String inputPath() {
  196.         String path;
  197.         boolean isCorrect;
  198.         do {
  199.             isCorrect = true;
  200.             System.out.println("Введите полный путь к файлу");
  201.             path = scanner.nextLine();
  202.             File file = new File(path);
  203.             if (!file.exists()) {
  204.                 isCorrect = false;
  205.                 System.out.println("Неверно введен путь");
  206.             }
  207.             if (isCorrect && !file.canRead()) {
  208.                 System.out.println("Невозможно считать данные с файла");
  209.             }
  210.             if (isCorrect && !file.canWrite()) {
  211.                 System.out.println("Невозможно записать данные в файл");
  212.             }
  213.         } while (!isCorrect);
  214.         return path;
  215.     }
  216.  
  217.     private static int openData() throws FileNotFoundException {
  218.         String path = inputPath();
  219.         boolean isCorrect = true;
  220.         Scanner fileReader = new Scanner(new File(path));
  221.         try {
  222.             size = fileReader.nextInt();
  223.         } catch (Exception e) {
  224.             isCorrect = false;
  225.             System.out.println("");
  226.         }
  227.         if (isCorrect && size <= 50) {
  228.             if ((size % 2 == 0) && (size % 4 != 0)) {
  229.             } else {
  230.                 System.out.println("Число должно быть четно-нечетной степени");
  231.                 isCorrect = false;
  232.             }
  233.         } else {
  234.             System.out.println("Максимальный размер квадрата равен 50");
  235.             isCorrect = false;
  236.         }
  237.         if (isCorrect) {
  238.             System.out.println("Данные были успешно считаны.");
  239.         } else {
  240.             System.out.println("Данные не были считаны с файла");
  241.             size = getSize();
  242.         }
  243.         return size;
  244.     }
  245.  
  246.     private static void outputSquare() throws IOException{
  247.         int number = readingSelection();
  248.         if (number == 1) {
  249.             size = getSize();
  250.         } else {
  251.             size = openData();
  252.         }
  253.  
  254.         magicSquare = new int[size][size];
  255.         if ((size % 2 == 0) && (size % 4 != 0)) {
  256.             magicSquare = magicSquareOfEvenOddOrder(size);
  257.         }
  258.  
  259.         for (int i = 0; i < size; i++) {
  260.             for (int j = 0; j < size; j++) {
  261.                 System.out.print(magicSquare[i][j] + "\t");
  262.             }
  263.             System.out.println();
  264.         }
  265.     }
  266.  
  267.     private static void saveSquareToFile() throws IOException {
  268.         if ((size % 2 != 0) || (size % 4 == 0)) {
  269.             System.out.println("Создайте квадрта");
  270.             return;
  271.         }
  272.  
  273.         String path = inputPath();
  274.         FileWriter writer = new FileWriter(path);
  275.  
  276.         for (int i = 0; i < size; i++) {
  277.             for (int j = 0; j < size; j++) {
  278.                 writer.write(magicSquare[i][j] + "\t");
  279.             }
  280.             System.out.println();
  281.         }
  282.         writer.close();
  283.     }
  284.  
  285.     private static void getUserChoice(int num) throws IOException {
  286.         switch (num) {
  287.             case 1 -> outputSquare();
  288.             case 2 -> saveSquareToFile();
  289.         }
  290.     }
  291.  
  292. }
Advertisement
Add Comment
Please, Sign In to add comment