Last active
April 13, 2017 18:11
-
-
Save algb12/b6881e5bc6cdb7024d4ab1d27eee736a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// AUTHOR: algb12 | |
// An implementation of the Pascal's triangle in PHP | |
// It is relatively fast, even with values in the 100s and 1000s | |
function pascalRow($n) | |
{ | |
// Every Pascal's triangle starts with a 1 | |
$row = [1]; | |
// If row number ($n) is 0, just return an array with 1 in it | |
if ($n === 0) { | |
return $row; | |
} | |
// No answer for a number less than 1 | |
if ($n < 1) { | |
return; | |
} | |
// While current iteration ($i) is less than $n, process row | |
for ($i = 0; $i < $n; ++$i) { | |
// Adjust last index based on count to zero-based array by subtracting 1 | |
$lastIdx = count($row) - 1; | |
// New row is initially an empty array | |
$newRow = []; | |
// First element in Pascal's triangle is always 1 | |
$newRow[0] = 1; | |
// For each element in the row, do action below | |
foreach ($row as $k => $v) { | |
// If current element is last element | |
if ($k === $lastIdx) { | |
// Append a 1 to new row (rows always end in a 1) | |
$newRow[$k + 1] = 1; | |
// Set current row to new row | |
$row = $newRow; | |
// Exit this loop as end of row is reached | |
break; | |
} | |
// If current element is not last element | |
if ($k !== $lastIdx) { | |
// Append sum of current element and next one to new row | |
$newRow[$k + 1] = $row[$k] + $row[$k + 1]; | |
} | |
} | |
} | |
return $row; | |
} | |
// Test with small integer | |
print_r(pascalRow(4)); | |
// Test with another small integer | |
print_r(pascalRow(7)); | |
// Test with a larger integer | |
print_r(pascalRow(43)); | |
// Test with a very large integer | |
print_r(pascalRow(732)); | |
// This is like nCr for n = 33 and r = 7 | |
echo pascalRow(33)[7]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment