Skip to content

Instantly share code, notes, and snippets.

@itarato
Created September 13, 2014 23:17
Show Gist options
  • Save itarato/444eb6ecba89405920c2 to your computer and use it in GitHub Desktop.
Save itarato/444eb6ecba89405920c2 to your computer and use it in GitHub Desktop.
Regular expression image generation
<?php
/**
* Example: php file.php 6 "1"
*/
class Rec {
protected $grid = [];
protected $fourDirectionMap = [[0, 0], [1, 0], [1, 1], [0, 1]];
protected $size;
protected $regex;
public function __construct($aSize = 3, $aRegex = '') {
$this->size = pow(2, $aSize);
$this->regex = $aRegex;
$this->emptyGrid();
$this->gen($this->size, 0, 0);
$this->printGrid();
}
protected function emptyGrid() {
for ($y = 0; $y < $this->size; $y++) {
for ($x = 0; $x < $this->size; $x++) {
$this->grid[$x][$y] = 0;
}
}
}
protected function printGrid() {
echo "\n\n";
for ($y = 0; $y < $this->size; $y++) {
for ($x = 0; $x < $this->size; $x++) {
$isMatch = preg_match('/' . $this->regex . '/', $this->grid[$x][$y]);
echo $isMatch ? ' ' : 'O ';
// echo $this->grid[$x][$y] . ' ';
}
echo "\n";
}
echo "\n\n";
}
protected function gen($size, $startX, $startY, $segment = '') {
$newSize = $size >> 1;
if ($newSize > 1) {
$this->gen($newSize, $startX, $startY, $segment . '1');
$this->gen($newSize, $startX + $newSize, $startY, $segment . '2');
$this->gen($newSize, $startX + $newSize, $startY + $newSize, $segment . '3');
$this->gen($newSize, $startX, $startY + $newSize, $segment . '4');
}
else {
foreach ($this->fourDirectionMap as $index => $direction) {
$this->grid[$startX + $direction[0]][$startY + $direction[1]] = $segment . ($index + 1);
}
}
}
}
new Rec($argv[1], $argv[2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment