Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.util.Scanner;
- public class Main {
- private static final Scanner scan = new Scanner(System.in);
- private static Node head = new Node();
- private static int[] prevArr = null;
- public static void main(String[] args) {
- welcome();
- int source = takeInputSource();
- int[][] matrix = takeMatrix(source);
- createList(matrix);
- System.out.print("Выберите номер вершины(" + 1 + ", " + matrix.length + "): ");
- int Vertex = takeInt(1, matrix.length);
- int[] arr = findArray(Vertex, matrix.length);
- source = takeOutputSource();
- output(source, arr);
- }
- private static int[] findArray(int vertex, int length) {
- int[] arr = new int[length];
- for (int i = 0; i < length; i++) {
- arr[i] = 10000;
- }
- arr[vertex - 1] = 0;
- boolean areSame;
- do {
- Node temp = head;
- while (temp != null) {
- if (arr[temp.getToVertex() - 1] > arr[temp.getFromVertex() - 1] + 1) {
- arr[temp.getToVertex() - 1] = arr[temp.getFromVertex() - 1] + 1;
- }
- temp = temp.getNext();
- }
- areSame = arr == prevArr;
- prevArr = arr;
- } while (!isAllFind(arr) && !areSame);
- return arr;
- }
- private static boolean isAllFind(int[] arr) {
- boolean answer = true;
- int i = 0;
- while (answer && (i < arr.length)) {
- if (arr[i] == 10000) {
- answer = false;
- }
- i++;
- }
- return answer;
- }
- public static void welcome() {
- System.out.println();
- System.out.println("ВAC ПРИВЕТСТВУЕТ ПРОГРАММА ПЕРЕВОДА МАТРИЦЫ СМЕЖНОСТИ В СПИСКИ ИНЦИНДЕНЦИЙ");
- }
- public static int takeInputSource() {
- int source = 0;
- boolean isInCorrect;
- do {
- isInCorrect = false;
- System.out.print("\nВыберите источник матрицы:\n1. Файл\n2. Консоль\nВаш выбор: ");
- try {
- source = Integer.parseInt(scan.nextLine());
- } catch (NumberFormatException e) {
- System.out.print("\nОшибка! Число введено некорректно.\n");
- isInCorrect = true;
- }
- if (!isInCorrect && (source != 2 && source != 1)) {
- System.out.print("\nОшибка! Число введено некорректно.\n");
- isInCorrect = true;
- }
- } while(isInCorrect);
- return source;
- }
- public static int takeOutputSource() {
- int source = 0;
- boolean isInCorrect;
- do {
- isInCorrect = false;
- System.out.print("\nВыберите способ вывода:\n1. Файл\n2. Консоль\nВаш выбор: ");
- try {
- source = Integer.parseInt(scan.nextLine());
- } catch (NumberFormatException e) {
- System.out.print("\nОшибка! Число введено некорректно.\n");
- isInCorrect = true;
- }
- if (!isInCorrect && (source != 2 && source != 1)) {
- System.out.print("\nОшибка! Число введено некорректно.\n");
- isInCorrect = true;
- }
- } while(isInCorrect);
- return source;
- }
- private static String takeInPath() {
- String path;
- boolean isIncorrect;
- System.out.print("\nВведите путь к файлу: ");
- do {
- isIncorrect = false;
- path = scan.nextLine();
- if (Files.notExists(Path.of(path))) {
- System.out.print("Файл не найден\nВведите путь к файлу: ");
- isIncorrect = true;
- }
- if (!isIncorrect && (!path.endsWith(".txt"))) {
- System.out.print("Файл найден, но он нетипа \".txt\"\nВведите путь к файлу: ");
- isIncorrect = true;
- }
- }while (isIncorrect);
- return path;
- }
- static String takeOutPath() {
- String path;
- boolean isIncorrect;
- System.out.print("\nВведите путь к файлу: ");
- do {
- isIncorrect = false;
- path = scan.nextLine();
- if (!path.endsWith(".txt")) {
- System.out.print("Это должен быть \".txt\" файл\nВведите путь к файлу: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return path;
- }
- private static int takeInt(final int MIN_VALUE, final int MAX_VALUE) {
- int num = 0;
- boolean isInCorrect;
- do {
- isInCorrect = false;
- try {
- num = Integer.parseInt(scan.nextLine());
- } catch (NumberFormatException e) {
- System.out.print("Ошибка! Введите число повторно: ");
- isInCorrect = true;
- }
- if (!isInCorrect && (num < MIN_VALUE || num > MAX_VALUE)) {
- System.out.print("Ошибка! Введите число из диапазона[" + MIN_VALUE + "," + MAX_VALUE + "]: ");
- isInCorrect = true;
- }
- } while(isInCorrect);
- return num;
- }
- private static int[][] takeMatrix(int source) {
- int[][] matrix;
- if (source == 1) {
- String path = takeInPath();
- matrix = takeMatrixFromFile(path);
- while (matrix == null) {
- path = takeInPath();
- matrix = takeMatrixFromFile(path);
- }
- }
- else {
- System.out.print("\nВведите количество вершин графа: ");
- int size = takeInt(2,13);
- matrix = takeMatrixFromConsole(size);
- }
- return matrix;
- }
- private static int[][] takeMatrixFromFile(final String path) {
- int[][] matrix = null;
- int size = 0;
- int lineCounter = 0;
- boolean isCorrect = true;
- try(BufferedReader reader = new BufferedReader(new FileReader(path))) {
- size = Integer.parseInt(reader.readLine());
- lineCounter++;
- if ((size < 2) || (size > 13)) {
- isCorrect = false;
- System.out.println("Некорректные данные!!");
- }
- else {
- matrix = new int[size][size];
- while (isCorrect && lineCounter < size + 1) {
- try {
- String[] line = reader.readLine().split(" ");
- for (int i = 0; i < line.length; i++) {
- matrix[lineCounter - 1][i] = Integer.parseInt(line[i]);
- if ((lineCounter - 1 == i) && (matrix[lineCounter - 1][i] == 1)) {
- System.out.println("\nМатрица заполнена неверно!");
- isCorrect = false;
- }
- }
- lineCounter++;
- }
- catch (Exception e) {
- System.out.println("\nНекорректные данные!!");
- isCorrect = false;
- }
- }
- }
- }catch (Exception e) {
- System.out.println("\nОшибка ввода/вывода!!");
- isCorrect = false;
- }
- if (!isCorrect || (lineCounter != size + 1)) {
- matrix = null;
- }
- return matrix;
- }
- private static int[][] takeMatrixFromConsole(final int size) {
- int[][] matrix = new int[size][size];
- for (int i = 0; i < size; i++) {
- for (int j = 0; j < size; j++) {
- matrix[i][j] = 0;
- }
- }
- for (int i = 0; i < size; i++) {
- int j = -1;
- while (j != 0) {
- System.out.print("\nВведите номер вершины, с которой связана вершина " + (i + 1) + ". Если хотите прекратить, введите 0: ");
- j = takeInt(0, size);
- if (j != 0) {
- if ( matrix[i][j - 1] == 1) {
- System.out.println("Эта вершина уже записана");
- j = -1;
- }
- else {
- System.out.println("Связь вершин " + (i + 1) + " и " + j + " записана успешно");
- matrix[i][j-1] = 1;
- matrix[j-1][i] = 1;
- }
- }
- }
- }
- return matrix;
- }
- private static void createList(int[][] matrix) {
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[0].length; j++) {
- if (matrix[i][j] == 1){
- addNode(i+1, j+1);
- }
- }
- }
- }
- private static void addNode(int fromVertex, int toVertex) {
- Node newNode = new Node();
- newNode.setFromVertex(fromVertex);
- newNode.setToVertex(toVertex);
- if ((head == null) || (head.getFromVertex() == 0)) {
- head = newNode;
- }
- else {
- Node currentNode = head;
- while (currentNode.getNext() != null) {
- currentNode = currentNode.getNext();
- }
- currentNode.setNext(newNode);
- }
- }
- private static void output(int source, int[] arr) {
- if (source == 1) {
- String path = takeOutPath();
- outputToFile(path, arr);
- }
- else {
- outputToConsole(arr);
- }
- }
- private static void outputToConsole(int[] arr) {
- System.out.println("Список расстояний:");
- for (int i = 0; i < arr.length; i++) {
- System.out.println(i + 1 + ": " + arr[i]);
- }
- }
- static void outputToFile(final String path, final int[] arr) {
- try (FileWriter fw = new FileWriter(path)) {
- fw.write("Список расстояний:\n");
- for (int i = 0; i < arr.length; i++) {
- fw.write(i + 1 + ": " + arr[i] + "\n");
- }
- System.out.println("Запись в файл прошла в штатном режиме :)");
- } catch (Exception e) {
- System.out.println("Ошибка при записи в файл!\nЗапись произведена в консоль:\n");
- outputToConsole(arr);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement