Vanilla_Fury

laba_3_3_java

Nov 29th, 2020
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.29 KB | None | 0 0
  1. // Пошаговая сортировка. Разработать алгоритм методом пошаговой детализации и программу, реализующую этот алгоритм.
  2.  
  3. package com.company;
  4.  
  5. import java.io.File;
  6. import java.io.PrintWriter;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.Scanner;
  10.  
  11. class ExceptionFileCannotBeReadOrEmpty extends Exception {
  12. }
  13.  
  14. class ExceptionStringWithNoNumbersFound extends Exception {
  15. }
  16.  
  17. class ExceptionTooManyNumbersInString extends Exception {
  18. }
  19.  
  20. class ExceptionSomeErrorInFile extends Exception {
  21. }
  22.  
  23. public class Main {
  24.  
  25. private static Scanner scConsole;
  26.  
  27. private static final String MES_TASK = "Пошаговая сортировка. Разработать алгоритм методом пошаговой детализации и программу, реализующую этот алгоритм.";
  28. private static final String ERROR_FILE_NOT_FOUND = "Файл не найден.";
  29. private static final String FORMAT_INPUT_OF_PATH = "Пожалуйста, введите путь к файлу %s: ";
  30. private static final String MES_ASK_INPUT_METHOD = "\nОткуда брать данные?\n\t1 - из файла\n\t2 - ввести вручную\n";
  31. private static final String MES_ASK_AGAIN_INPUT_METHOD = "\t\"1\" - повторить попытку.\n\t\"2\" - ввести данные из консоли.\n";
  32. private static final String ERROR_FILE_CANNOT_BE_READ_OR_IS_EMPTY = "Файл не может быть прочитан или пуст.";
  33. private static final String MES_ASK_OUTPUT_TO_FILE = "Хотите вывести ответ в файл?\n\t1 - да\n\t2 - нет\n";
  34. private static final String ERROR_FILE_CANNOT_BE_CREATED_OR_OPENED = "Файл не может быть создан или открыт. Повторите попытку:\n";
  35. private static final String ERROR_CHOICE_IS_INCORRECT = "\tНадо ввести \"1\" или \"2\".\n\tПовторите попытку: ";
  36. private static final String ERROR_STRING_WITHOUT_NUMBERS = "Введённая строка не содержит целые числа.\n";
  37. private static final String ERROR_NO_NUMBERS_IN_STRING_IN_FILE = "Первая строка в файле не содержит целые числа или перед числами есть другие символы.\n";
  38. private static final String ERROR_NUMBER_OUT_OF_RANGE = "Одно или несколько чисел в строке выходят за рамки допустимых значений.\n";
  39. private static final String ERROR_TOO_MANY_NUMBERS_IN_STRING = "В строке слишком много чисел\n";
  40. private static final String MES_NOT_EVERYTHING_READ = "Уведомление: не вся строка была прочитана. Возможно, в строке есть не числа.\n" +
  41. "Были прочитаны все числа до первого лишнего символа.\n";
  42. private static final String MES_INPUT_REQUEST = "Введите строку с числами через пробел:";
  43. private static final String MES_TRY_AGAIN = "Повторите попытку\n";
  44. private static final String SYS_IP_METHOD_FILE = "FromFile";
  45. private static final String SYS_IP_METHOD_CONS = "FromConsole";
  46. private static final String SYS_OP_YES = "Output to file";
  47. private static final String SYS_OP_NO = "Don't output to file";
  48. private static final Integer MIN_NUMBER = -1000000;
  49. private static final Integer MAX_NUMBER = 1000000;
  50. private static final Integer MAX_QUANTITY_OF_NUMBERS = 10000;
  51.  
  52. private static String choose(String sChoice1, String sChoice2, String sQuestion) {
  53. short nChoice = 2;
  54. boolean bIsIncorrect;
  55. String sAnswer;
  56.  
  57. System.out.println(sQuestion + "\tВаш выбор: ");
  58. do {
  59. bIsIncorrect = false;
  60. try {
  61. nChoice = Short.parseShort(scConsole.nextLine());
  62. } catch (NumberFormatException e) {
  63. bIsIncorrect = true;
  64. }
  65. if (!bIsIncorrect && !(nChoice == 1) && !(nChoice == 2)) {
  66. bIsIncorrect = true;
  67. }
  68. if (bIsIncorrect) {
  69. System.out.println(ERROR_CHOICE_IS_INCORRECT);
  70. }
  71. } while (bIsIncorrect);
  72.  
  73. sAnswer = nChoice == 1 ? sChoice1 : sChoice2;
  74.  
  75. return sAnswer;
  76. }
  77.  
  78. private static String inputPathToFile(boolean bIsInput) {
  79. String sPath;
  80.  
  81. System.out.printf(FORMAT_INPUT_OF_PATH, bIsInput ? "ввода" : "вывода");
  82. sPath = scConsole.nextLine();
  83. return sPath;
  84. }
  85.  
  86. private static int[] readArrFromFile(String sPathToFile) throws java.io.FileNotFoundException, ExceptionFileCannotBeReadOrEmpty, ExceptionStringWithNoNumbersFound, ExceptionTooManyNumbersInString {
  87. Scanner scFileInput = new Scanner(new File(sPathToFile));
  88. String sInput;
  89. int[] aArr;
  90. int nQuantityOfNum;
  91. Scanner scLine;
  92. short flForError = -1;
  93.  
  94. if (scFileInput.hasNextLine()) {
  95. sInput = scFileInput.nextLine();
  96. scLine = new Scanner(sInput);
  97.  
  98. if (scLine.hasNextInt()) {
  99. nQuantityOfNum = countQuantityOfNumbers(scLine, flForError);
  100. if (nQuantityOfNum > MAX_QUANTITY_OF_NUMBERS) {
  101. throw new ExceptionTooManyNumbersInString();
  102. }
  103. } else {
  104. throw new ExceptionStringWithNoNumbersFound();
  105. }
  106.  
  107. aArr = new int[nQuantityOfNum];
  108. scLine = new Scanner(sInput);
  109.  
  110. for (int i = 0; i < nQuantityOfNum; i++) {
  111. aArr[i] = scLine.nextInt();
  112. }
  113. } else {
  114. throw new ExceptionFileCannotBeReadOrEmpty();
  115. }
  116.  
  117. scLine.close();
  118. scFileInput.close();
  119.  
  120. return aArr;
  121. }
  122.  
  123. private static int countQuantityOfNumbers(Scanner scLine, final short flForError) {
  124. int nQuantityOfNum = 0;
  125. int nNumber;
  126.  
  127. while (scLine.hasNextInt() && nQuantityOfNum > flForError) {
  128. nQuantityOfNum++;
  129. nNumber = scLine.nextInt();
  130. if (nNumber < MIN_NUMBER || nNumber > MAX_NUMBER) {
  131. nQuantityOfNum = -1;
  132. System.out.print(ERROR_NUMBER_OUT_OF_RANGE + MES_TRY_AGAIN);
  133. }
  134. }
  135. if (scLine.hasNext()) {
  136. System.out.print(MES_NOT_EVERYTHING_READ);
  137. }
  138. return nQuantityOfNum;
  139. }
  140.  
  141. private static String getStringAndCountQuantity(int[] nQuantityOfNum) {
  142. boolean bIsIncorrect;
  143. String sInput;
  144. Scanner scLine;
  145. final short flForError = -1;
  146.  
  147. do {
  148. bIsIncorrect = false;
  149. sInput = scConsole.nextLine();
  150. scLine = new Scanner(sInput);
  151. if (scLine.hasNextInt()) {
  152. nQuantityOfNum[0] = countQuantityOfNumbers(scLine, flForError);
  153. if (nQuantityOfNum[0] == flForError) bIsIncorrect = true;
  154. if (nQuantityOfNum[0] > MAX_QUANTITY_OF_NUMBERS) {
  155. bIsIncorrect = true;
  156. System.out.print(ERROR_TOO_MANY_NUMBERS_IN_STRING + MES_TRY_AGAIN);
  157. }
  158. } else {
  159. System.out.print(ERROR_STRING_WITHOUT_NUMBERS + MES_TRY_AGAIN);
  160. bIsIncorrect = true;
  161. }
  162. } while (bIsIncorrect);
  163.  
  164. scLine.close();
  165. return sInput;
  166. }
  167.  
  168. private static int[] readArrFromConsole() {
  169. String sInput;
  170. Scanner scLine;
  171. int[] aArr;
  172. int[] nQuantityOfNum = new int[1];
  173.  
  174. System.out.println(MES_INPUT_REQUEST);
  175. sInput = getStringAndCountQuantity(nQuantityOfNum);
  176.  
  177. aArr = new int[nQuantityOfNum[0]];
  178. scLine = new Scanner(sInput);
  179.  
  180. for (int i = 0; i < nQuantityOfNum[0]; i++) {
  181. aArr[i] = scLine.nextInt();
  182. }
  183.  
  184. scLine.close();
  185. return aArr;
  186. }
  187.  
  188. private static int[] inputFromFile() throws ExceptionSomeErrorInFile {
  189. String sPathToFile = inputPathToFile(true);
  190. int[] aInput;
  191.  
  192. try {
  193. aInput = readArrFromFile(sPathToFile);
  194. } catch (java.io.FileNotFoundException e) {
  195. System.out.println(ERROR_FILE_NOT_FOUND);
  196. throw new ExceptionSomeErrorInFile();
  197. } catch (ExceptionFileCannotBeReadOrEmpty e) {
  198. System.out.println(ERROR_FILE_CANNOT_BE_READ_OR_IS_EMPTY);
  199. throw new ExceptionSomeErrorInFile();
  200. } catch (ExceptionStringWithNoNumbersFound e) {
  201. System.out.println(ERROR_NO_NUMBERS_IN_STRING_IN_FILE);
  202. throw new ExceptionSomeErrorInFile();
  203. } catch (ExceptionTooManyNumbersInString e) {
  204. System.out.print(ERROR_TOO_MANY_NUMBERS_IN_STRING);
  205. throw new ExceptionSomeErrorInFile();
  206. }
  207.  
  208. return aInput;
  209. }
  210.  
  211. private static int[] getInput() {
  212. int[] aInput = new int[1];
  213. boolean bInputIsNotDone = true;
  214.  
  215. String sInputMethod = choose(SYS_IP_METHOD_FILE, SYS_IP_METHOD_CONS, MES_ASK_INPUT_METHOD);
  216.  
  217. do {
  218. switch (sInputMethod) {
  219. case SYS_IP_METHOD_FILE -> {
  220. try {
  221. aInput = inputFromFile();
  222. bInputIsNotDone = false;
  223. } catch (ExceptionSomeErrorInFile e) {
  224. sInputMethod = choose(SYS_IP_METHOD_FILE, SYS_IP_METHOD_CONS, MES_ASK_AGAIN_INPUT_METHOD);
  225. }
  226. }
  227. case SYS_IP_METHOD_CONS -> {
  228. aInput = readArrFromConsole();
  229. bInputIsNotDone = false;
  230. }
  231. }
  232. } while (bInputIsNotDone);
  233.  
  234. return aInput;
  235. }
  236.  
  237. public static boolean splitInputBetweenLists(int[] aInput, int nDivisor, List<Integer>[] listBuckets, short nBitness) {
  238. int temp;
  239. boolean flStillWorking = false;
  240.  
  241. for (int num : aInput) {
  242. temp = num / nDivisor;
  243. listBuckets[temp % nBitness].add(num);
  244. if (!flStillWorking && temp > 0) {
  245. flStillWorking = true;
  246. }
  247. }
  248.  
  249. return flStillWorking;
  250. }
  251.  
  252. public static void lsdSort(int[] aInput) {
  253. short nBitness = 10; // разрядность
  254. boolean flStillWorking = true;
  255. int nDivisor = 1;
  256.  
  257. List<Integer>[] listBuckets = new ArrayList[nBitness];
  258. for (int i = 0; i < listBuckets.length; i++) {
  259. listBuckets[i] = new ArrayList<>();
  260. }
  261.  
  262. while (flStillWorking) {
  263. flStillWorking = splitInputBetweenLists(aInput, nDivisor, listBuckets, nBitness);
  264.  
  265. // moving lists back into input array
  266. int i = 0;
  267. for (int j = 0; j < nBitness; j++) {
  268. for (int num : listBuckets[j]) {
  269. aInput[i] = num;
  270. i++;
  271. }
  272. listBuckets[j].clear();
  273. }
  274.  
  275. nDivisor *= nBitness;
  276. }
  277. }
  278.  
  279. private static void outputToFile(int[] aArr, String sPathToFile) {
  280. boolean bOutputNotReady = true;
  281. do {
  282. try {
  283. PrintWriter fOutput = new PrintWriter(sPathToFile);
  284.  
  285. for (int i = 0; i < aArr.length - 1; i++) {
  286. fOutput.print(aArr[i] + " ");
  287. }
  288. fOutput.print(aArr[aArr.length - 1] + "\n");
  289.  
  290. fOutput.close();
  291. bOutputNotReady = false;
  292. } catch (Exception e) {
  293. System.out.print(ERROR_FILE_CANNOT_BE_CREATED_OR_OPENED);
  294. String sShouldOutputInfoToFile = choose(SYS_OP_YES, SYS_OP_NO, MES_ASK_OUTPUT_TO_FILE);
  295. if (sShouldOutputInfoToFile.equals(SYS_OP_YES)) {
  296. sPathToFile = inputPathToFile(false);
  297. } else {
  298. bOutputNotReady = false;
  299. }
  300. }
  301. } while (bOutputNotReady);
  302. }
  303.  
  304. private static void outputAnswer(int[] aArr) {
  305. System.out.println("Ответ:");
  306. for (int i = 0; i < aArr.length - 1; i++) {
  307. System.out.print(aArr[i] + ", ");
  308. }
  309. System.out.println(aArr[aArr.length - 1]);
  310.  
  311. String sShouldOutputInfoToFile = choose(SYS_OP_YES, SYS_OP_NO, MES_ASK_OUTPUT_TO_FILE);
  312. if (sShouldOutputInfoToFile.equals(SYS_OP_YES)) {
  313. String sPathToFile = inputPathToFile(false);
  314. outputToFile(aArr, sPathToFile);
  315. }
  316.  
  317. }
  318.  
  319. public static void main(String[] args) {
  320. scConsole = new Scanner(System.in);
  321.  
  322. System.out.println(MES_TASK);
  323. // Путь к моему файлу ввода: /Users/sasha/Documents/___Университет/ОАиП/Пз/Лабы/блок 3/input.txt
  324. // Путь к моему файлу вывода: /Users/sasha/Documents/___Университет/ОАиП/Пз/Лабы/блок 3/output.txt
  325.  
  326. int[] aArr = getInput();
  327. lsdSort(aArr);
  328. outputAnswer(aArr);
  329.  
  330. scConsole.close();
  331. }
  332. }
  333.  
Advertisement
Add Comment
Please, Sign In to add comment