Current articles

The game of life: my php version

The game of life

This is my version of the game of life.

My solution

This is my version of the game of life.

<?php

  fscanf(STDIN, "%d %d",
      $width,
      $height
  );

  $board = [];
  $next = [];

  for ($i = 0; $i < $height; $i++) {
      fscanf(STDIN, "%s", $line);
      $board[] = str_split($line);
  }

  function countNeighbors($board, $i, $j) {
      $neighbors = 0;

      // - horizontally
      $neighbors += isset($board[$i - 1][$j]) && $board[$i - 1][$j] == 1;
      $neighbors += isset($board[$i + 1][$j]) && $board[$i + 1][$j] == 1;

      // | vertically
      $neighbors += isset($board[$i][$j - 1]) && $board[$i][$j - 1] == 1;
      $neighbors += isset($board[$i][$j + 1]) && $board[$i][$j + 1] == 1;

      // / diagonally
      $neighbors += isset($board[$i - 1][$j - 1]) && $board[$i - 1][$j - 1] == 1;
      $neighbors += isset($board[$i + 1][$j + 1]) && $board[$i + 1][$j + 1] == 1;

      // \ diagonally
      $neighbors += isset($board[$i - 1][$j + 1]) && $board[$i - 1][$j + 1] == 1;
      $neighbors += isset($board[$i + 1][$j - 1]) && $board[$i + 1][$j - 1] == 1;

      return $neighbors;
  }

  for ($i = 0; $i < $height; $i++) {
      for ($j = 0; $j < $width; $j++) {
          if (isset($board[$i][$j])) {
              $neighbors = countNeighbors($board, $i, $j);
              $next[$i][$j] = $board[$i][$j] == 1
                  ? !($neighbors < 2 || $neighbors > 3) ? '1' : '0'
                  : $next[$i][$j] = $neighbors == 3 ? '1' : '0';
          }
      }
  }

  for ($i = 0; $i < $height; $i++) {
      for ($j = 0; $j < $width; $j++) {
          echo $next[$i][$j];
      }
      echo "\n";
  }

Conclusions

Comments

Links