Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 24.12.2022, 00:26   #1
dealsper
Новичок
Джуниор
 
Регистрация: 24.12.2022
Сообщений: 1
По умолчанию Заполнение массива спиралью С++

Если быть короче, то надо алгоритм заполнения матрицы(спиралькой) начинать с верхенего правого угла и идти к центру против часовой стрелки. Мой код делает наоборот, из центра в правый верхний угол. В матрицу записывается фраза из файла, так же код может шифровать фразу из файла и расшировать шифрованное, и все это записываются в отдельные файлы. Фраза из исходного файла Say "Hello" To My Little Friend! .
Код:
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <conio.h>

using namespace std;

void Open(fstream& file, string path) {
    try {
        file.open(path);
        if (!file.is_open()) {
            throw "Ошибка открытия файла";
        }
    }
    catch (const exception& ex) {
        ex.what();
        exit;
    }
}

void Read(vector<char>& text, string path) {
    fstream file;
    Open(file, path);
    while (!file.eof()) {
        char buff;
        file >> buff;
        if (buff != ' ') {
            text.push_back(buff);
        }
    }
    text.pop_back();
    file.close();
}

void Out(vector<char>& text) {
    for (int i = 0; i < text.size(); i++) {
        cout << text[i];
    } cout << endl;
}

int main() {
    srand(time(NULL));
    setlocale(LC_ALL, "Russian");

    while (true) {
        cout << "1 - Шифровка фразы (из файла file.txt в файл encode.txt)\n2 - Расшифровка шифрованной фразы (из файла encode.txt в файл decode.txt)\nЧтобы выйти нажмите Esc\n";
        if (_getch() == 27) break;

        int choise; cout << "Ввод: "; cin >> choise; cout << endl;
        if (choise == 1) {
            vector<char>text;
            Read(text, "file.txt");

            cout << "Ваш изначальный текст: "; Out(text); cout << endl;

            int matrix_size = 0;
            if (sqrt(text.size()) == (int)sqrt(text.size())) matrix_size = sqrt(text.size());
            else matrix_size = (int)sqrt(text.size()) + 1;

            for (int i = text.size(); i < pow(matrix_size, 2); i++) {
                text.push_back(char('а' + rand() % ('я' - 'а')));
            }
            cout << "Текст с добавкой букв: "; Out(text); cout << endl;

            int index = 0;
            if (matrix_size % 2 == 0) index = matrix_size / 2 - 1;
            else index = matrix_size / 2;

            char* matrix; matrix = new char[matrix_size * matrix_size];
            for (int i = 0; i < matrix_size; i++) {
                for (int j = 0; j < matrix_size; j++) {
                    *(matrix + i * matrix_size + j) = '0';
                }
            }

            cout << endl << endl;

            int i = index; int j = index; int step = 0; int counter = 1;
            while (step < text.size()) {
                for (int l = 0; l < counter; l++)
                    if (step < text.size()) { *(matrix + i * matrix_size + j) = text[step]; step++; j++; }
                for (int l = 0; l < counter; l++)
                    if (step < text.size()) { *(matrix + i * matrix_size + j) = text[step]; step++; i++; }
                counter++;
                for (int l = 0; l < counter; l++)
                    if (step < text.size()) { *(matrix + i * matrix_size + j) = text[step]; step++; j--; }
                for (int l = 0; l < counter; l++)
                    if (step < text.size()) { *(matrix + i * matrix_size + j) = text[step]; step++; i--; }
                counter++;
            }

            cout << "Матрица: \t";
            for (int i = 0; i < matrix_size; i++) {
                for (int j = 0; j < matrix_size; j++) {
                    cout << *(matrix + i * matrix_size + j) << ' ' << ' ';
                } cout << endl << "\t\t";
            }
            cout << endl << endl;

            fstream encode; Open(encode, "encode.txt");

            cout << "Зашифрованный текст: ";
            for (int j = 0; j < matrix_size; j++) {
                for (int i = 0; i < matrix_size; i++) {
                    cout << *(matrix + i * matrix_size + j);
                    encode << *(matrix + i * matrix_size + j);
                }
            } cout << endl << endl;

            encode.close();
        }
        else if (choise == 2) {
            vector<char>code;
            Read(code, "encode.txt");
            cout << endl << "Шифрованный текст: "; Out(code); cout << endl;

            int matrix_size = 0;
            if (sqrt(code.size()) == (int)sqrt(code.size())) matrix_size = sqrt(code.size());
            else { cout << "\n\t===Ошибка! Неверный шифр===\n"; break; }

            int index = 0;
            if (matrix_size % 2 == 0) index = matrix_size / 2 - 1;
            else index = matrix_size / 2;

            char* matrix; matrix = new char[matrix_size * matrix_size]; int step = 0;
            for (int j = 0; j < matrix_size; j++)
                for (int i = 0; i < matrix_size; i++) {
                    *(matrix + i * matrix_size + j) = code[step]; step++;
                }

            fstream decode; Open(decode, "decode.txt");

            int i = index; int j = index; step = 0; int counter = 1;
            while (step < code.size()) {
                for (int l = 0; l < counter; l++)
                    if (step < code.size()) { decode << *(matrix + i * matrix_size + j); step++; j++; }
                for (int l = 0; l < counter; l++)
                    if (step < code.size()) { decode << *(matrix + i * matrix_size + j); step++; i++; }
                counter++;
                for (int l = 0; l < counter; l++)
                    if (step < code.size()) { decode << *(matrix + i * matrix_size + j); step++; j--; }
                for (int l = 0; l < counter; l++)
                    if (step < code.size()) { decode << *(matrix + i * matrix_size + j); step++; i--; }
                counter++;
            }

            decode.close();

            vector<char>text;
            Read(text, "decode.txt");
            cout << "Расшифрованный текст: "; Out(text); cout << endl;
        }
        else {
            cout << "Неверный ввод!" << endl;
        }
    }
    return 0;
}

Последний раз редактировалось dealsper; 24.12.2022 в 00:40.
dealsper вне форума Ответить с цитированием
Старый 26.12.2022, 05:44   #2
Пётр Седов
Форумчанин
 
Регистрация: 26.10.2022
Сообщений: 119
По умолчанию

Код:
#include <assert.h>
#include <string.h>
#include <vector>
#include <iostream>

using namespace std;

int main() {
  const int matrix_size = 7;
  char matrix[matrix_size * matrix_size];

  const char* s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  vector<char> text(s, s + strlen(s)); // в STL для работы с текстом обычно используют std::string или std::string_view
  int text_pos = 0;

  // изначально, границы заполнения -- вся матрица
  int min_row_slit = 0;
  int max_row_slit = matrix_size;
  int min_col_slit = 0;
  int max_col_slit = matrix_size;
  for (;;) {
    assert(min_col_slit < max_col_slit);
    // заполняем верхний край
    for (int col = max_col_slit - 1; col >= min_col_slit; col--) {
      matrix[min_row_slit * matrix_size + col] = (text_pos < text.size() ? text[text_pos++] : '0');
    }
    // сужаем границы
    min_row_slit++;

    if (min_row_slit >= max_row_slit) {break;}
    // заполняем левый край
    for (int row = min_row_slit; row < max_row_slit; row++) {
      matrix[row * matrix_size + min_col_slit] = (text_pos < text.size() ? text[text_pos++] : '0');
    }
    // сужаем границы
    min_col_slit++;

    assert(min_col_slit < max_col_slit);
    // заполняем нижний край
    for (int col = min_col_slit; col < max_col_slit; col++) {
      matrix[(max_row_slit - 1) * matrix_size + col] = (text_pos < text.size() ? text[text_pos++] : '0');
    }
    // сужаем границы
    max_row_slit--;

    if (min_row_slit >= max_row_slit) {break;}
    // заполняем правый край
    for (int row = max_row_slit - 1; row >= min_row_slit; row--) {
      matrix[row * matrix_size + (max_col_slit - 1)] = (text_pos < text.size() ? text[text_pos++] : '0');
    }
    // сужаем границы
    max_col_slit--;
  }
  
  for (int row = 0; row < matrix_size; row++) {
    for (int col = 0; col < matrix_size; col++) {
      cout << matrix[row * matrix_size + col] << ' ';
    }
    cout << endl;
  }
  return 0;
}
Вывод на консоль:
Код:
g f e d c b a
h C B A z y x
i D Q P O N w
j E R W V M v
k F S T U L u
l G H I J K t
m n o p q r s
Пётр Седов вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Заполнение listbox значениями из массива. Заполнение массива. Gnaqeaz C# (си шарп) 9 23.10.2014 07:53
Заполнения массива спиралью(Ruby) Dyaside Ruby 0 13.12.2013 14:20
Вывод двумерного массива спиралью Valerie_Kotik Помощь студентам 1 28.12.2012 09:15
Сортировка двумерного числового массива «спиралью» vicvtor Помощь студентам 2 06.07.2011 09:10
Заполнение массива спиралью Fellics{новичок} Помощь студентам 1 01.12.2010 20:53