Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Пошаговая сортировка. Разработать алгоритм методом пошаговой детализации и программу, реализующую этот алгоритм.
- package com.company;
- import java.io.File;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- class ExceptionFileCannotBeReadOrEmpty extends Exception {
- }
- class ExceptionStringWithNoNumbersFound extends Exception {
- }
- class ExceptionTooManyNumbersInString extends Exception {
- }
- class ExceptionSomeErrorInFile extends Exception {
- }
- public class Main {
- private static Scanner scConsole;
- private static final String MES_TASK = "Пошаговая сортировка. Разработать алгоритм методом пошаговой детализации и программу, реализующую этот алгоритм.";
- private static final String ERROR_FILE_NOT_FOUND = "Файл не найден.";
- private static final String FORMAT_INPUT_OF_PATH = "Пожалуйста, введите путь к файлу %s: ";
- private static final String MES_ASK_INPUT_METHOD = "\nОткуда брать данные?\n\t1 - из файла\n\t2 - ввести вручную\n";
- private static final String MES_ASK_AGAIN_INPUT_METHOD = "\t\"1\" - повторить попытку.\n\t\"2\" - ввести данные из консоли.\n";
- private static final String ERROR_FILE_CANNOT_BE_READ_OR_IS_EMPTY = "Файл не может быть прочитан или пуст.";
- private static final String MES_ASK_OUTPUT_TO_FILE = "Хотите вывести ответ в файл?\n\t1 - да\n\t2 - нет\n";
- private static final String ERROR_FILE_CANNOT_BE_CREATED_OR_OPENED = "Файл не может быть создан или открыт. Повторите попытку:\n";
- private static final String ERROR_CHOICE_IS_INCORRECT = "\tНадо ввести \"1\" или \"2\".\n\tПовторите попытку: ";
- private static final String ERROR_STRING_WITHOUT_NUMBERS = "Введённая строка не содержит целые числа.\n";
- private static final String ERROR_NO_NUMBERS_IN_STRING_IN_FILE = "Первая строка в файле не содержит целые числа или перед числами есть другие символы.\n";
- private static final String ERROR_NUMBER_OUT_OF_RANGE = "Одно или несколько чисел в строке выходят за рамки допустимых значений.\n";
- private static final String ERROR_TOO_MANY_NUMBERS_IN_STRING = "В строке слишком много чисел\n";
- private static final String MES_NOT_EVERYTHING_READ = "Уведомление: не вся строка была прочитана. Возможно, в строке есть не числа.\n" +
- "Были прочитаны все числа до первого лишнего символа.\n";
- private static final String MES_INPUT_REQUEST = "Введите строку с числами через пробел:";
- private static final String MES_TRY_AGAIN = "Повторите попытку\n";
- private static final String SYS_IP_METHOD_FILE = "FromFile";
- private static final String SYS_IP_METHOD_CONS = "FromConsole";
- private static final String SYS_OP_YES = "Output to file";
- private static final String SYS_OP_NO = "Don't output to file";
- private static final Integer MIN_NUMBER = -1000000;
- private static final Integer MAX_NUMBER = 1000000;
- private static final Integer MAX_QUANTITY_OF_NUMBERS = 10000;
- private static String choose(String sChoice1, String sChoice2, String sQuestion) {
- short nChoice = 2;
- boolean bIsIncorrect;
- String sAnswer;
- System.out.println(sQuestion + "\tВаш выбор: ");
- do {
- bIsIncorrect = false;
- try {
- nChoice = Short.parseShort(scConsole.nextLine());
- } catch (NumberFormatException e) {
- bIsIncorrect = true;
- }
- if (!bIsIncorrect && !(nChoice == 1) && !(nChoice == 2)) {
- bIsIncorrect = true;
- }
- if (bIsIncorrect) {
- System.out.println(ERROR_CHOICE_IS_INCORRECT);
- }
- } while (bIsIncorrect);
- sAnswer = nChoice == 1 ? sChoice1 : sChoice2;
- return sAnswer;
- }
- private static String inputPathToFile(boolean bIsInput) {
- String sPath;
- System.out.printf(FORMAT_INPUT_OF_PATH, bIsInput ? "ввода" : "вывода");
- sPath = scConsole.nextLine();
- return sPath;
- }
- private static int[] readArrFromFile(String sPathToFile) throws java.io.FileNotFoundException, ExceptionFileCannotBeReadOrEmpty, ExceptionStringWithNoNumbersFound, ExceptionTooManyNumbersInString {
- Scanner scFileInput = new Scanner(new File(sPathToFile));
- String sInput;
- int[] aArr;
- int nQuantityOfNum;
- Scanner scLine;
- short flForError = -1;
- if (scFileInput.hasNextLine()) {
- sInput = scFileInput.nextLine();
- scLine = new Scanner(sInput);
- if (scLine.hasNextInt()) {
- nQuantityOfNum = countQuantityOfNumbers(scLine, flForError);
- if (nQuantityOfNum > MAX_QUANTITY_OF_NUMBERS) {
- throw new ExceptionTooManyNumbersInString();
- }
- } else {
- throw new ExceptionStringWithNoNumbersFound();
- }
- aArr = new int[nQuantityOfNum];
- scLine = new Scanner(sInput);
- for (int i = 0; i < nQuantityOfNum; i++) {
- aArr[i] = scLine.nextInt();
- }
- } else {
- throw new ExceptionFileCannotBeReadOrEmpty();
- }
- scLine.close();
- scFileInput.close();
- return aArr;
- }
- private static int countQuantityOfNumbers(Scanner scLine, final short flForError) {
- int nQuantityOfNum = 0;
- int nNumber;
- while (scLine.hasNextInt() && nQuantityOfNum > flForError) {
- nQuantityOfNum++;
- nNumber = scLine.nextInt();
- if (nNumber < MIN_NUMBER || nNumber > MAX_NUMBER) {
- nQuantityOfNum = -1;
- System.out.print(ERROR_NUMBER_OUT_OF_RANGE + MES_TRY_AGAIN);
- }
- }
- if (scLine.hasNext()) {
- System.out.print(MES_NOT_EVERYTHING_READ);
- }
- return nQuantityOfNum;
- }
- private static String getStringAndCountQuantity(int[] nQuantityOfNum) {
- boolean bIsIncorrect;
- String sInput;
- Scanner scLine;
- final short flForError = -1;
- do {
- bIsIncorrect = false;
- sInput = scConsole.nextLine();
- scLine = new Scanner(sInput);
- if (scLine.hasNextInt()) {
- nQuantityOfNum[0] = countQuantityOfNumbers(scLine, flForError);
- if (nQuantityOfNum[0] == flForError) bIsIncorrect = true;
- if (nQuantityOfNum[0] > MAX_QUANTITY_OF_NUMBERS) {
- bIsIncorrect = true;
- System.out.print(ERROR_TOO_MANY_NUMBERS_IN_STRING + MES_TRY_AGAIN);
- }
- } else {
- System.out.print(ERROR_STRING_WITHOUT_NUMBERS + MES_TRY_AGAIN);
- bIsIncorrect = true;
- }
- } while (bIsIncorrect);
- scLine.close();
- return sInput;
- }
- private static int[] readArrFromConsole() {
- String sInput;
- Scanner scLine;
- int[] aArr;
- int[] nQuantityOfNum = new int[1];
- System.out.println(MES_INPUT_REQUEST);
- sInput = getStringAndCountQuantity(nQuantityOfNum);
- aArr = new int[nQuantityOfNum[0]];
- scLine = new Scanner(sInput);
- for (int i = 0; i < nQuantityOfNum[0]; i++) {
- aArr[i] = scLine.nextInt();
- }
- scLine.close();
- return aArr;
- }
- private static int[] inputFromFile() throws ExceptionSomeErrorInFile {
- String sPathToFile = inputPathToFile(true);
- int[] aInput;
- try {
- aInput = readArrFromFile(sPathToFile);
- } catch (java.io.FileNotFoundException e) {
- System.out.println(ERROR_FILE_NOT_FOUND);
- throw new ExceptionSomeErrorInFile();
- } catch (ExceptionFileCannotBeReadOrEmpty e) {
- System.out.println(ERROR_FILE_CANNOT_BE_READ_OR_IS_EMPTY);
- throw new ExceptionSomeErrorInFile();
- } catch (ExceptionStringWithNoNumbersFound e) {
- System.out.println(ERROR_NO_NUMBERS_IN_STRING_IN_FILE);
- throw new ExceptionSomeErrorInFile();
- } catch (ExceptionTooManyNumbersInString e) {
- System.out.print(ERROR_TOO_MANY_NUMBERS_IN_STRING);
- throw new ExceptionSomeErrorInFile();
- }
- return aInput;
- }
- private static int[] getInput() {
- int[] aInput = new int[1];
- boolean bInputIsNotDone = true;
- String sInputMethod = choose(SYS_IP_METHOD_FILE, SYS_IP_METHOD_CONS, MES_ASK_INPUT_METHOD);
- do {
- switch (sInputMethod) {
- case SYS_IP_METHOD_FILE -> {
- try {
- aInput = inputFromFile();
- bInputIsNotDone = false;
- } catch (ExceptionSomeErrorInFile e) {
- sInputMethod = choose(SYS_IP_METHOD_FILE, SYS_IP_METHOD_CONS, MES_ASK_AGAIN_INPUT_METHOD);
- }
- }
- case SYS_IP_METHOD_CONS -> {
- aInput = readArrFromConsole();
- bInputIsNotDone = false;
- }
- }
- } while (bInputIsNotDone);
- return aInput;
- }
- public static boolean splitInputBetweenLists(int[] aInput, int nDivisor, List<Integer>[] listBuckets, short nBitness) {
- int temp;
- boolean flStillWorking = false;
- for (int num : aInput) {
- temp = num / nDivisor;
- listBuckets[temp % nBitness].add(num);
- if (!flStillWorking && temp > 0) {
- flStillWorking = true;
- }
- }
- return flStillWorking;
- }
- public static void lsdSort(int[] aInput) {
- short nBitness = 10; // разрядность
- boolean flStillWorking = true;
- int nDivisor = 1;
- List<Integer>[] listBuckets = new ArrayList[nBitness];
- for (int i = 0; i < listBuckets.length; i++) {
- listBuckets[i] = new ArrayList<>();
- }
- while (flStillWorking) {
- flStillWorking = splitInputBetweenLists(aInput, nDivisor, listBuckets, nBitness);
- // moving lists back into input array
- int i = 0;
- for (int j = 0; j < nBitness; j++) {
- for (int num : listBuckets[j]) {
- aInput[i] = num;
- i++;
- }
- listBuckets[j].clear();
- }
- nDivisor *= nBitness;
- }
- }
- private static void outputToFile(int[] aArr, String sPathToFile) {
- boolean bOutputNotReady = true;
- do {
- try {
- PrintWriter fOutput = new PrintWriter(sPathToFile);
- for (int i = 0; i < aArr.length - 1; i++) {
- fOutput.print(aArr[i] + " ");
- }
- fOutput.print(aArr[aArr.length - 1] + "\n");
- fOutput.close();
- bOutputNotReady = false;
- } catch (Exception e) {
- System.out.print(ERROR_FILE_CANNOT_BE_CREATED_OR_OPENED);
- String sShouldOutputInfoToFile = choose(SYS_OP_YES, SYS_OP_NO, MES_ASK_OUTPUT_TO_FILE);
- if (sShouldOutputInfoToFile.equals(SYS_OP_YES)) {
- sPathToFile = inputPathToFile(false);
- } else {
- bOutputNotReady = false;
- }
- }
- } while (bOutputNotReady);
- }
- private static void outputAnswer(int[] aArr) {
- System.out.println("Ответ:");
- for (int i = 0; i < aArr.length - 1; i++) {
- System.out.print(aArr[i] + ", ");
- }
- System.out.println(aArr[aArr.length - 1]);
- String sShouldOutputInfoToFile = choose(SYS_OP_YES, SYS_OP_NO, MES_ASK_OUTPUT_TO_FILE);
- if (sShouldOutputInfoToFile.equals(SYS_OP_YES)) {
- String sPathToFile = inputPathToFile(false);
- outputToFile(aArr, sPathToFile);
- }
- }
- public static void main(String[] args) {
- scConsole = new Scanner(System.in);
- System.out.println(MES_TASK);
- // Путь к моему файлу ввода: /Users/sasha/Documents/___Университет/ОАиП/Пз/Лабы/блок 3/input.txt
- // Путь к моему файлу вывода: /Users/sasha/Documents/___Университет/ОАиП/Пз/Лабы/блок 3/output.txt
- int[] aArr = getInput();
- lsdSort(aArr);
- outputAnswer(aArr);
- scConsole.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment