Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //stick it in a while loop so you don't have to keep re-running
- while (1) {
- //initialize the triangle array
- $triangle = array();
- echo "INPUT ZERO-BASED COORDINATES\n";
- // open a handle to standard input in read mode, get the first line.
- $handle = fopen("php://stdin", "r");
- $line = fgets($handle);
- //split it up by the comma.
- $coords = explode(',', trim($line));
- // if the numbers are anything but digits, it's not a valid input.
- // could probably use preg_ functions to do all input matching (forget explode)
- // but I'm too lazy.
- if (!preg_match('/^\d+$/', $coords[0]) && !preg_match('/^\d+$/', $coords[1])) {
- die("INVALID INPUT\n");
- }
- //get the result
- $result = calculate($coords[1], $coords[0]);
- echo "RESULT: " . $result . "\n";
- // Get the string length of $result, pad all other results to this size
- $numsize = strlen($result);
- // render the triangle.
- for ($y = 0; $y <= $coords[0]; $y++) {
- // for every row go through all the values
- for ($x = 0; $x <= $y; $x++) {
- //if this has a value, pad it to $numsize
- //otherwise output asterisks
- if (isset($triangle[$y][$x])) {
- $padded_item = str_pad($triangle[$y][$x], $numsize, " ");
- echo $padded_item . " ";
- } else
- echo str_repeat("*", $numsize) . " ";
- }
- echo "\n";
- }
- }
- // Calculate a point on the pascal's triangle
- // takes zero based x and y ints
- function calculate($x, $y) {
- // grab that triangle out of the global scope
- global $triangle;
- // if it's the first or last value in a row, it'll be 1.
- if (($x == 0) || ($x == $y)) {
- return 1;
- }
- // if it's outside of the row's values it'll be a zero
- // there could be some argument to this, but I feel pretty secure in
- // considering this to be the case.
- if ($x > $y) {
- return 0;
- }
- // if the value directly above the target value is undefined, perform a calculate() on it
- if (!isset($triangle[$y - 1][$x])) {
- calculate($x, $y - 1);
- }
- // same as above but for the value above and one to the left.
- if (!isset($triangle[$y - 1][$x - 1])) {
- calculate($x - 1, $y - 1);
- }
- // define this location on the triangle and return it.
- $triangle[$y][$x] = $triangle[$y - 1][$x] + $triangle[$y - 1][$x - 1];
- return $triangle[$y][$x];
- }
- ?>
Add Comment
Please, Sign In to add comment