Advertisement
NickAndNick

Магический квадрат

Dec 13th, 2017
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <set>
  2. template<typename Type, size_t Rank>
  3. bool magical(Type(&matrix)[Rank][Rank]) {
  4.     auto last = Rank * Rank;
  5.     std::set<Type> tmp;
  6.     auto s = 0u;
  7.     for (const auto &row : matrix) {
  8.         for (const auto value : row) {
  9.             if (value <= 0 || value > Type(last)) return false;
  10.             s += value;
  11.             tmp.insert(value);
  12.         }
  13.     }
  14.     if (s != last * (last + 1) / 2 || tmp.size() < last) return false;
  15.     auto sum = s / Rank;
  16.     auto a = 0u;
  17.     auto b = 0u;
  18.     for (auto i = 0u; i < Rank; ++i) {
  19.         a += matrix[i][i];
  20.         b += matrix[i][Rank - i - 1];
  21.     }
  22.     if (a != sum || b != sum) return false;
  23.     for (auto r = 0u; r < Rank; ++r) {
  24.         a = b = 0u;
  25.         for (auto c = 0u; c < Rank; ++c) {
  26.             a += matrix[r][c];
  27.             b += matrix[c][r];
  28.         }
  29.         if (a != sum || b != sum) return false;
  30.     }
  31.     return true;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement