Advertisement
Alyks

Untitled

Nov 17th, 2019
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.63 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.FileWriter;
  4. import java.io.IOException;
  5. import java.io.RandomAccessFile;
  6. import java.util.Scanner;
  7.  
  8. public class Main {
  9.     static void showVector(double[] vector) {
  10.         for (double el : vector)
  11.             System.out.print(el + " ");
  12.         System.out.println("");
  13.     }
  14.  
  15.     static String showMatrix(double[][] matrix) {
  16.         String matrixString = "";
  17.         for (double[] row : matrix) {
  18.             for (double el : row) {
  19.                 System.out.print(el + " ");
  20.                 matrixString += el + " ";
  21.             }
  22.  
  23.             System.out.println("");
  24.         }
  25.         return matrixString;
  26.     }
  27.  
  28.     static String takeVectorType(RandomAccessFile raf) throws IOException {
  29.         raf.seek(0);
  30.         String vectorType = "";
  31.         boolean notCorrect = true;
  32.         while (vectorType != null && notCorrect) {
  33.             vectorType = raf.readLine();
  34.             if (vectorType != null) {
  35.                 vectorType = new String(vectorType.getBytes("ISO-8859-1"), "windows-1251").toLowerCase();
  36.                 if (vectorType.equals("вектор-строка") || vectorType.equals("вектор-столбец"))
  37.                     notCorrect = false;
  38.             }
  39.         }
  40.  
  41.         return vectorType;
  42.     }
  43.  
  44.     static double[] takeVector(RandomAccessFile raf) throws IOException {
  45.         String line = "";
  46.         double[] vector = {};
  47.  
  48.         int vectorLength = Integer.parseInt(raf.readLine());
  49.         vector = takeRow(raf.readLine(), vectorLength);
  50.  
  51.         return vector;
  52.     }
  53.  
  54.     static double[] takeRow(String str, int size) {
  55.         double[] row = new double[size];
  56.         String[] outputList = str.split("\\s");
  57.         if (outputList.length == size) {
  58.             for (int i = 0; i < size; i++)
  59.                 if (outputList[i].matches("\\d+"))
  60.                     row[i] = Double.parseDouble(outputList[i]);
  61.         } else
  62.             System.out.println("Количество столбцов, введенных в файле, должно совпадать с количеством столбцов в матрице");
  63.         return row;
  64.     }
  65.  
  66.     static double[][] takeMatrixFromFile(RandomAccessFile raf) throws IOException {
  67.         int matrixRows = Integer.parseInt(raf.readLine());
  68.         int matrixCols = Integer.parseInt(raf.readLine());
  69.  
  70.         double[][] matrix = new double[matrixRows][matrixCols];
  71.         for (int i = 0; i < matrixRows; i++) {
  72.             String currString = raf.readLine();
  73.             matrix[i] = takeRow(currString, matrixCols);
  74.         }
  75.  
  76.         return matrix;
  77.     }
  78.  
  79.     static double[][] takeProduct(double[][] matrix, double[] vector, int vectorLength) {
  80.         double[][] product = new double[vectorLength][matrix[0].length];
  81.  
  82.         for (int i = 0; i < product.length; i++) {
  83.             for (int j = 0; j < matrix.length; j++) {
  84.                 for (int k = 0; k < matrix[j].length; k++) {
  85.                     product[i][k] += vector[vectorLength == 1 ? j : i] * matrix[j][k];
  86.                 }
  87.             }
  88.         }
  89.  
  90.         return product;
  91.     }
  92.  
  93.     public static void main(String[] args) {
  94.         Scanner scan = new Scanner(System.in);
  95.         boolean notCorrect = true;
  96.         System.out.println("Данная программа находит произведение вектора на матрицу\n");
  97.         System.out.println("Введите путь до файла");
  98.         String filePath = scan.nextLine();
  99.         int matrixRows = 0, matrixCols = 0, vectorLength = 0;
  100.         String vectorType = "";
  101.         double[][] matrix = {};
  102.         double[] vector = {};
  103.         try {
  104.             RandomAccessFile raf = new RandomAccessFile(filePath, "r");
  105.             matrix = takeMatrixFromFile(raf);
  106.             vectorType = takeVectorType(raf);
  107.             vector = takeVector(raf);
  108.             raf.close();
  109.             notCorrect = false;
  110.         } catch (IOException err) {
  111.             System.out.println("Произошла ошибка при чтении файла. Убедитесь, что такой файл существует, либо проверьте имя файла.");
  112.         }
  113.  
  114.         if (!notCorrect) {
  115.             System.out.println("Матрица:");
  116.             showMatrix(matrix);
  117.             System.out.println("Тип вектора: " + vectorType);
  118.             System.out.println("Вектор:");
  119.             showVector(vector);
  120.  
  121.             matrixRows = matrix.length;
  122.             vectorLength = vector.length;
  123.  
  124.             if ((vectorType.equals("вектор-столбец") && matrixRows != 1) || (vectorType.equals("вектор-строка") && matrixRows != vectorLength)) {
  125.                 System.out.println("Число строк в матрице должно быть равно числу столбцов в векторе");
  126.             } else {
  127.                 vectorLength = vectorType.equals("вектор-столбец") ? vectorLength : 1;
  128.  
  129.                 double[][] product = takeProduct(matrix, vector, vectorLength);
  130.  
  131.                 System.out.println("Результат: ");
  132.                 String result = showMatrix(product);
  133.                 try (FileWriter fw = new FileWriter("output.txt", false)) {
  134.                     fw.write("Результат: " + result);
  135.                 } catch (IOException err) {
  136.                     System.out.println("Произошла ошибка при попытке записи результата в файл");
  137.                 }
  138.                 System.out.println("Результат сохранен в файл output.txt");
  139.             }
  140.         }
  141.     }
  142. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement