Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
source
magic_square_module

*.ilk
*.obj
*.pdb
51 changes: 50 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,50 @@
<h1>Some changes</h1>
<div align="center">
<h1>⚠️Важное! Эта ветка предназначена для Windows и компилятора VS. Если у вас Linux и компилятор g++, используйте main ветку.⚠️</h1>
</div>

<br>

<div align="center">
<h2>🧮 О проекте</h2>
</div>
<p>Магический квадрат — это квадратная таблица размера n×n, заполненная различными числами таким образом, что сумма чисел в каждой строке, каждом столбце и на обеих диагоналях одинакова. Данный проект реализует генерацию магических квадратов нечётного порядка (n = 2k + 1) с использованием классического сиамского метода, также известного как метод де ла Лубера.</p>

<br>

<div align="center">
<h2>📊 Основные возможности</h2>
</div>
<div>
<p>✅ Генерация магических квадратов любого нечётного порядка (3, 5, 7, ...)</p>
<p>✅ Проверка магических свойств (суммы строк, столбцов, диагоналей)</p>
<p>✅ Сохранение результатов в текстовый файл</p>
<p>✅ Визуально приятное форматирование вывода</p>
</div>

<br>


<div align="center">
<h2>🚀 Установка(легкая)</h2>
</div>
<h3>Скачайте файл source.exe и откройте его</h3>


<div align="center">
<h2>🚀 Установка(сложная)</h2>
</div>

<h3>Предварительные требования</h3>
<p>Windows</p>
<p>Компилятор C++11 или новее (Visual Studio)</p>

<h3>Сборка из исходного кода</h3>

<h4>Клонировать репозиторий :</h4>
<p>Откройте настроенный Vs code с помощью компилятора visual Studio и выполните запись в terminal :</p>
<pre><code>git clone -b Windows_edition https://github.com/matb22/Magic-square.git</code></pre>
<p>Откройте файл source.cpp и запустите процесс компиляции с помощью кнопки в vs code</p>
<p>Done!</p>



10 changes: 8 additions & 2 deletions magic_square.h
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
#ifndef MAGIC_SQUARE_H
#define MAGIC_SQUARE_H

void generateMagicSquare(int n) ;

#include "magic_square_module.cpp"

void DisplaySquareInfo() ;
void OutputSquareConsole(int n, const std::vector<std::vector<int>>& magic_square);
void OutputSquareFile(int n, const std::vector<std::vector<int>>& magic_square);
int CountDigits(int number);
bool IsMagicSquareValid(const std::vector<std::vector<int>>& square);
void GenerateMagicSquare(int square_size) ;




#endif
233 changes: 100 additions & 133 deletions magic_square_module.cpp
Original file line number Diff line number Diff line change
@@ -1,173 +1,140 @@
#include <iostream>
#include <iomanip>
#include <vector>
#include <fstream>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <vector>

void OutputSquareConsole(int n, const std::vector<std::vector<int>>& magic_square);
void OutputSquareFile(int n, const std::vector<std::vector<int>>& magic_square);
int CountDigits(int number);
bool IsMagicSquareValid(const std::vector<std::vector<int>>& square);



void Output_square_console(int n , std::vector<std::vector<int>> magicSquare) ;
void Output_square_file(int n , std::vector<std::vector<int>> magicSquare);
int countDigits(int n ) ;
bool isMagicSquareValid(const std::vector<std::vector<int>>& square) ;

void generateMagicSquare(int n) {
void GenerateMagicSquare(int square_size) {
const int n = square_size;



std::vector<std::vector<int>> magicSquare(n, std::vector<int>(n, 0));
std::vector<std::vector<int>> magic_square(n, std::vector<int>(n, 0));

int i = 0;
int j = n / 2;

for (int num = 1; num <= n * n; num++) {
magicSquare[i][j] = num;
for (int num = 1; num <= n * n; ++num) {
magic_square[i][j] = num;

int next_i = (i - 1 + n) % n;
int next_j = (j + 1) % n;
const int next_i = (i - 1 + n) % n;
const int next_j = (j + 1) % n;

if (magicSquare[next_i][next_j] != 0) {
if (magic_square[next_i][next_j] != 0) {
i = (i + 1) % n;
}
else {
} else {
i = next_i;
j = next_j;
}
}

if (isMagicSquareValid(magicSquare)) {
std::cout << "✓ Квадрат корректный!\n";
}
else {
std::cout << "✗ Ошибка: квадрат некорректный!\n";
}





if (IsMagicSquareValid(magic_square)) {
std::cout << "✓ Квадрат корректный!\n";
} else {
std::cout << "✗ Ошибка: квадрат некорректный!\n";
}

Output_square_console(n , magicSquare) ;
Output_square_file( n , magicSquare) ;

OutputSquareConsole(n, magic_square);
OutputSquareFile(n, magic_square);
}


void Output_square_console(int n , std::vector<std::vector<int>> magicSquare) {
void OutputSquareConsole(int n, const std::vector<std::vector<int>>& magic_square) {
std::cout << "Магический квадрат порядка " << n << ":\n";
std::cout << "Сумма в каждой строке, столбце и диагонали = "
<< n * (n * n + 1) / 2 << "\n\n";
std::cout << "Сумма в каждой строке, столбце и диагонали = "
<< n * (n * n + 1) / 2 << "\n\n";

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout << std::setw(countDigits(n*n) + 1) << magicSquare[i][j] << " ";
const int column_width = CountDigits(n * n) + 1;

for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
std::cout << std::setw(column_width) << magic_square[i][j] << " ";
}
std::cout << std::endl;
std::cout << "\n";
}
}

void OutputSquareFile(int n, const std::vector<std::vector<int>>& magic_square) {
std::ofstream output_file("magic_square.txt");
if (!output_file.is_open()) {
std::cerr << "Ошибка: не удалось открыть файл для записи.\n";
return;
}

output_file << "Магический квадрат порядка " << n << ":\n";
output_file << "Сумма в каждой строке, столбце и диагонали = "
<< n * (n * n + 1) / 2 << "\n\n";

void Output_square_file(int n , std::vector<std::vector<int>> magicSquare) {
std::ofstream f2 ;
f2.open("magic_square.txt" , std::ios::out) ;
const int column_width = CountDigits(n * n) + 1;

f2 << "Магический квадрат порядка " << n << ":\n";
f2 << "Сумма в каждой строке, столбце и диагонали = "
<< n * (n * n + 1) / 2 << "\n\n";

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
f2 << std::setw(countDigits(n*n) + 1) << magicSquare[i][j] << " ";
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
output_file << std::setw(column_width) << magic_square[i][j] << " ";
}
f2 << std::endl;
output_file << "\n";
}

f2.close() ;
}





int countDigits(int n ) {

if (n == 0) return 1;
if (n < 0) n = -n;

return static_cast<int>(log10(n)) + 1;
}







void Square_info() {
std::cout<<"\n\n Магический квадрат — это квадратная таблица размером n×n, заполненная разными\n" ;
std::cout<<" натуральными числами (обычно от 1 до n²) таким образом, что:\n" ;
std::cout<<"* Cумма чисел в каждой строке, каждом столбце и на обеих диагоналях — одинаковая.\n\n" ;


int CountDigits(int number) {
if (number == 0) return 1;
if (number < 0) number = -number;

return static_cast<int>(std::log10(number)) + 1;
}

void DisplaySquareInfo() {
std::cout << "\n\n Магический квадрат — это квадратная таблица размером n×n,\n"
<< " заполненная разными натуральными числами (обычно от 1 до n²)\n"
<< " таким образом, что сумма чисел в каждой строке, каждом столбце\n"
<< " и на обеих диагоналях — одинаковая.\n\n";
}




bool isMagicSquareValid(const std::vector<std::vector<int>>& square) {
int n = square.size();
if (n % 2 == 0) return false;

// Проверяем, что все числа от 1 до n² присутствуют ровно один раз
std::vector<bool> found(n * n + 1, false);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int num = square[i][j];
if (num < 1 || num > n * n || found[num]) {
return false;
}
found[num] = true;
}
}

// Вычисляем магическую константу
int magicSum = n * (n * n + 1) / 2;

// Проверяем суммы строк
for (int i = 0; i < n; i++) {
int rowSum = 0;
for (int j = 0; j < n; j++) {
rowSum += square[i][j];
}
if (rowSum != magicSum) return false;
}

// Проверяем суммы столбцов
for (int j = 0; j < n; j++) {
int colSum = 0;
for (int i = 0; i < n; i++) {
colSum += square[i][j];
}
if (colSum != magicSum) return false;
bool IsMagicSquareValid(const std::vector<std::vector<int>>& square) {
const int n = square.size();
if (n <= 0 || n % 2 == 0) return false;

std::vector<bool> found(n * n + 1, false);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
const int num = square[i][j];
if (num < 1 || num > n * n || found[num]) {
return false;
}
found[num] = true;
}

// Проверяем главную диагональ
int diag1Sum = 0;
for (int i = 0; i < n; i++) {
diag1Sum += square[i][i];
}

const int magic_sum = n * (n * n + 1) / 2;

for (int i = 0; i < n; ++i) {
int row_sum = 0;
for (int j = 0; j < n; ++j) {
row_sum += square[i][j];
}
if (diag1Sum != magicSum) return false;

// Проверяем побочную диагональ
int diag2Sum = 0;
for (int i = 0; i < n; i++) {
diag2Sum += square[i][n - 1 - i];
if (row_sum != magic_sum) return false;
}

for (int j = 0; j < n; ++j) {
int col_sum = 0;
for (int i = 0; i < n; ++i) {
col_sum += square[i][j];
}
if (diag2Sum != magicSum) return false;

return true;
if (col_sum != magic_sum) return false;
}

int diag1_sum = 0;
for (int i = 0; i < n; ++i) {
diag1_sum += square[i][i];
}
if (diag1_sum != magic_sum) return false;

int diag2_sum = 0;
for (int i = 0; i < n; ++i) {
diag2_sum += square[i][n - 1 - i];
}
if (diag2_sum != magic_sum) return false;

return true;
}
Loading