Skip to content

Instantly share code, notes, and snippets.

@Golpha
Last active May 20, 2016 12:23
Show Gist options
  • Save Golpha/fed3e05d1738ed3dfce3 to your computer and use it in GitHub Desktop.
Save Golpha/fed3e05d1738ed3dfce3 to your computer and use it in GitHub Desktop.
Pyramid Iteration
0
101
21012
3210123
432101234
54321012345
6543210123456
765432101234567
87654321012345678
9876543210123456789
A
BAB
CBABC
DCBABCD
EDCBABCDE
FEDCBABCDEF
GFEDCBABCDEFG
HGFEDCBABCDEFGH
IHGFEDCBABCDEFGHI
JIHGFEDCBABCDEFGHIJ
KJIHGFEDCBABCDEFGHIJK
LKJIHGFEDCBABCDEFGHIJKL
MLKJIHGFEDCBABCDEFGHIJKLM
NMLKJIHGFEDCBABCDEFGHIJKLMN
ONMLKJIHGFEDCBABCDEFGHIJKLMNO
PONMLKJIHGFEDCBABCDEFGHIJKLMNOP
QPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQ
RQPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQR
SRQPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQRS
TSRQPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQRST
UTSRQPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQRSTU
VUTSRQPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQRSTUV
WVUTSRQPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQRSTUVW
XWVUTSRQPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQRSTUVWX
YXWVUTSRQPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQRSTUVWXY
ZYXWVUTSRQPONMLKJIHGFEDCBABCDEFGHIJKLMNOPQRSTUVWXYZ
<?php
version_compare(PHP_VERSION, '5.4.0', '>=') or die('Update your PHP Version, your version is no longer supported by php.net');
class PyramidIterator implements Iterator {
private $range;
private $row;
public function __construct(array $range)
{
$this->range = $range;
$this->rewind();
}
public function getIndentLength()
{
return count($this->range) - 1 - $this->row;
}
public function key()
{
return $this->row;
}
public function current()
{
$left = array_reverse(array_slice($this->range, 0 , $this->row + 1));
$right = $this->key()
? array_slice($this->range, 1, $this->row)
: [];
return join($left).join($right);
}
public function next()
{
$this->row++;
}
public function valid()
{
return count($this->range) > $this->row;
}
public function rewind()
{
$this->row = 0;
}
}
header('Content-Type: text/plain; charset=utf-8');
$content = [];
$iterator = new PyramidIterator(range(0,9));
foreach ( $iterator as $row ) {
$content[] = str_repeat(' ', $iterator->getIndentLength()).$row;
}
echo join(PHP_EOL, $content);
echo PHP_EOL.PHP_EOL;
$content = [];
$iterator = new PyramidIterator(range('A', 'Z'));
foreach ( $iterator as $row ) {
$content[] = str_repeat(' ', $iterator->getIndentLength()).$row;
}
echo join(PHP_EOL, $content);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment