468 lines
14 KiB
C++
468 lines
14 KiB
C++
#include <iostream>
|
||
#include <fstream>
|
||
#include <cctype>
|
||
#include <limits>
|
||
#include <string>
|
||
#include <sstream>
|
||
#include <vector>
|
||
#include <algorithm>
|
||
#include <cmath>
|
||
#include <cstring>
|
||
#include <iomanip> // Для форматирования вывода
|
||
using namespace std;
|
||
|
||
// Функция перевода из двоичной строки в десятичное число
|
||
int binaryToDecimal(const string& binary) {
|
||
int decimal = 0;
|
||
for (char c : binary) {
|
||
decimal = decimal * 2 + (c - '0');
|
||
}
|
||
return decimal;
|
||
}
|
||
|
||
// Функция перевода из десятичного числа в пятеричную систему
|
||
string decimalToBase5(int decimal) {
|
||
if (decimal == 0) return "0";
|
||
string base5 = "";
|
||
while (decimal > 0) {
|
||
base5 += (decimal % 5) + '0';
|
||
decimal /= 5;
|
||
}
|
||
reverse(base5.begin(), base5.end());
|
||
return base5;
|
||
}
|
||
int gcdDivision(int a, int b) {
|
||
while (b != 0) {
|
||
int remainder = a % b;
|
||
a = b;
|
||
b = remainder;
|
||
}
|
||
return a;
|
||
}
|
||
|
||
int gcdSubtraction(int a, int b) {
|
||
while (a != b) {
|
||
if (a > b)
|
||
a -= b;
|
||
else
|
||
b -= a;
|
||
}
|
||
return a;
|
||
}
|
||
|
||
int z1(int a, int b, int method) {
|
||
switch (method) {
|
||
case 1:
|
||
return gcdDivision(a, b);
|
||
case 2:
|
||
return gcdSubtraction(a, b);
|
||
default:
|
||
cout << "Некорректный выбор метода. Выберите 1 или 2." << endl;
|
||
return -1;
|
||
}
|
||
}
|
||
|
||
void findLeastFrequentVowel(const string& filePath) {
|
||
ifstream file(filePath);
|
||
if (!file) {
|
||
cerr << "Не удалось открыть файл." << endl;
|
||
return;
|
||
}
|
||
|
||
int counts[6] = { 0 }; // Счётчики для гласных: a, e, i, o, u, y
|
||
char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
|
||
|
||
char ch;
|
||
while (file >> noskipws >> ch) {
|
||
ch = tolower(ch);
|
||
for (int i = 0; i < 6; ++i) {
|
||
if (ch == vowels[i]) {
|
||
++counts[i];
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
file.close();
|
||
|
||
int minCount = numeric_limits<int>::max();
|
||
char leastVowel = '\0'; // Инициализация нулевым символом
|
||
|
||
for (int i = 0; i < 6; ++i) {
|
||
if (counts[i] > 0 && counts[i] < minCount) {
|
||
minCount = counts[i];
|
||
leastVowel = vowels[i];
|
||
}
|
||
}
|
||
|
||
if (leastVowel != '\0') { // Проверка, нашлась ли гласная
|
||
cout << "Наименее часто встречающаяся гласная: " << leastVowel
|
||
<< " (" << minCount << " раз)" << endl;
|
||
}
|
||
else {
|
||
cout << "В файле нет гласных букв." << endl;
|
||
}
|
||
}
|
||
|
||
|
||
void z3_22() {
|
||
string filePath;
|
||
filePath = "txt.txt";
|
||
findLeastFrequentVowel(filePath);
|
||
|
||
}
|
||
|
||
void z1launcher() {
|
||
int a, b, method;
|
||
|
||
cout << "Введите два положительных целых числа: ";
|
||
if (!(cin >> a >> b) || a <= 0 || b <= 0) {
|
||
cout << "Ошибка: ввод должен быть положительными целыми числами." << endl;
|
||
return;
|
||
}
|
||
|
||
cout << "Выберите метод:\n1 - Деление\n2 - Вычитание\nВаш выбор: ";
|
||
if (!(cin >> method) || (method != 1 && method != 2)) {
|
||
cout << "Ошибка: некорректный выбор метода. Введите 1 или 2." << endl;
|
||
return;
|
||
}
|
||
|
||
int result = z1(a, b, method);
|
||
if (result != -1) {
|
||
cout << "НОД = " << result << endl;
|
||
}
|
||
}
|
||
|
||
|
||
void findWordCombination(const string& fileName, const string& combination) {
|
||
ifstream file(fileName);
|
||
if (!file.is_open()) {
|
||
cerr << "Не удалось открыть файл: " << fileName << endl;
|
||
return;
|
||
}
|
||
|
||
string line;
|
||
size_t lineNumber = 0;
|
||
bool found = false;
|
||
|
||
while (getline(file, line)) {
|
||
++lineNumber;
|
||
size_t pos = line.find(combination);
|
||
if (pos != string::npos) {
|
||
found = true;
|
||
|
||
// Выводим строку с выделением найденного сочетания слов
|
||
cout << "Найдено в строке " << lineNumber << ": ";
|
||
cout << line.substr(0, pos); // Текст до совпадения
|
||
cout << "\033[31m" << line.substr(pos, combination.length()) << "\033[0m"; // Выделенное совпадение
|
||
cout << line.substr(pos + combination.length()) << endl; // Текст после совпадения
|
||
}
|
||
}
|
||
|
||
if (!found) {
|
||
cout << "Сочетание \"" << combination << "\" не найдено в файле." << endl;
|
||
}
|
||
|
||
file.close();
|
||
}
|
||
|
||
|
||
void z3_16() {
|
||
string fileName, combination;
|
||
|
||
fileName = "txt2.txt";
|
||
|
||
|
||
cout << "Введите сочетание слов для поиска: ";
|
||
cin >> combination;
|
||
|
||
findWordCombination(fileName, combination);
|
||
|
||
|
||
}
|
||
bool isBinary(const string& str) {
|
||
for (char c : str) {
|
||
if (c != '0' && c != '1') {
|
||
return false;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
void z4_22() {
|
||
int n;
|
||
cout << "Введите длину массива: ";
|
||
cin >> n;
|
||
|
||
vector<string> binaryArray;
|
||
cout << "Введите " << n << " чисел в двоичной системе:\n";
|
||
for (int i = 0; i < n; ++i) {
|
||
string binary;
|
||
cin >> binary;
|
||
if (isBinary(binary)) {
|
||
binaryArray.push_back(binary);
|
||
}
|
||
else {
|
||
cout << "Ошибка: '" << binary << "' не является двоичным числом. Попробуйте снова.\n";
|
||
--i; // Повторить ввод для текущей итерации
|
||
}
|
||
}
|
||
|
||
vector<string> base5Array;
|
||
|
||
for (const string& binary : binaryArray) {
|
||
int decimal = binaryToDecimal(binary); // Перевод в десятичное
|
||
string base5 = decimalToBase5(decimal); // Перевод в пятеричное
|
||
base5Array.push_back(base5);
|
||
}
|
||
|
||
cout << "Числа в пятеричной системе: ";
|
||
for (const string& num : base5Array) {
|
||
cout << num << " ";
|
||
}
|
||
cout << endl;
|
||
}
|
||
void z4_16() {
|
||
double epsilon; // Входное значение ε
|
||
cout << "Введите значение epsilon: ";
|
||
cin >> epsilon;
|
||
|
||
double y = 0; // Итоговая сумма
|
||
int n = 1; // Начальный индекс
|
||
const double limit = epsilon; // Условие для множителя
|
||
|
||
while (true) {
|
||
double term = pow(1.0 / 3, n) * pow(cos(pow(3, n - 1)), 3);
|
||
if (pow(1.0 / 3, n) < limit) {
|
||
break; // Условие выхода из цикла
|
||
}
|
||
y += term;
|
||
n++;
|
||
}
|
||
|
||
cout << "Результат вычислений: y = " << y << endl;
|
||
}
|
||
string convertToBase(int number, int base) {
|
||
string result;
|
||
const char digits[] = "0123456789";
|
||
while (number > 0) {
|
||
result += digits[number % base];
|
||
number /= base;
|
||
}
|
||
reverse(result.begin(), result.end());
|
||
return result.empty() ? "0" : result; // Если число 0, вернуть "0"
|
||
}
|
||
void sieveOfEratosthenes(int n) {
|
||
|
||
// Создаем динаический массив для хранения информации о простых числах
|
||
bool* isPrime = new bool[n + 1];
|
||
|
||
// Изначально предполагаем, что все числа простые
|
||
memset(isPrime, true, (n + 1) * sizeof(bool));
|
||
|
||
// 0 и 1 не являются простыми числами
|
||
isPrime[0] = isPrime[1] = false;
|
||
|
||
// Решето Эратосфена
|
||
for (int i = 2; i * i <= n; ++i) {
|
||
if (isPrime[i]) {
|
||
for (int j = i * i; j <= n; j += i) {
|
||
isPrime[j] = false;
|
||
}
|
||
}
|
||
}
|
||
|
||
// Вывод всех простых чисел
|
||
cout << "Простые числа до " << n << ": ";
|
||
for (int i = 2; i <= n; ++i) {
|
||
if (isPrime[i]) {
|
||
cout << i << " ";
|
||
}
|
||
}
|
||
cout << endl;
|
||
|
||
// Освобождаем память
|
||
delete[] isPrime;
|
||
}
|
||
|
||
void z2() {
|
||
int n;
|
||
cout << "Введите предел для поиска простых чисел: ";
|
||
cin >> n;
|
||
|
||
if (n < 2) {
|
||
cout << "Простых чисел нет." << endl;
|
||
}
|
||
else {
|
||
sieveOfEratosthenes(n);
|
||
}
|
||
|
||
}
|
||
void z5_16() {
|
||
string inputFile = "input.txt"; // Исходный файл
|
||
string outputFile = "output.txt"; // Файл для результатов
|
||
ifstream inFile(inputFile);
|
||
ofstream outFile(outputFile);
|
||
|
||
if (!inFile.is_open()) {
|
||
cerr << "Не удалось открыть файл " << inputFile << endl;
|
||
|
||
}
|
||
|
||
if (!outFile.is_open()) {
|
||
cerr << "Не удалось открыть файл " << outputFile << endl;
|
||
|
||
}
|
||
|
||
int base;
|
||
cout << "Введите целевую систему счисления (от 2 до 9): ";
|
||
cin >> base;
|
||
|
||
if (base < 2 || base > 9) {
|
||
cerr << "Система счисления должна быть в пределах от 2 до 9." << endl;
|
||
|
||
}
|
||
|
||
string hexNumber;
|
||
while (inFile >> hexNumber) {
|
||
int decimalNumber = stoi(hexNumber, nullptr, 16); // Преобразование из 16-й в 10-ю систему
|
||
string converted = convertToBase(decimalNumber, base);
|
||
outFile << converted << endl;
|
||
}
|
||
|
||
cout << "Перевод завершен. Результаты сохранены в файл " << outputFile << endl;
|
||
|
||
inFile.close();
|
||
outFile.close();
|
||
}
|
||
// Структура для хранения данных о стране
|
||
struct Country {
|
||
string name;
|
||
int gold;
|
||
int silver;
|
||
int bronze;
|
||
int totalMedals;
|
||
int points;
|
||
|
||
// Вычислить общее число медалей и очков
|
||
void calculate() {
|
||
totalMedals = gold + silver + bronze;
|
||
points = gold * 7 + silver * 6 + bronze * 5;
|
||
}
|
||
};
|
||
|
||
// Функция для сравнения стран по золотым медалям
|
||
bool compareByGold(const Country& a, const Country& b) {
|
||
if (a.gold != b.gold) {
|
||
return a.gold > b.gold; // Сортировка по золотым медалям
|
||
}
|
||
return a.totalMedals > b.totalMedals; // Вторичная сортировка по общему количеству медалей
|
||
}
|
||
|
||
void z5_22() {
|
||
int n;
|
||
|
||
cout << "Введите количество стран: ";
|
||
cin >> n;
|
||
|
||
// Динамическое выделение памяти для массива стран
|
||
Country* countries = new Country[n];
|
||
|
||
// Ввод данных
|
||
for (int i = 0; i < n; ++i) {
|
||
cout << "Введите название страны (пожалуйста на Английском): ";
|
||
cin >> countries[i].name;
|
||
cout << "Введите количество золотых, серебряных и бронзовых медалей: ";
|
||
cin >> countries[i].gold >> countries[i].silver >> countries[i].bronze;
|
||
countries[i].calculate();
|
||
}
|
||
|
||
// Сортировка стран
|
||
sort(countries, countries + n, compareByGold);
|
||
|
||
// Сохранение данных в файл
|
||
ofstream outFile("olympic_results.txt");
|
||
if (!outFile) {
|
||
cerr << "Ошибка открытия файла для записи!" << endl;
|
||
delete[] countries; // Освобождение памяти перед выходом
|
||
return;
|
||
}
|
||
|
||
outFile << left << setw(15) << "Страна"
|
||
<< setw(10) << "Золото"
|
||
<< setw(10) << "Серебро"
|
||
<< setw(10) << "Бронза"
|
||
<< setw(15) << "Всего Медалей"
|
||
<< setw(10) << "Очки" << endl;
|
||
|
||
for (int i = 0; i < n; ++i) {
|
||
outFile << left << setw(15) << countries[i].name
|
||
<< setw(10) << countries[i].gold
|
||
<< setw(10) << countries[i].silver
|
||
<< setw(10) << countries[i].bronze
|
||
<< setw(15) << countries[i].totalMedals
|
||
<< setw(10) << countries[i].points << endl;
|
||
}
|
||
outFile.close();
|
||
|
||
// Вывод данных на экран
|
||
cout << left << setw(15) << "Страна"
|
||
<< setw(10) << "Золото"
|
||
<< setw(10) << "Серебро"
|
||
<< setw(10) << "Бронза"
|
||
<< setw(15) << "ВсегоМедалей"
|
||
<< setw(10) << "Очки" << endl;
|
||
|
||
for (int i = 0; i < n; ++i) {
|
||
cout << left << setw(15) << countries[i].name
|
||
<< setw(10) << countries[i].gold
|
||
<< setw(10) << countries[i].silver
|
||
<< setw(10) << countries[i].bronze
|
||
<< setw(15) << countries[i].totalMedals
|
||
<< setw(10) << countries[i].points << endl;
|
||
}
|
||
|
||
cout << "Результаты сохранены в файл 'olympic_results.txt'." << endl;
|
||
|
||
// Освобождаем память
|
||
delete[] countries;
|
||
}
|
||
void showMenu() {
|
||
cout << "Меню задач:\n";
|
||
cout << "1. «Алгоритм Евклида»\n";
|
||
cout << "2. «Решето какого-то чела»\n"; // готов
|
||
cout << "3. 3.16\n";
|
||
cout << "4. 3.22\n";
|
||
cout << "6. 4.16\n";
|
||
cout << "7. 4.22\n";// готов
|
||
cout << "8. 5.16\n";
|
||
cout << "9. 5.22\n";// готово\\
|
||
cout << "0. Выход\n";
|
||
}
|
||
void launchTasks() {
|
||
int choice;
|
||
do {
|
||
showMenu();
|
||
cout << "Выберите номер задачи для запуска (или 0 для выхода): ";
|
||
cin >> choice;
|
||
|
||
switch (choice) {
|
||
case 1: z1launcher(); break;
|
||
case 2: z2(); break;
|
||
case 3: z3_16(); break;
|
||
case 4: z3_22(); break;
|
||
case 6: z4_16(); break;
|
||
case 7: z4_22(); break;
|
||
case 8: z5_16(); break;
|
||
case 9: z5_22(); break;
|
||
case 0: cout << "Выход из программы.\n"; break;
|
||
default: cout << "Ошибка: неверный выбор. Пожалуйста, попробуйте снова.\n";
|
||
}
|
||
cout << endl;
|
||
} while (choice != 0);
|
||
}
|
||
int main() {
|
||
setlocale(LC_ALL, "");
|
||
|
||
|
||
launchTasks();
|
||
return 0;
|
||
} |