Advertisement
SmnVadik

Lab 7.3 (Java)

Sep 13th, 2023
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.74 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Graph {
  5.     private int V; // Количество вершин
  6.     private List<Integer>[] adjList; // Список смежности
  7.  
  8.     public Graph(int vertices) {
  9.         V = vertices;
  10.         adjList = new ArrayList[vertices];
  11.         for (int i = 0; i < vertices; ++i) {
  12.             adjList[i] = new ArrayList<>();
  13.         }
  14.     }
  15.  
  16.     public void addEdge(int u, int v) {
  17.         adjList[u].add(v);
  18.         adjList[v].add(u);
  19.     }
  20.  
  21.     public Set<Integer> findVertexCover() {
  22.         Set<Integer> vertexCover = new HashSet<>();
  23.         boolean[] visited = new boolean[V];
  24.  
  25.         for (int u = 0; u < V; u++) {
  26.             if (!visited[u]) {
  27.                 for (int v : adjList[u]) {
  28.                     if (!visited[v]) {
  29.                         vertexCover.add(u);
  30.                         vertexCover.add(v);
  31.                         visited[u] = true;
  32.                         visited[v] = true;
  33.                         break;
  34.                     }
  35.                 }
  36.             }
  37.         }
  38.         return vertexCover;
  39.     }
  40. }
  41.  
  42. public class Main {
  43.     private static final int MIN_SIZE = 3;
  44.     private static final int MAX_SIZE = 12;
  45.     private static final int MIN_VALUE = 0;
  46.     private static final Scanner scanner = new Scanner(System.in);
  47.  
  48.  
  49.     public static void main(String[] args) throws FileNotFoundException {
  50.         outputTaskInfo();
  51.         processUserInput();
  52.         scanner.close();
  53.     }
  54.  
  55.     public static void outputTaskInfo() {
  56.         System.out.println("Найти вершинное покрытие графа.");
  57.     }
  58.  
  59.     public static void processUserInput() throws FileNotFoundException {
  60.         int sizeVertices = 0;
  61.         int choiceForInput;
  62.         String pathToIn = "";
  63.  
  64.         System.out.println("Вы желаете ввести данные с консоли(0) или взять данные из файла(1)?");
  65.         choiceForInput = getVerificationOfChoice();
  66.  
  67.         if (choiceForInput == 0) {
  68.             sizeVertices = readSizeFromConsole();
  69.             Graph graph = new Graph(sizeVertices);
  70.             fillGraphFromConsole(graph, sizeVertices);
  71.             processUserOutput(graph);
  72.         }
  73.         if (choiceForInput == 1) {
  74.             pathToIn = inputPathToFile();
  75.             sizeVertices = readSizeFromFile(pathToIn);
  76.             Graph graph = new Graph(sizeVertices);
  77.             fillGraphFromFile(graph, sizeVertices, pathToIn);
  78.             processUserOutput(graph);
  79.         }
  80.     }
  81.  
  82.     public static void processUserOutput(Graph graph) {
  83.         int choiceForOutput;
  84.         String path = "";
  85.         boolean isIncorrect;
  86.  
  87.         System.out.println("Вы желаете получить результат в консоли(0) или в файле(1)?");
  88.         choiceForOutput = getVerificationOfChoice();
  89.  
  90.         Set<Integer> vertexCover = graph.findVertexCover();
  91.  
  92.         if (choiceForOutput == 1) {
  93.             path = inputPathToFile();
  94.             System.out.println("Вывод вершинного покрытия графа в файл...");
  95.             do {
  96.                 isIncorrect = false;
  97.                 try {
  98.                     FileWriter writer = new FileWriter(path);
  99.                     writer.write("Вершинное покрытие графа:\n");
  100.                     for (int vertex : vertexCover) {
  101.                         writer.write(vertex +" ");
  102.                     }
  103.                     writer.close();
  104.                 } catch (IOException e) {
  105.                     isIncorrect = true;
  106.                     System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!");
  107.                     path = inputPathToFile();
  108.                 }
  109.             } while (isIncorrect);
  110.             System.out.println("Данные успешно записаны в файл!");
  111.         }
  112.         if (choiceForOutput == 0) {
  113.             System.out.println("Вершинное покрытие графа:");
  114.             for (int vertex : vertexCover) {
  115.                 System.out.print(vertex + " ");
  116.             }
  117.         }
  118.     }
  119.  
  120.     public static int getVerificationOfChoice() {
  121.         int choice = 0;
  122.         boolean isIncorrect;
  123.         do {
  124.             isIncorrect = false;
  125.             try {
  126.                 choice = Integer.parseInt(scanner.nextLine());
  127.             } catch (NumberFormatException e) {
  128.                 System.out.println("Проверьте корректность ввода данных!");
  129.                 isIncorrect = true;
  130.             }
  131.             if (!isIncorrect && (choice != 0 && choice != 1)) {
  132.                 System.out.println("Для выбора введите 0 или 1!");
  133.                 isIncorrect = true;
  134.             }
  135.         } while (isIncorrect);
  136.         return choice;
  137.     }
  138.  
  139.     public static String inputPathToFile() {
  140.         boolean isIncorrect;
  141.         String path;
  142.         System.out.println("Укажите путь к файлу: ");
  143.         do {
  144.             isIncorrect = false;
  145.             path = scanner.nextLine();
  146.             File file = new File(path);
  147.  
  148.             if (!file.exists()) {
  149.                 System.out.println("По указанному пути файл не найден! Укажите правильный путь: ");
  150.                 isIncorrect = true;
  151.             }
  152.         } while (isIncorrect);
  153.  
  154.         return path;
  155.     }
  156.  
  157.     public static int readSizeFromConsole(){
  158.         int size = 0;
  159.         boolean isIncorrect;
  160.         System.out.print("Введите количество вершин графа: ");
  161.         do {
  162.             isIncorrect = false;
  163.             try {
  164.                 size = Integer.parseInt(scanner.nextLine());
  165.             } catch (NumberFormatException e) {
  166.                 System.out.println("Проверьте корректность ввода данных!");
  167.                 isIncorrect = true;
  168.             }
  169.             if (!isIncorrect && (size < MIN_SIZE || size > MAX_SIZE)) {
  170.                 System.out.println("Введите число от " + MIN_SIZE + " до " + MAX_SIZE + "! \n");
  171.                 isIncorrect = true;
  172.             }
  173.         } while (isIncorrect);
  174.         return size;
  175.     }
  176.  
  177.     public static int readSizeFromFile(final String path) {
  178.         int size;
  179.         System.out.println("Происходит чтение количества вершин...");
  180.         try (BufferedReader br = new BufferedReader(new FileReader(path))) {
  181.             size = Integer.parseInt(br.readLine());
  182.         } catch (Exception e) {
  183.             System.out.println("Ошибка при считывании количества вершин из файла!Введите количество с консоли!");
  184.             size = readSizeFromConsole();
  185.         }
  186.         return size;
  187.     }
  188.  
  189.     public static Graph fillGraphFromFile (Graph graph, int size, final String path) throws FileNotFoundException {
  190.         int num1 = 0;
  191.         int num2 = 0;
  192.         int count = 0 ;
  193.         Scanner fr = new Scanner(new File(path));
  194.  
  195.         System.out.println("Чтение вершин ...");
  196.         fr.nextLine();
  197.         while (fr.hasNext()) {
  198.             fr.next();
  199.             count++;
  200.         }
  201.         fr.close();
  202.  
  203.         if (count > size * 2) {
  204.             System.out.println("Ошибка при чтении! Введите с консоли!");
  205.             fillGraphFromConsole(graph, size);
  206.         } else {
  207.             fr = new Scanner(new File(path));
  208.             fr.nextLine();
  209.  
  210.             for (int i = 0; i < size; i++) {
  211.                 try {
  212.                     num1 = fr.nextInt();
  213.                     num2 = fr.nextInt();
  214.                 } catch (Exception e) {
  215.                     System.out.println("Ошибка при считывании вершин из файла!Введите вершины с консоли!");
  216.                     fillGraphFromConsole(graph, size);
  217.                 }
  218.                 if (num1 < MIN_VALUE || num1 > (size - 1) || num2 < MIN_VALUE || num2 > (size - 1)) {
  219.                     System.out.println("Ошибка при считывании вершин из файла! Введите вершины с консоли!");
  220.                     fillGraphFromConsole(graph, size);
  221.                 }
  222.  
  223.             }
  224.         }
  225.         return graph;
  226.     }
  227.  
  228.     public static int getVertices(int i, int numVertices) {
  229.         int number = 0;
  230.         boolean isIncorrect;
  231.         do {
  232.             isIncorrect = false;
  233.             System.out.print("Введите " + i + " вершину графа: ");
  234.             try {
  235.                 number = Integer.parseInt(scanner.nextLine());
  236.             } catch (NumberFormatException e) {
  237.                 System.out.println("Проверьте корректность ввода данных!");
  238.                 isIncorrect = true;
  239.             }
  240.             if (!isIncorrect && (number < MIN_VALUE || number > (numVertices - 1))) {
  241.                 System.out.println("Введите число от " + MIN_VALUE + " до " + (numVertices - 1) + "!");
  242.                 isIncorrect = true;
  243.             }
  244.         } while (isIncorrect);
  245.         return number;
  246.     }
  247.  
  248.     public static Graph fillGraphFromConsole(Graph graph, int amountVertices) {
  249.         int num1, num2;
  250.         System.out.println("Добавьте положение ребер между введенными двумя вершинами (первая вершина 0)");
  251.         for (int i = 0; i < amountVertices; i++) {
  252.             num1 = getVertices(1, amountVertices);
  253.             num2 = getVertices(2, amountVertices);
  254.             graph.addEdge(num1, num2);
  255.         }
  256.         return graph;
  257.     }
  258.  
  259. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement