Advertisement
SmnVadik

Lab5.2(Java)

Aug 19th, 2023
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.76 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.ArrayList;
  3. import java.util.Objects;
  4. import java.util.Scanner;
  5.  
  6. public class Main {
  7.  
  8.     static Scanner scanner = new Scanner(System.in);
  9.     public static boolean exit = false;
  10.     public static Tree tree = new Tree();
  11.     public static ArrayList<Integer> keys = new ArrayList<>();
  12.     public static void main (String[] args) throws IOException{
  13.         System.out.println("Эта программа демонстрирует дерево как структуру данных.");
  14.         while (!exit) {
  15.             showInfo();
  16.             chooseAction();
  17.         }
  18.     }
  19.  
  20.     public static void showInfo () {
  21.         System.out.println("1 - создать пустое дерево");
  22.         System.out.println("2 - добавить новый элемент в дерево");
  23.         System.out.println("3 - удалить элемент из дерева");
  24.         System.out.println("4 - просмотреть дерево");
  25.         System.out.println("5 - открыть дерево из файла");
  26.         System.out.println("6 - сохранить дерево в файл");
  27.         System.out.println("7 - Выход");
  28.     }
  29.     private static int inputData() {
  30.         int n = 0;
  31.         boolean isIncorrect;
  32.         final int MIN_SIZE = 1;
  33.         do {
  34.             isIncorrect = false;
  35.             try {
  36.                 n = Integer.parseInt(scanner.nextLine());
  37.             } catch (Exception e) {
  38.                 isIncorrect = true;
  39.                 System.out.println("Пожалуйста, введите целое число");
  40.             }
  41.             if (n < MIN_SIZE && !isIncorrect) {
  42.                 System.out.println("Пожалуйста, введите положительное число");
  43.                 isIncorrect = true;
  44.             }
  45.         } while (isIncorrect);
  46.         return n;
  47.     }
  48.  
  49.     private static int inputKey() {
  50.         int n = 0;
  51.         boolean isIncorrect;
  52.         do {
  53.             isIncorrect = false;
  54.             try {
  55.                 n = Integer.parseInt(scanner.nextLine());
  56.             } catch (Exception e) {
  57.                 isIncorrect = true;
  58.                 System.out.println("Пожалуйста, введите целое число");
  59.             }
  60.         } while (isIncorrect);
  61.         return n;
  62.     }
  63.  
  64.     public static void chooseAction () throws IOException {
  65.         int chose;
  66.         boolean isIncorrect;
  67.         final int MAX = 8;
  68.         System.out.println("Пожалуйста, выберите:");
  69.  
  70.         do {
  71.             chose = inputData();
  72.             isIncorrect = false;
  73.             if ((chose > MAX) || (chose < 1)) {
  74.                 isIncorrect = true;
  75.                 System.out.println("Пожалуйста, введите правильный номер функции.");
  76.             }
  77.         } while (isIncorrect);
  78.  
  79.         switch (chose) {
  80.             case 1 -> buildTree();
  81.             case 2 -> addNode();
  82.             case 3 -> removeNode();
  83.             case 4 -> showTree();
  84.             case 5 -> openFile();
  85.             case 6 -> saveData();
  86.             case 7 -> exit = true;
  87.         }
  88.     }
  89.  
  90.     public static void buildTree () {
  91.         tree.createTree();
  92.         System.out.println("Готово!");
  93.         System.out.println(); // просто пустая строка для удобства чтения
  94.     }
  95.  
  96.     public static boolean checkExistenceOrUniqueness (int nodeToDelete) {
  97.         for (Integer key : keys) {
  98.             if (nodeToDelete == key) {
  99.                 return true;
  100.             }
  101.         }
  102.         return false;
  103.     }
  104.  
  105.     public static boolean checkUniqueness (int[] keysFromFile) {
  106.         for (int i = 0; i < keysFromFile.length; i++){
  107.             for (int j = i + 1; j < keysFromFile.length; j++){
  108.                 if (keysFromFile[i] == keysFromFile[j]) {
  109.                     System.out.println("В вашем файле есть повторения. Измените исходные данные.");
  110.                     return false;
  111.                 }
  112.             }
  113.         }
  114.         for (int i = 0; i < keysFromFile.length; i++) {
  115.             if (keys.contains(keysFromFile[i])) {
  116.                 System.out.println("Элемент, которого пытаются добавить, уже существует. Измените исходные данные.");
  117.                 return false;
  118.             }
  119.         }
  120.         return true;
  121.     }
  122.  
  123.     public static void addNode () {
  124.         System.out.println("Входной узел:");
  125.         int node = inputKey();
  126.         if (checkExistenceOrUniqueness(node)) {
  127.             System.out.println("К сожалению, невозможно добавить узел, который уже существует. Введите снова");
  128.         } else {
  129.             tree.addNode(node);
  130.             keys.add(node);
  131.             System.out.println("Узел \"" + node +"\" добавлен.");
  132.         }
  133.         System.out.println(); // просто пустая строка для удобства чтения
  134.     }
  135.  
  136.     public static void removeNode () {
  137.         System.out.println("Введите элемент для удаления.");
  138.         int nodeToDelete = inputKey();
  139.         int index;
  140.         if (tree.getRoot() != null) {
  141.             if (checkExistenceOrUniqueness(nodeToDelete)) {
  142.                 tree.deleteNode(nodeToDelete);
  143.                 index = keys.indexOf(nodeToDelete);
  144.                 keys.remove(index);
  145.                 System.out.println("Готово!");
  146.             } else
  147.                 System.out.println("Такого узла не существует.");
  148.         } else {
  149.             System.out.println("Дерево пустое.");
  150.         }
  151.         System.out.println(); // просто пустая строка для удобства чтения
  152.     }
  153.  
  154.     public static void showTree () {
  155.         String text = "";
  156.         if (tree.getRoot() != null) {
  157.             System.out.println("Для улучшения работы пользователя поверните монитор по часовой стрелке)");
  158.             Tree root = tree.getRoot();
  159.             tree.printTree(root, 0, text);
  160.             System.out.println("Номера вершин: " + tree.string);
  161.             tree.string = "";
  162.         } else {
  163.             System.out.println("Дерево пустое.");
  164.         }
  165.         System.out.println(); // просто пустая строка для удобства чтения
  166.     }
  167.  
  168.     public static String inputFilePath() {
  169.         String path;
  170.         boolean isIncorrect;
  171.         do {
  172.             isIncorrect = false;
  173.             System.out.println("Введите путь к файлу:");
  174.             path = scanner.nextLine();
  175.             File file = new File(path);
  176.             if (!file.exists()) {
  177.                 System.out.println("Неправильный путь к файлу");
  178.                 isIncorrect = true;
  179.             }
  180.             if (!file.canRead() && file.exists()) {
  181.                 System.out.println("Невозможно прочитать из файла.");
  182.                 isIncorrect = true;
  183.             }
  184.             if (!file.canWrite() && file.canRead()) {
  185.                 System.out.println("Невозможно записать в файл.");
  186.                 isIncorrect = true;
  187.             }
  188.         } while (isIncorrect);
  189.         return path;
  190.     }
  191.  
  192.     public static String[] deleteSpacesInArray (String[] keys) {
  193.         int counterOfSpaces = 0;
  194.         for (int j = 0; j < keys.length; j++) {
  195.             if (!Objects.equals(keys[j], "")) {
  196.                 counterOfSpaces++;
  197.             }
  198.         }
  199.         int i = 0;
  200.         String[] newArr = new String[counterOfSpaces];
  201.         for (int j = 0; j < keys.length; j++) {
  202.             if (!Objects.equals(keys[j], "")) {
  203.                 newArr[i] = keys[j];
  204.                 i++;
  205.             }
  206.         }
  207.         return newArr;
  208.     }
  209.     public static boolean checkArrayOfStrings (String[] keys) {
  210.         for (int j = 0; j < keys.length; j++){
  211.             try {
  212.                 Integer.parseInt(keys[j]);
  213.             } catch (Exception e) {
  214.                 System.out.println("Проверьте файл, он не должен содержать ничего, кроме цифр.");
  215.                 return false;
  216.             }
  217.         }
  218.         return true;
  219.     }
  220.  
  221.     public static int[] getArrOfKeys (String[] keys) {
  222.         int[] keysFromFile = new int[keys.length];
  223.         for (int j = 0; j < keys.length; j++) {
  224.             keysFromFile[j] = Integer.parseInt(keys[j]);
  225.         }
  226.         return keysFromFile;
  227.     }
  228.     public static void openFile () {
  229.         System.out.println("Пример строки с узлами дерева:");
  230.         System.out.println("узел1 - узел2 - узел3 - ... - узелN");
  231.         System.out.println("P.S. после каждой позиции ожидается только пробел. Узлы из файла будут добавлены в существующее дерево.");
  232.         String path = inputFilePath();
  233.         String str;
  234.         String[] mas;
  235.         try {
  236.             Scanner fileReader = new Scanner(new File(path));
  237.             str = fileReader.nextLine();
  238.             mas = str.split(" ");
  239.             mas = deleteSpacesInArray(mas);
  240.             if (checkArrayOfStrings(mas)) {
  241.                 int[] keysFromFile = getArrOfKeys(mas);
  242.                 if (checkUniqueness(keysFromFile)) {
  243.                     for (int j = 0; j < keysFromFile.length; j++) {
  244.                         tree.addNode(keysFromFile[j]);
  245.                         keys.add(keysFromFile[j]);
  246.                     }
  247.                     System.out.println("Готово!");
  248.                 }
  249.             }
  250.         } catch (Exception q) {
  251.             System.out.println("Что-то пошло не так, проверьте файл.");
  252.         }
  253.     }
  254.     public static void saveData () throws IOException {
  255.         if (tree.getRoot() != null) {
  256.             String path = inputFilePath();
  257.             FileWriter writer = new FileWriter(path);
  258.             String result = "";
  259.             for (Integer key: keys) {
  260.                 result = result + key + " ";
  261.             }
  262.             writer.write(result);
  263.             writer.close();
  264.             System.out.println("Готово!");
  265.         } else {
  266.             System.out.println("Дерево пусто, добавьте несколько узлов!");
  267.         }
  268.     }
  269. }
  270.  
  271.  
  272. public class Tree {
  273.  
  274.     public String string = "";
  275.     private int key;
  276.     private Tree leftChild;
  277.     private Tree rightChild;
  278.  
  279.     public static Tree rootNode;
  280.  
  281.     public Tree getRoot() {
  282.         return rootNode;
  283.     }
  284.  
  285.     public int getKey() {
  286.         return this.key;
  287.     }
  288.  
  289.     public void setKey(final int key) {
  290.         this.key = key;
  291.     }
  292.  
  293.     public Tree getLeftChild() {
  294.         return this.leftChild;
  295.     }
  296.  
  297.     public void setLeftChild(final Tree leftChild) {
  298.         this.leftChild = leftChild;
  299.     }
  300.  
  301.     public Tree getRightChild() {
  302.         return this.rightChild;
  303.     }
  304.  
  305.     public void setRightChild(final Tree rightChild) {
  306.         this.rightChild = rightChild;
  307.     }
  308.  
  309.     public void createTree() {
  310.         rootNode = null;
  311.     }
  312.  
  313.     public void addNode(int key) {
  314.         Tree newNode = new Tree();
  315.         newNode.setKey(key);
  316.         if (rootNode == null) {
  317.             rootNode = newNode;
  318.         } else {
  319.             Tree currentNode = rootNode;
  320.             Tree parentNode;
  321.             while (true) {
  322.                 parentNode = currentNode;
  323.                 if (key == currentNode.getKey()) {
  324.                     return;
  325.                 } else if (key < currentNode.getKey()) {
  326.                     currentNode = currentNode.getLeftChild();
  327.                     if (currentNode == null) {
  328.                         parentNode.setLeftChild(newNode);
  329.                         return;
  330.                     }
  331.                 } else {
  332.                     currentNode = currentNode.getRightChild();
  333.                     if (currentNode == null) {
  334.                         parentNode.setRightChild(newNode);
  335.                         return;
  336.                     }
  337.                 }
  338.             }
  339.         }
  340.     }
  341.  
  342.     public void deleteNode(int value) {
  343.         Tree currentNode = rootNode;
  344.         Tree parentNode = rootNode;
  345.         boolean isLeftChild = true;
  346.         while (currentNode.getKey() != value) {
  347.             parentNode = currentNode;
  348.             if (value < currentNode.getKey()) {
  349.                 isLeftChild = true;
  350.                 currentNode = currentNode.getLeftChild();
  351.             }
  352.             else {
  353.                 isLeftChild = false;
  354.                 currentNode = currentNode.getRightChild();
  355.             }
  356.         }
  357.  
  358.         if (currentNode.getLeftChild() == null && currentNode.getRightChild() == null) {
  359.             if (currentNode == rootNode)
  360.                 rootNode = null;
  361.             else if (isLeftChild)
  362.                 parentNode.setLeftChild(null);
  363.             else
  364.                 parentNode.setRightChild(null);
  365.         }
  366.         else if (currentNode.getRightChild() == null) {
  367.             if (currentNode == rootNode)
  368.                 rootNode = currentNode.getLeftChild();
  369.             else if (isLeftChild)
  370.                 parentNode.setLeftChild(currentNode.getLeftChild());
  371.             else
  372.                 parentNode.setRightChild(currentNode.getLeftChild());
  373.         }
  374.         else if (currentNode.getLeftChild() == null) {
  375.             if (currentNode == rootNode)
  376.                 rootNode = currentNode.getRightChild();
  377.             else if (isLeftChild)
  378.                 parentNode.setLeftChild(currentNode.getRightChild());
  379.             else
  380.                 parentNode.setRightChild(currentNode.getRightChild());
  381.         }
  382.         else {
  383.             Tree successor = getSuccessor(currentNode);
  384.             if (currentNode == rootNode)
  385.                 rootNode = successor;
  386.             else if (isLeftChild)
  387.                 parentNode.setLeftChild(successor);
  388.             else
  389.                 parentNode.setRightChild(successor);
  390.         }
  391.     }
  392.  
  393.     private Tree getSuccessor(Tree deleteNode) {
  394.         Tree successorParent = deleteNode;
  395.         Tree successor = deleteNode;
  396.         Tree current = deleteNode.getRightChild();
  397.         while (current != null) {
  398.             successorParent = successor;
  399.             successor = current;
  400.             current = current.getLeftChild();
  401.         }
  402.         if (successor != deleteNode.getRightChild()) {
  403.             successorParent.setLeftChild(successor.getRightChild());
  404.             successor.setRightChild(deleteNode.getRightChild());
  405.         }
  406.         successor.setLeftChild(deleteNode.getLeftChild());
  407.         return successor;
  408.     }
  409.  
  410.     public static int height(Tree node) {
  411.         if (node == null) {
  412.             return 0;
  413.         }
  414.  
  415.         if ((node.getLeftChild() != null && node.getLeftChild().getRightChild() == node) && (node.getRightChild() != null && node.getRightChild().getLeftChild() == node)) {
  416.             return 1;
  417.         }
  418.  
  419.         return 1 + Math.max(height(node.getLeftChild()), height(node.getRightChild()));
  420.     }
  421.  
  422.     public void printTree(Tree node, int level, String text) {
  423.  
  424.         if (node == null) {
  425.             return;
  426.         }
  427.         printTree(node.getRightChild(), level + 1, text);
  428.         for (int i = 0; i < level; i++) {
  429.             System.out.print("    ");
  430.         }
  431.         System.out.println(node.getKey());
  432.         if (height(node.getLeftChild()) != height(node.getRightChild())) {
  433.             text = text + node.getKey() + ' ';
  434.             string = string + text;
  435.         }
  436.         printTree(node.getLeftChild(), level + 1, text);
  437.     }
  438. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement