Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.*;
- import java.util.ArrayList;
- import java.util.Scanner;
- public class Main {
- private static final Scanner scanner = new Scanner(System.in);
- private static final int MIN_VALUE = 1;
- private static final int MAX_VALUE = 9;
- private static final int CHOICE_VALUE = 2;
- public static final String ANSI_RED = "\u001B[31m";
- public static final String ANSI_GREEN = "\u001B[32m";
- public static final String ANSI_YELLOW = "\u001B[33m";
- public static final String ANSI_CYAN = "\u001B[36m";
- public static void main(String[] args) {
- System.out.println(ANSI_GREEN + "Эта программа преобразовывает списки инцидентности в матрицу смежности.");
- System.out.println(ANSI_CYAN + "\nВыберите способ ввода: (1 - Консоль) (2 - Файл)");
- System.out.print(ANSI_CYAN + "Выбор: ");
- int choice = enterNumber(MIN_VALUE, CHOICE_VALUE);
- IncidenceList incidenceLists = enterIncidenceLists(choice);
- System.out.println(ANSI_YELLOW + "Списки инцидентности:");
- System.out.println(incidenceLists.toString());
- int[][] adjacencyMatrix = incidenceLists.toMatrix();
- System.out.println(ANSI_CYAN + "Выберите способ вывода: (1 - Консоль) (2 - Файл)");
- System.out.print(ANSI_CYAN + "Выбор: ");
- choice = enterNumber(MIN_VALUE, CHOICE_VALUE);
- displayMatrix(choice, adjacencyMatrix);
- }
- private static IncidenceList enterIncidenceLists(final int choice) {
- IncidenceList incidenceList = new IncidenceList();
- if (choice == 1) {
- incidenceList = readListFromConsole();
- } else if (choice == 2) {
- incidenceList = readListFromFile();
- }
- return incidenceList;
- }
- private static IncidenceList readListFromConsole() {
- ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
- System.out.print(ANSI_CYAN + "Введите количество вершин: ");
- int amountVertex = enterNumber(MIN_VALUE, MAX_VALUE);
- for (int i = 0; i < amountVertex; i++) {
- System.out.println(ANSI_CYAN + "Введите список инцидентности " + (i + 1) + "-й вершины: ");
- ArrayList<Integer> listOfVertex = checkPrevLists(lists, i + 1);
- for (int j = i + 1; j < amountVertex; j++) {
- System.out.println(ANSI_CYAN + "Добавить в список " + (j + 1) + "-ю вершину? (1 - Да) (2 - Нет)");
- int choice = enterNumber(MIN_VALUE, CHOICE_VALUE);
- if (choice == 1) {
- listOfVertex.add(j + 1);
- }
- }
- lists.add(listOfVertex);
- }
- return new IncidenceList(lists);
- }
- private static ArrayList<Integer> checkPrevLists(final ArrayList<ArrayList<Integer>> lists, final int currentVertex) {
- ArrayList<Integer> listOfVertex = new ArrayList<>();
- for (int i = 0; i < lists.size(); i++) {
- for (int j = 0; j < lists.get(i).size(); j++) {
- if (lists.get(i).get(j) == currentVertex) {
- listOfVertex.add(i + 1);
- }
- }
- }
- return listOfVertex;
- }
- private static boolean isCorrectLine(String line, final int vertex, final int max) {
- boolean isCorrect = true;
- String[] strArr = line.split(" ");
- try {
- for (String strValue: strArr) {
- int num = Integer.parseInt(strValue);
- if (num > max || num < 1 || num == vertex) {
- isCorrect = false;
- }
- }
- } catch (NumberFormatException e) {
- isCorrect = false;
- }
- return isCorrect;
- }
- private static boolean isCorrectList(final int numOfList, final ArrayList<Integer> list, final ArrayList<ArrayList<Integer>> incidenceLists) {
- boolean isCorrect = true;
- for (int i = 0; i < list.size(); i++) {
- int vertex = list.get(i);
- if (numOfList > vertex) {
- boolean isContains = false;
- ArrayList<Integer> checkingList = incidenceLists.get(vertex - 1);
- for (int j = 0; j < checkingList.size(); j++) {
- if (checkingList.get(j) == numOfList) {
- isContains = true;
- }
- }
- if (!isContains) {
- isCorrect = false;
- }
- }
- }
- return isCorrect;
- }
- private static ArrayList<Integer> getListFromLine(String line) {
- ArrayList<Integer> list = new ArrayList<>();
- String[] strArr = line.split(" ");
- for (String num: strArr) {
- list.add(Integer.parseInt(num));
- }
- return list;
- }
- private static IncidenceList readListFromFile() {
- ArrayList<ArrayList<Integer>> fileList = new ArrayList<>();
- boolean isIncorrect;
- System.out.print(ANSI_CYAN + "Введите путь к файлу: ");
- do {
- isIncorrect = false;
- fileList.clear();
- String path = enterPathToFile();
- try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
- String line = reader.readLine();
- if (!(line.matches("^\\d{1,2}") && Integer.parseInt(line) >= MIN_VALUE)) {
- System.out.print(ANSI_RED + "Ошибка! Кол-во вершин не является целым числом или не входит в диапзон [1; 99]!\n" +
- "Введите путь к файлу с корректными данными: ");
- isIncorrect = true;
- } else {
- int amountVertexes = Integer.parseInt(line);
- int numOfList = 0;
- while ((line = reader.readLine()) != null && !isIncorrect) {
- numOfList++;
- if (isCorrectLine(line, numOfList, amountVertexes)) {
- ArrayList<Integer> list = getListFromLine(line);
- if (isCorrectList(numOfList, list, fileList)) {
- fileList.add(list);
- } else {
- System.out.print(ANSI_RED + "Ошибка! Списки инцидентности составлены неправильно!\nВведите путь к файлу с корректными данными: ");
- isIncorrect = true;
- }
- } else {
- System.out.print(ANSI_RED + "Ошибка! Списки инцидентности составлены неправильно!\nВведите путь к файлу с корректными данными: ");
- isIncorrect = true;
- }
- }
- if (!isIncorrect && amountVertexes != numOfList) {
- System.out.print(ANSI_RED + "Ошибка! Кол-во вершин и списков не совпадает!\nВведите путь к файлу с корректными данными: ");
- isIncorrect = true;
- }
- }
- } catch (IOException e) {
- System.out.print(ANSI_RED + "Ошибка ввода! Введите путь к файлу с корректными данными: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return new IncidenceList(fileList);
- }
- private static int enterNumber(final int min, final int max) {
- boolean isIncorrect;
- int num = 0;
- do {
- isIncorrect = false;
- try {
- num = Integer.parseInt(scanner.nextLine());
- } catch (NumberFormatException e) {
- System.out.print(ANSI_RED + "Ошибка! Введите целое натуральное число: ");
- isIncorrect = true;
- }
- if (!isIncorrect && (num > max || num < min)) {
- System.out.print(ANSI_RED + "Ошибка! Введите число в диапазоне [" + min + "; " + max + "]: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return num;
- }
- private static void displayMatrix(final int choice, final int[][] matrix) {
- if (choice == 1) {
- displayMatrixToConsole(matrix);
- } else if (choice == 2) {
- saveMatrixToFile(matrix);
- }
- }
- private static void saveMatrixToFile(final int[][] matrix) {
- boolean isIncorrect;
- System.out.print(ANSI_CYAN + "Введите путь к файлу: ");
- do {
- isIncorrect = false;
- String path = enterPathToFile();
- try (BufferedWriter bufWriter = new BufferedWriter(new FileWriter(path))) {
- bufWriter.write("Матрица смежности: \n");
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix.length; j++) {
- bufWriter.write(matrix[i][j] + " ");
- }
- bufWriter.write("\n");
- }
- } catch (IOException e) {
- System.out.print(ANSI_RED + "Ошибка доступа! Введите путь к доступному файлу: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- System.out.println(ANSI_GREEN + "\nРезультат успешно записан в файл!");
- }
- private static void displayMatrixToConsole(final int[][] matrix) {
- System.out.println(ANSI_YELLOW + "Матрица смежности: ");
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix.length; j++) {
- System.out.print(matrix[i][j] + " ");
- }
- System.out.println();
- }
- }
- private static String enterPathToFile() {
- boolean isIncorrect;
- String path;
- do {
- isIncorrect = false;
- path = scanner.nextLine();
- File textFile = new File(path);
- if (!textFile.exists()) {
- System.out.print(ANSI_RED + "Ошибка! Файл не существует! Повторите ввод: ");
- isIncorrect = true;
- }
- if (!isIncorrect && !path.endsWith(".txt")) {
- System.out.print(ANSI_RED + "Ошибка! Файл не является текстовым! Повторите ввод: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return path;
- }
- }
- //IncidenceList Class
- package com.company;
- import java.util.ArrayList;
- public class IncidenceList {
- private ArrayList<ArrayList<Integer>> list;
- public IncidenceList() {
- this.list = new ArrayList<>();
- }
- public IncidenceList(final ArrayList<ArrayList<Integer>> list) {
- this.list = list;
- }
- public int size() {
- return this.list.size();
- }
- public boolean isEmpty() {
- return list.size() == 0;
- }
- public String toString() {
- StringBuilder sb = new StringBuilder();
- if (!isEmpty()) {
- for (int i = 0; i < list.size(); i++) {
- sb.append(i + 1).append(": ");
- ArrayList<Integer> cols = list.get(i);
- for (int j = 0; j < cols.size(); j++) {
- sb.append(cols.get(j)).append(" -> ");
- }
- sb.delete(sb.length() - 4, sb.length());
- sb.append("\n");
- }
- } else {
- sb.append("[]");
- }
- return sb.toString();
- }
- public int[][] toMatrix() {
- int amountVertexes = list.size();
- int[][] matrix = new int[amountVertexes][amountVertexes];
- for (int i = 0; i < amountVertexes; i++) {
- for (int j = 0; j < list.get(i).size(); j++) {
- int vertex = list.get(i).get(j);
- matrix[i][vertex - 1] = 1;
- }
- }
- return matrix;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement