Advertisement
SmnVadik

Lab 4.2 (Java)

Mar 23rd, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.46 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.io.*;
  3. public class Main {
  4.     private static final Scanner scanner = new Scanner(System.in);
  5.     private static Scanner fileScanner;
  6.     private static final int MAX_P = 30;
  7.     private static final int MIN_P = 0;
  8.     private static final int MAX = 20;
  9.  
  10.  
  11.     public static void main(String[] args) throws IOException, FileNotFoundException{
  12.         control();
  13.         scanner.close();
  14.     }
  15.  
  16.     public static void control() throws FileNotFoundException, IOException{
  17.         String path;
  18.         int[] num = new int[3];
  19.         String[] str = new String[2];
  20.  
  21.         info();
  22.         if (selectToOpen() == 1) {
  23.             path = getPath();
  24.             fileScanner = new Scanner(new File(path));
  25.             num = getNumFromFile(path);
  26.             str = getStrFromFile(path);
  27.             fileScanner.close();
  28.         }
  29.         else {
  30.             num = inputNum();
  31.             str = inputStr();
  32.         }
  33.         int d = num[0];
  34.         int i = num[1];
  35.         int c = num[2];
  36.         String x = str[0];
  37.         String y = str[1];
  38.         int min = findMinCost(x, y, d, i, c);
  39.         outputToConsole(min);
  40.  
  41.         if (selectToSave() == 1) {
  42.             path = getPath();
  43.             outputToFile(min, path);
  44.         }
  45.     }
  46.  
  47.     static void info() {
  48.         System.out.println("Вводится три неотрицательных числа d, i, c и две строки X и Y.\n"+
  49.                 "Найти преобразование строки X в Y минимальной стоимости:");
  50.         System.out.println(" -\tудалить любой символ из X (стоимость операции d);\n" +
  51.                 " -\tвставить любой символ в X (стоимость операции i);\n" +
  52.                 " -\tзаменить символ в X на произвольный (стоимость операции с).\n");
  53.     }
  54.  
  55.     static int[] inputNum () {
  56.         int[] num = new int[3];
  57.         System.out.print("Введите неотрицательное число 'd': ");
  58.         int d = checkNum();
  59.         System.out.print("Введите неотрицательное число 'i': ");
  60.         int i = checkNum();
  61.         System.out.print("Введите неотрицательное число 'c': ");
  62.         int c = checkNum();
  63.         num[0] = d;
  64.         num[1] = i;
  65.         num[2] = c;
  66.         return num;
  67.     }
  68.  
  69.     static int checkNum() {
  70.         int num = 0;
  71.         boolean isCorrect;
  72.         do {
  73.             isCorrect = true;
  74.             try {
  75.                 num = Integer.parseInt(scanner.nextLine());
  76.             } catch (Exception e) {
  77.                 isCorrect = false;
  78.                 System.out.println("Проверьте корректность данных");
  79.             }
  80.             if (isCorrect & (num > MAX_P || num < MIN_P)) {
  81.                 isCorrect = false;
  82.                 System.out.println("Введите число 0 до 30");
  83.             }
  84.         } while (!isCorrect);
  85.         return num;
  86.     }
  87.  
  88.     static String[] inputStr () {
  89.         String[] str = new String[2];
  90.         System.out.println("Введите первую строку 'X'");
  91.         String x = checkLine();//scanner.nextLine();
  92.         System.out.println("Введите вторую строку 'Y'");
  93.         String y = checkLine();//scanner.nextLine();
  94.         str[0] = x;
  95.         str[1] = y;
  96.         return str;
  97.     }
  98.  
  99.     static String checkLine() {
  100.         String str = "";
  101.         boolean isCorrect;
  102.         do {
  103.             isCorrect = true;
  104.             try {
  105.                 str = scanner.nextLine();
  106.             } catch (Exception e) {
  107.                 isCorrect = false;
  108.                 System.out.println("Проверьте корректность данных");
  109.             }
  110.             if (isCorrect & (str.length() > MAX)) {
  111.                 isCorrect = false;
  112.                 System.out.println("Максимальное количество символов в строке равно 20");
  113.             }
  114.         } while (!isCorrect);
  115.         return str;
  116.     }
  117.  
  118.     static void outputToConsole (int min) {
  119.         System.out.println("Минимальная стоимость = " + min);
  120.     }
  121.  
  122.     static int selectToOpen () {
  123.         int choice = 0;
  124.         boolean isCorrect;
  125.         do {
  126.             System.out.println("Если вы хотите считать данные с файла - введите 1, с консоли - введите 0");  // If you want to read data from a file - enter 1, from the console - enter 0
  127.             isCorrect = true;
  128.             try {
  129.                 choice = Integer.parseInt(scanner.nextLine());
  130.             } catch (Exception e) {
  131.                 isCorrect = false;
  132.                 System.out.println("Проверьте корректность введенных данных"); //check the correctness of the entered data
  133.             }
  134.             if (isCorrect && (choice != 1 && choice != 0)) {
  135.                 isCorrect = false;
  136.                 System.out.println("Введите 1 или 0"); //Enter 1 or 0
  137.             }
  138.         } while (!isCorrect);
  139.         return choice;
  140.     }
  141.  
  142.     static String getPath () {
  143.         boolean isCorrect;
  144.         String path;
  145.         do {
  146.             isCorrect = true;
  147.             System.out.println("Введите полный путь к файлу"); //enter the full path to the file
  148.             path = scanner.nextLine();
  149.             File file = new File(path);
  150.             if (!file.exists()) {
  151.                 isCorrect = false;
  152.                 System.out.println("Проверьте корректность введенной директории"); //check the correctness of the entered directory
  153.             }
  154.         } while (!isCorrect);
  155.         return path;
  156.     }
  157.  
  158.     static int[] getNumFromFile (String path) {
  159.         int j;
  160.         int[] num = new int[3];
  161.         boolean isCorrect;
  162.         for (j = 0; j < num.length; j++) {
  163.             do {
  164.                 isCorrect = true;
  165.                 try {
  166.                     num[j] = Integer.parseInt(fileScanner.next());
  167.                 } catch (Exception e) {
  168.                     isCorrect = false;
  169.                     System.out.println("Проверьте корректность данных в файле"); //check the correctness of the data in the file
  170.                     path = getPath();
  171.                 }
  172.                 if (isCorrect && (num[j] < MIN_P || num[j] > MAX_P)) {
  173.                     isCorrect = false;
  174.                     System.out.println("Проверьте корректность данных в файле"); //"check the correctness of the data in the file
  175.                     path = getPath();
  176.                 }
  177.             } while (!isCorrect);
  178.         }
  179.         return num;
  180.     }
  181.  
  182.     static String[] getStrFromFile (String path) {
  183.         int j;
  184.         String text = fileScanner.nextLine();
  185.         String[] str = new String[2];
  186.         boolean isCorrect;
  187.         for (j = 0; j < str.length; j++) {
  188.             do {
  189.                 isCorrect = true;
  190.                 try {
  191.                     str[j] = fileScanner.nextLine();
  192.                 } catch (Exception e) {
  193.                     isCorrect = false;
  194.                     System.out.println("Проверьте корректность данных в файле"); //check the correctness of the data in the file
  195.                     path = getPath();
  196.                 }
  197.                 if (isCorrect && str[j].length() > MAX) {
  198.                     isCorrect = false;
  199.                     System.out.println("Проверьте корректность данных в файле"); //"check the correctness of the data in the file
  200.                     path = getPath();
  201.                 }
  202.             } while (!isCorrect);
  203.         }
  204.         return str;
  205.     }
  206.  
  207.     static int selectToSave () {
  208.         int choice = 0;
  209.         boolean isCorrect;
  210.         do {
  211.             System.out.println("Если вы хотите записать данные в файл - введите 1, нет - введите 0");
  212.             isCorrect = true;
  213.             try {
  214.                 choice = Integer.parseInt(scanner.nextLine());
  215.             } catch (Exception e) {
  216.                 isCorrect = false;
  217.                 System.out.println("Проверьте корректность введенных данных");
  218.             }
  219.             if (isCorrect && (choice != 1 && choice != 0)) {
  220.                 isCorrect = false;
  221.                 System.out.println("Введите 1 или 0");
  222.             }
  223.         } while (!isCorrect);
  224.         return choice;
  225.     }
  226.  
  227.     static void outputToFile(int res, String path) throws IOException{
  228.         FileWriter writer = new FileWriter(path);
  229.         writer.write("Минимальная стоимость = " + res);
  230.         writer.close();
  231.  
  232.         System.out.println("\n" + "Данные сохранены успешно");
  233.     }
  234.  
  235.     static int findMinCost(String X, String Y, int d, int i, int c) {     // метод Дамерау-Левенштейна
  236.         int m = X.length();
  237.         int n = Y.length();
  238.  
  239.         if (m == 0) {
  240.             // если строка X пустая, то для преобразования X в Y необходимо вставить все символы Y
  241.             return n * i;
  242.         }
  243.  
  244.         if (n == 0) {
  245.             // если строка Y пустая, то для преобразования X в Y необходимо удалить все символы X
  246.             return m * d;
  247.         }
  248.  
  249.         if (X.charAt(m - 1) == Y.charAt(n - 1)) {
  250.             // если последние символы X и Y совпадают, то ничего не нужно делать с ними
  251.             return findMinCost(X.substring(0, m - 1), Y.substring(0, n - 1), d, i, c);
  252.         }
  253.  
  254.         // находим минимальную стоимость преобразования
  255.         int deleteCost = findMinCost(X.substring(0, m - 1), Y, d, i, c) + d; // удаление символа из X
  256.         int insertCost = findMinCost(X, Y.substring(0, n - 1), d, i, c) + i; // вставка символа в X
  257.         int replaceCost = findMinCost(X.substring(0, m - 1), Y.substring(0, n - 1), d, i, c) + c; // замена символа в X на символ из Y
  258.  
  259.         return Math.min(Math.min(deleteCost, insertCost), replaceCost);
  260.     }
  261.  
  262. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement