JosepRivaille

P21600: El joc de la vida (1)

May 27th, 2015
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5.  
  6. typedef vector<char> Row;
  7. typedef vector<Row> Matrix;
  8.  
  9. void read_matrix(Matrix& M) {
  10.     int f = M.size();
  11.     int c = M[0].size();
  12.     for (int i = 0; i < f; ++i) {
  13.         for (int j = 0; j < c; ++j) {
  14.             cin >> M[i][j];
  15.         }
  16.     }
  17. }
  18.  
  19. void wrote_matrix(Matrix& M) {
  20.     int f = M.size();
  21.     int c = M[0].size();
  22.     for (int i = 0; i < f; ++i) {
  23.         for (int j = 0; j < c; ++j) {
  24.             cout << M[i][j];
  25.         }
  26.         cout << endl;
  27.     }
  28. }
  29.  
  30. int count_pos(const Matrix& M, int i, int j) {
  31.     int f = M.size();
  32.     int c = M[0].size();
  33.     int add_i = i + 1;
  34.     int add_j = j + 1;
  35.     int sub_i = i - 1;
  36.     int sub_j = j - 1;
  37.     bool exists_add_i = add_i < f;
  38.     bool exists_add_j = add_j < c;
  39.     bool exists_sub_i = sub_i >= 0;
  40.     bool exists_sub_j = sub_j >= 0;
  41.     int count = 0;
  42.     if (exists_sub_i && M[sub_i][j] == 'B') ++count; //Nord
  43.     if (exists_sub_j && M[i][sub_j] == 'B') ++count; //Oest
  44.     if (exists_add_i && M[add_i][j] == 'B') ++count; //Sud
  45.     if (exists_add_j && M[i][add_j] == 'B') ++count; //Est
  46.     if (exists_sub_i && exists_sub_j && M[sub_i][sub_j] == 'B') ++count; //Nord-oest
  47.     if (exists_sub_i && exists_add_j && M[sub_i][add_j] == 'B') ++count; //Nord-est
  48.     if (exists_add_i && exists_add_j && M[add_i][add_j] == 'B') ++count; //Sud-est
  49.     if (exists_add_i && exists_sub_j && M[add_i][sub_j] == 'B') ++count; //Sud-oest
  50.     return count;
  51. }
  52.  
  53. Matrix modify_matrix(const Matrix& M) {
  54.     int f = M.size();
  55.     int c = M[0].size();
  56.     Matrix next_state(f, Row(c));
  57.     next_state = M;
  58.     for (int i = 0; i < f; ++i) {
  59.         for (int j = 0; j < c; ++j) {
  60.             int aux = count_pos(M, i, j);
  61.             if (M[i][j] == '.' && aux == 3) next_state[i][j] = 'B';
  62.             else if (M[i][j] == 'B' && aux != 2 && aux != 3) next_state[i][j] = '.';
  63.         }
  64.     }
  65.     return next_state;
  66. }
  67.  
  68. int main() {
  69.     int f, c;
  70.     bool primer = true;
  71.     while (cin >> f >> c && (f != 0 && c != 0)) {
  72.         if (not primer) cout << endl;
  73.         else primer = false;
  74.         Matrix M(f, Row(c));
  75.         read_matrix(M);
  76.         Matrix Result(f, Row(c));
  77.         Result = modify_matrix(M);
  78.         wrote_matrix(Result);
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment