Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.io.*;
- public class Main {
- private static final Scanner scanner = new Scanner(System.in);
- private static Scanner fileScanner;
- private static final int MAX_P = 30;
- private static final int MIN_P = 0;
- private static final int MAX = 20;
- public static void main(String[] args) throws IOException, FileNotFoundException{
- control();
- scanner.close();
- }
- public static void control() throws FileNotFoundException, IOException{
- String path;
- int[] num = new int[3];
- String[] str = new String[2];
- info();
- if (selectToOpen() == 1) {
- path = getPath();
- fileScanner = new Scanner(new File(path));
- num = getNumFromFile(path);
- str = getStrFromFile(path);
- fileScanner.close();
- }
- else {
- num = inputNum();
- str = inputStr();
- }
- int d = num[0];
- int i = num[1];
- int c = num[2];
- String x = str[0];
- String y = str[1];
- int min = findMinCost(x, y, d, i, c);
- outputToConsole(min);
- if (selectToSave() == 1) {
- path = getPath();
- outputToFile(min, path);
- }
- }
- static void info() {
- System.out.println("Вводится три неотрицательных числа d, i, c и две строки X и Y.\n"+
- "Найти преобразование строки X в Y минимальной стоимости:");
- System.out.println(" -\tудалить любой символ из X (стоимость операции d);\n" +
- " -\tвставить любой символ в X (стоимость операции i);\n" +
- " -\tзаменить символ в X на произвольный (стоимость операции с).\n");
- }
- static int[] inputNum () {
- int[] num = new int[3];
- System.out.print("Введите неотрицательное число 'd': ");
- int d = checkNum();
- System.out.print("Введите неотрицательное число 'i': ");
- int i = checkNum();
- System.out.print("Введите неотрицательное число 'c': ");
- int c = checkNum();
- num[0] = d;
- num[1] = i;
- num[2] = c;
- return num;
- }
- static int checkNum() {
- int num = 0;
- boolean isCorrect;
- do {
- isCorrect = true;
- try {
- num = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность данных");
- }
- if (isCorrect & (num > MAX_P || num < MIN_P)) {
- isCorrect = false;
- System.out.println("Введите число 0 до 30");
- }
- } while (!isCorrect);
- return num;
- }
- static String[] inputStr () {
- String[] str = new String[2];
- System.out.println("Введите первую строку 'X'");
- String x = checkLine();//scanner.nextLine();
- System.out.println("Введите вторую строку 'Y'");
- String y = checkLine();//scanner.nextLine();
- str[0] = x;
- str[1] = y;
- return str;
- }
- static String checkLine() {
- String str = "";
- boolean isCorrect;
- do {
- isCorrect = true;
- try {
- str = scanner.nextLine();
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность данных");
- }
- if (isCorrect & (str.length() > MAX)) {
- isCorrect = false;
- System.out.println("Максимальное количество символов в строке равно 20");
- }
- } while (!isCorrect);
- return str;
- }
- static void outputToConsole (int min) {
- System.out.println("Минимальная стоимость = " + min);
- }
- static int selectToOpen () {
- int choice = 0;
- boolean isCorrect;
- do {
- System.out.println("Если вы хотите считать данные с файла - введите 1, с консоли - введите 0"); // If you want to read data from a file - enter 1, from the console - enter 0
- isCorrect = true;
- try {
- choice = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность введенных данных"); //check the correctness of the entered data
- }
- if (isCorrect && (choice != 1 && choice != 0)) {
- isCorrect = false;
- System.out.println("Введите 1 или 0"); //Enter 1 or 0
- }
- } while (!isCorrect);
- return choice;
- }
- static String getPath () {
- boolean isCorrect;
- String path;
- do {
- isCorrect = true;
- System.out.println("Введите полный путь к файлу"); //enter the full path to the file
- path = scanner.nextLine();
- File file = new File(path);
- if (!file.exists()) {
- isCorrect = false;
- System.out.println("Проверьте корректность введенной директории"); //check the correctness of the entered directory
- }
- } while (!isCorrect);
- return path;
- }
- static int[] getNumFromFile (String path) {
- int j;
- int[] num = new int[3];
- boolean isCorrect;
- for (j = 0; j < num.length; j++) {
- do {
- isCorrect = true;
- try {
- num[j] = Integer.parseInt(fileScanner.next());
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность данных в файле"); //check the correctness of the data in the file
- path = getPath();
- }
- if (isCorrect && (num[j] < MIN_P || num[j] > MAX_P)) {
- isCorrect = false;
- System.out.println("Проверьте корректность данных в файле"); //"check the correctness of the data in the file
- path = getPath();
- }
- } while (!isCorrect);
- }
- return num;
- }
- static String[] getStrFromFile (String path) {
- int j;
- String text = fileScanner.nextLine();
- String[] str = new String[2];
- boolean isCorrect;
- for (j = 0; j < str.length; j++) {
- do {
- isCorrect = true;
- try {
- str[j] = fileScanner.nextLine();
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность данных в файле"); //check the correctness of the data in the file
- path = getPath();
- }
- if (isCorrect && str[j].length() > MAX) {
- isCorrect = false;
- System.out.println("Проверьте корректность данных в файле"); //"check the correctness of the data in the file
- path = getPath();
- }
- } while (!isCorrect);
- }
- return str;
- }
- static int selectToSave () {
- int choice = 0;
- boolean isCorrect;
- do {
- System.out.println("Если вы хотите записать данные в файл - введите 1, нет - введите 0");
- isCorrect = true;
- try {
- choice = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность введенных данных");
- }
- if (isCorrect && (choice != 1 && choice != 0)) {
- isCorrect = false;
- System.out.println("Введите 1 или 0");
- }
- } while (!isCorrect);
- return choice;
- }
- static void outputToFile(int res, String path) throws IOException{
- FileWriter writer = new FileWriter(path);
- writer.write("Минимальная стоимость = " + res);
- writer.close();
- System.out.println("\n" + "Данные сохранены успешно");
- }
- static int findMinCost(String X, String Y, int d, int i, int c) { // метод Дамерау-Левенштейна
- int m = X.length();
- int n = Y.length();
- if (m == 0) {
- // если строка X пустая, то для преобразования X в Y необходимо вставить все символы Y
- return n * i;
- }
- if (n == 0) {
- // если строка Y пустая, то для преобразования X в Y необходимо удалить все символы X
- return m * d;
- }
- if (X.charAt(m - 1) == Y.charAt(n - 1)) {
- // если последние символы X и Y совпадают, то ничего не нужно делать с ними
- return findMinCost(X.substring(0, m - 1), Y.substring(0, n - 1), d, i, c);
- }
- // находим минимальную стоимость преобразования
- int deleteCost = findMinCost(X.substring(0, m - 1), Y, d, i, c) + d; // удаление символа из X
- int insertCost = findMinCost(X, Y.substring(0, n - 1), d, i, c) + i; // вставка символа в X
- int replaceCost = findMinCost(X.substring(0, m - 1), Y.substring(0, n - 1), d, i, c) + c; // замена символа в X на символ из Y
- return Math.min(Math.min(deleteCost, insertCost), replaceCost);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement