negtab

java

Nov 17th, 2024
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.91 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.io.*;
  3.  
  4. public class Main
  5. {
  6. public static void printTask()
  7. {
  8. System.out.println("Эта программа сортирует массив чисел метод слияния");
  9. }
  10. public static Scanner scanner = new Scanner(System.in);
  11. public static String readPathFile()
  12. {
  13. String pathToFile;
  14. boolean isInCorrect;
  15. do {
  16. isInCorrect = false;
  17. System.out.print("Введите путь к файлу с расширением.txt: ");
  18. pathToFile = scanner.nextLine();
  19. if (pathToFile.length() < 5 || !pathToFile.endsWith(".txt")) {
  20. System.out.println("Расширение файла не .txt!\n");
  21. isInCorrect = true;
  22. }
  23. } while (isInCorrect);
  24. return pathToFile;
  25. }
  26.  
  27. public static boolean isNotExists(String pathToFile)
  28. {
  29. File file = new File(pathToFile);
  30. return !file.exists();
  31. }
  32.  
  33. public static boolean isNotAbleToReading(String pathToFile)
  34. {
  35. File file = new File(pathToFile);
  36. return !file.canRead();
  37. }
  38.  
  39. public static boolean isNotAbleToWriting(String pathToFile)
  40. {
  41. File file = new File(pathToFile);
  42. return !file.canWrite();
  43. }
  44.  
  45. public static boolean isEmpty(String pathToFile) throws IOException
  46. {
  47. boolean isEmpty;
  48.  
  49. isEmpty = false;
  50.  
  51. try (FileReader fileReader = new FileReader(pathToFile))
  52. {
  53. isEmpty = fileReader.read() == -1;
  54. }
  55. catch (IOException exception)
  56. {
  57. exception.printStackTrace();
  58. }
  59. return isEmpty;
  60. }
  61.  
  62. public static String getFileNormalReading() throws IOException
  63. {
  64. String pathToFile;
  65. boolean isInCorrect;
  66. do
  67. {
  68. isInCorrect = false;
  69. pathToFile = readPathFile();
  70. if (isNotExists(pathToFile))
  71. {
  72. isInCorrect = true;
  73. System.out.println("Проверьте корректность ввода пути к файлу!\n");
  74. }
  75. if (isInCorrect || isNotAbleToReading(pathToFile))
  76. {
  77. isInCorrect = true;
  78. System.out.println("Файл закрыт для чтения!\n");
  79. }
  80. if (isInCorrect || isEmpty(pathToFile))
  81. {
  82. isInCorrect = true;
  83. System.out.println("Файл пуст!\n");
  84. }
  85. }
  86. while (isInCorrect);
  87.  
  88. return pathToFile;
  89. }
  90.  
  91. public static String getFileNormalWriting() throws IOException
  92. {
  93. String pathToFile;
  94. boolean isInCorrect;
  95. do
  96. {
  97. isInCorrect = false;
  98. pathToFile = readPathFile();
  99. if (isNotExists(pathToFile))
  100. {
  101. isInCorrect = true;
  102. System.out.println("Проверьте корректность ввода пути к файлу!\n");
  103. }
  104. if (isInCorrect || isNotAbleToWriting(pathToFile))
  105. {
  106. isInCorrect = true;
  107. System.out.println("Файл закрыт для записи!\n");
  108. }
  109. }
  110. while (isInCorrect);
  111.  
  112. return pathToFile;
  113. }
  114.  
  115. public static int inputIntFromConsole(int min, int max)
  116. {
  117. int inputNumber;
  118. boolean isInCorrect;
  119.  
  120. inputNumber = 0;
  121.  
  122. do
  123. {
  124. isInCorrect = false;
  125. try
  126. {
  127. inputNumber = Integer.parseInt(scanner.nextLine());
  128. }
  129. catch (NumberFormatException exception)
  130. {
  131. isInCorrect = true;
  132. }
  133. if (isInCorrect || inputNumber < min || inputNumber > max)
  134. {
  135. System.out.println("Неверный ввод");
  136. isInCorrect = true;
  137. }
  138. }
  139. while (isInCorrect);
  140.  
  141. return inputNumber;
  142. }
  143.  
  144. public static int inputIntWithText(String message, int min, int max)
  145. {
  146. int inputNumber;
  147. boolean isInCorrect;
  148.  
  149. inputNumber = 0;
  150.  
  151. do
  152. {
  153. System.out.printf(message + " от " + min + " до " + max + ": ");
  154. isInCorrect = false;
  155. try
  156. {
  157. inputNumber = Integer.parseInt(scanner.nextLine());
  158. }
  159. catch (NumberFormatException exception)
  160. {
  161. isInCorrect = true;
  162. }
  163. if (isInCorrect || inputNumber < min || inputNumber > max)
  164. {
  165. System.out.println("Неверный ввод");
  166. isInCorrect = true;
  167. }
  168. }
  169. while (isInCorrect);
  170.  
  171. return inputNumber;
  172. }
  173.  
  174. public static int[] inputArrayOfIntFromConsole(String message, int size, int min, int max)
  175. {
  176. boolean isInCorrect;
  177. int[] array;
  178.  
  179. array = new int[size];
  180.  
  181. for (int i = 0; i < size; i ++)
  182. {
  183. do
  184. {
  185. System.out.printf(message + " от " + min + " до " + max + ": ");
  186. isInCorrect = false;
  187. try
  188. {
  189. array[i] = Integer.parseInt(scanner.nextLine());
  190. }
  191. catch (NumberFormatException exception)
  192. {
  193. isInCorrect = true;
  194. }
  195. if (isInCorrect || array[i] < min || array[i] > max)
  196. {
  197. System.out.println("Неверный ввод");
  198. isInCorrect = true;
  199. }
  200. }
  201. while (isInCorrect);
  202. }
  203.  
  204. return array;
  205. }
  206.  
  207. public static int[] ReadInputArray(int choose, int minSize, int maxSize, int min, int max)
  208. {
  209. String pathToFile = " ";
  210. int[] inputArray = new int[1];
  211. if(choose == 2)
  212. {
  213. String[] s;
  214. int[]array = new int[1];
  215. int size = 0;
  216. int counter = 0;
  217. boolean isInCorrect;
  218. try
  219. {
  220. pathToFile = getFileNormalReading();
  221. }
  222. catch (IOException exception)
  223. {
  224. exception.printStackTrace();
  225. }
  226.  
  227. try (BufferedReader reader = new BufferedReader(new FileReader(pathToFile)))
  228. {
  229. isInCorrect = false;
  230. try
  231. {
  232. size = Integer.parseInt(reader.readLine());
  233. }
  234. catch (NumberFormatException exception)
  235. {
  236. isInCorrect = true;
  237. }
  238. if (isInCorrect || size < minSize || size > maxSize)
  239. {
  240. System.out.println("Неверно введено количество точек первой числовой последовательности, введите через консоль: ");
  241. size = inputIntFromConsole(minSize, maxSize);
  242. }
  243.  
  244. inputArray = new int[size + 1];
  245. inputArray[0] = size;
  246. s = reader.readLine().split(" ");
  247. if(s.length == size)
  248. {
  249. for (int i = 0; i < size; i ++)
  250. {
  251. isInCorrect = false;
  252. try
  253. {
  254. inputArray[i + 1] = Integer.parseInt(s[i]);
  255. }
  256. catch (NumberFormatException exception)
  257. {
  258. isInCorrect = true;
  259. }
  260. if (isInCorrect || inputArray[i + 1] < min || inputArray[i + 1] > max)
  261. {
  262. System.out.println("Неверный ввод элемента первой числовой последовательности, введите через консоль: ");
  263. array[i] = inputIntFromConsole(min, max);
  264. }
  265. }
  266. isInCorrect = false;
  267. }
  268.  
  269. if(s.length < size)
  270. {
  271. int diver = size - s.length;
  272. for (int i = 0; i < size - diver; i ++)
  273. {
  274. isInCorrect = false;
  275. try
  276. {
  277. inputArray[i + 1] = Integer.parseInt(s[i]);
  278. }
  279. catch (NumberFormatException exception)
  280. {
  281. isInCorrect = true;
  282. }
  283. if (isInCorrect || inputArray[i + 1] < min || inputArray[i + 1] > max)
  284. {
  285. System.out.println("Неверный ввод элемента первой числовой последовательности, введите через консоль: ");
  286. inputArray[i + 1] = inputIntFromConsole(min, max);
  287. }
  288. }
  289. isInCorrect = false;
  290. System.out.println("В файле не хватает элеметнов для массива");
  291. for(int i = 0; i < diver; i ++)
  292. {
  293. System.out.print("Введите " + (i + s.length + 1) + " элемент массива: ");
  294. inputArray[i + s.length + 1] = inputIntFromConsole(min, max);
  295. }
  296. }
  297. }
  298. catch (IOException exception)
  299. {
  300. exception.printStackTrace();
  301. }
  302. }
  303. return inputArray;
  304. }
  305.  
  306. public static int inputInt(int choose, int[] inputArray)
  307. {
  308. int inputNum = 0;
  309. if(choose == 1)
  310. {
  311. inputNum = inputIntWithText("Введите количество элементов числовой последовательности",1, 100);
  312. }
  313. else
  314. {
  315. inputNum = inputArray[0];
  316. }
  317. return inputNum;
  318. }
  319.  
  320. public static int[] inputArrayOfInt(int choose, int[] inputArray, int size, int period)
  321. {
  322. int[] array = new int[size];
  323. if(choose == 1)
  324. {
  325. array = inputArrayOfIntFromConsole("Введите члены числовой последовательности",size, -10000, 10000);
  326. }
  327. else
  328. {
  329. if(period == 1)
  330. {
  331. for(int i = 0; i < size; i ++)
  332. array[i] = inputArray[i + 2];
  333. }
  334. else
  335. {
  336. for(int i = 0; i < size; i ++)
  337. array[i] = inputArray[i + 1];
  338. }
  339.  
  340. }
  341. return array;
  342. }
  343.  
  344. public static void printArray(int[] array)
  345. {
  346. for(int i = 0; i < array.length; i++)
  347. {
  348. System.out.print(array[i] + " ");
  349. }
  350. }
  351.  
  352. public static void writeSolveToFile(String pathToFile, int[] array)
  353. {
  354. System.out.println("Полученная числовая последовательность записана в файл и равна: ");
  355. printArray(array);
  356. try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(pathToFile)))
  357. {
  358. fileWriter.write("Полученная числовая последовательность: ");
  359. for(int i = 0; i < array.length; i++)
  360. {
  361. fileWriter.write(array[i]);
  362. }
  363. fileWriter.close();
  364. }
  365. catch (IOException exception)
  366. {
  367. exception.printStackTrace();
  368. }
  369. }
  370.  
  371. public static void output(int outputChoice, int[] array)
  372. {
  373. if (outputChoice == 1)
  374. {
  375. System.out.print("Полученная последовательность: ");
  376. printArray(array);
  377. }
  378. else if (outputChoice == 2)
  379. {
  380. String pathToFile = " ";
  381. try
  382. {
  383. pathToFile = getFileNormalWriting();
  384. writeSolveToFile(pathToFile, array);
  385. }
  386. catch (IOException exception)
  387. {
  388. exception.printStackTrace();
  389. }
  390. }
  391. }
  392.  
  393. public static void merge(int[] arr, int left, int mid, int right) {
  394. int sizeL = mid - left + 1;
  395. int sizeR = right - mid;
  396.  
  397. int[] leftArray = new int[sizeL];
  398. int[] rightArray = new int[sizeR];
  399.  
  400. for (int i = 0; i < sizeL; i++)
  401. leftArray[i] = arr[left + i];
  402. for (int i = 0; i < sizeR; i++)
  403. rightArray[i] = arr[mid + 1 + i];
  404.  
  405. int indexL = 0, indexR = 0, index = left;
  406.  
  407. while (indexL < sizeL && indexR < sizeR) {
  408. arr[index++] = (leftArray[indexL] <= rightArray[indexR]) ? leftArray[indexL++] : rightArray[indexR++];
  409. }
  410.  
  411. while (indexL < sizeL) {
  412. arr[index++] = leftArray[indexL++];
  413. }
  414.  
  415. while (indexR < sizeR) {
  416. arr[index++] = rightArray[indexR++];
  417. }
  418. }
  419.  
  420. public static void mergeSort(int[] arr, int size) {
  421. for (int currentSize = 1; currentSize < size; currentSize *= 2) {
  422. for (int leftStart = 0; leftStart < size - 1; leftStart += 2 * currentSize) {
  423. int mid = Math.min(leftStart + currentSize - 1, size - 1);
  424. int rightEnd = Math.min(leftStart + 2 * currentSize - 1, size - 1);
  425.  
  426. merge(arr, leftStart, mid, rightEnd);
  427. }
  428. }
  429. }
  430.  
  431. public static int chooseTheInput()
  432. {
  433. System.out.print("Выберите ввод из консоли(1) или из файла(2): ");
  434. return inputIntFromConsole(1, 2);
  435. }
  436.  
  437. public static int chooseTheOutput()
  438. {
  439. System.out.print("Выберите вывод в консоль(1) или в файл(2): ");
  440. return inputIntFromConsole(1, 2);
  441. }
  442.  
  443. public static void main(String[] args)
  444. {
  445. int size = 0;
  446. int inputChoose = 0;
  447. int outputChoose = 0;
  448. int[] array = new int[1];
  449. int[] inputArray = new int[1];
  450.  
  451. printTask();
  452. inputChoose = chooseTheInput();
  453. inputArray = ReadInputArray(inputChoose, 2, 10, -10000, 10000);
  454. size = inputInt(inputChoose, inputArray);
  455. array = inputArrayOfInt(inputChoose, inputArray, size, 10000);
  456. mergeSort(array, size);
  457. outputChoose = chooseTheOutput();
  458. output(outputChoose, array);
  459. scanner.close();
  460. }
  461. }
Advertisement
Add Comment
Please, Sign In to add comment