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 String ANSI_RED = "\u001B[31m";
- private static final String ANSI_RESET = "\u001b[0m";
- private static final String ANSI_YELLOW = "\u001B[33m";
- private static final String ANSI_CYAN = "\u001B[36m";
- private static final int MIN_VALUE = 2;
- private static final int MAX_VALUE = 99;
- private static final int MIN_CHOICE_VALUE = 1;
- private static final int MAX_CHOICE_VALUE = 2;
- public static void main(String[] args) {
- System.out.println(ANSI_YELLOW + "Эта программа преобразовывает списки инцидентности в матрицу инциденций.");
- System.out.println(ANSI_CYAN + "\n(нумерация ребер: сначала ребра первой вершины, потом второй и т.д.)");
- System.out.println("(в файле в первой строке должно быть количество вершин, а в каждой\n" +
- "последующей - инцидентные вершины для каждой вершины, начиная с 1-й)" + ANSI_RESET);
- System.out.println("\nВыберите способ ввода: (1 - Консоль) (2 - Файл)");
- System.out.print("Выбор: ");
- int choice = enterNumber(MIN_CHOICE_VALUE, MAX_CHOICE_VALUE);
- IncidenceList incidenceLists = enterIncidenceLists(choice);
- System.out.println("Списки инцидентности:");
- System.out.println(incidenceLists.toString());
- int[][] incidenceMatrix = incidenceLists.toIncidenceMatrix();
- System.out.println("Выберите способ вывода: (1 - Консоль) (2 - Файл)");
- System.out.print("Выбор: ");
- choice = enterNumber(MIN_CHOICE_VALUE, MAX_CHOICE_VALUE);
- displayMatrix(choice, incidenceMatrix);
- scanner.close();
- }
- 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("\nВведите количество вершин: ");
- int amountVertex = enterNumber(MIN_VALUE, MAX_VALUE);
- for (int i = 0; i < amountVertex; i++) {
- System.out.println("Введите список инцидентности " + (i + 1) + "-й вершины: ");
- ArrayList<Integer> listOfVertex = checkPrevLists(lists, i + 1);
- for (int j = i + 1; j < amountVertex; j++) {
- System.out.println("Добавить в список " + (j + 1) + "-ю вершину? (1 - Да) (2 - Нет)");
- byte choice = enterNumber(MIN_CHOICE_VALUE, MAX_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("\nВведите путь к файлу: ");
- 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 + "Ошибка! Кол-во вершин не является целым числом или не входит в диапзон [2; 99]!\n" +
- ANSI_RESET + "Введите путь к файлу с корректными данными: ");
- 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 + "Ошибка! Списки инцидентности составлены неправильно!" +
- ANSI_RESET + "\nВведите путь к файлу с корректными данными: ");
- isIncorrect = true;
- }
- } else {
- System.out.print(ANSI_RED + "Ошибка! Списки инцидентности составлены неправильно!" +
- ANSI_RESET + "\nВведите путь к файлу с корректными данными: ");
- isIncorrect = true;
- }
- }
- if (!isIncorrect && amountVertexes != numOfList) {
- System.out.print(ANSI_RED + "Ошибка! Кол-во вершин и списков не совпадает!" +
- ANSI_RESET + "\nВведите путь к файлу с корректными данными: ");
- isIncorrect = true;
- }
- }
- } catch (IOException e) {
- System.out.print(ANSI_RED + "Ошибка ввода! " + ANSI_RESET + "Введите путь к файлу с корректными данными: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return new IncidenceList(fileList);
- }
- private static byte enterNumber(final int min, final int max) {
- boolean isIncorrect;
- byte num = 0;
- do {
- isIncorrect = false;
- try {
- num = Byte.parseByte(scanner.nextLine());
- } catch (NumberFormatException e) {
- System.out.print(ANSI_RED + "Ошибка! " + ANSI_RESET + "Введите целое натуральное число: ");
- isIncorrect = true;
- }
- if (!isIncorrect && (num > max || num < min)) {
- System.out.print(ANSI_RED + "Ошибка! " + ANSI_RESET + "Введите число в диапазоне [" + 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("Введите путь к файлу: ");
- 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 + "Ошибка доступа! " + ANSI_RESET + "Введите путь к доступному файлу: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- System.out.println("\nРезультат успешно записан в файл!");
- }
- private static void displayMatrixToConsole(final int[][] matrix) {
- System.out.println("Матрица инциденций: ");
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[i].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 + "Ошибка! Файл не существует! " + ANSI_RESET + "Повторите ввод: ");
- isIncorrect = true;
- }
- if (!isIncorrect && !path.endsWith(".txt")) {
- System.out.print(ANSI_RED + "Ошибка! Файл не является текстовым! " + ANSI_RESET + "Повторите ввод: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return path;
- }
- }
- 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(" -> ");
- }
- if (sb.toString().endsWith(" -> ")) {
- sb.delete(sb.length() - 4, sb.length());
- }
- sb.append("\n");
- }
- } else {
- sb.append("[]");
- }
- return sb.toString();
- }
- public int[][] toIncidenceMatrix() {
- int amountVertexes = list.size();
- int amountEdges = countEdges();
- int numberOfEdge = 0;
- int[][] matrix = new int[amountVertexes][amountEdges];
- for (int i = 0; i < list.size(); i++) {
- ArrayList<Integer> incidenceList = list.get(i);
- for (int j = 0; j < incidenceList.size(); j++) {
- int vertex = incidenceList.get(j);
- if (vertex > i + 1) {
- matrix[i][numberOfEdge] = 1;
- matrix[vertex - 1][numberOfEdge] = 1;
- numberOfEdge++;
- }
- }
- }
- return matrix;
- }
- private int countEdges() {
- int edges = 0;
- for (int i = 0; i < list.size(); i++) {
- ArrayList<Integer> incidenceList = list.get(i);
- for (int j = 0; j < incidenceList.size(); j++) {
- if (incidenceList.get(j) > i + 1) {
- edges++;
- }
- }
- }
- return edges;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement