aboutsummaryrefslogtreecommitdiff
path: root/challenge-153
diff options
context:
space:
mode:
authorLubos Kolouch <lubos@kolouch.net>2022-02-26 13:11:09 +0100
committerLubos Kolouch <lubos@kolouch.net>2022-02-26 13:11:09 +0100
commitf5ef44c5be4ea6d4e3137014aa5788236eab4b6d (patch)
tree6168f1c09728aa9e84bce547645f1797463964d6 /challenge-153
parentdecb68c5a9c212ae099534722c360da5644ba498 (diff)
downloadperlweeklychallenge-club-f5ef44c5be4ea6d4e3137014aa5788236eab4b6d.tar.gz
perlweeklychallenge-club-f5ef44c5be4ea6d4e3137014aa5788236eab4b6d.tar.bz2
perlweeklychallenge-club-f5ef44c5be4ea6d4e3137014aa5788236eab4b6d.zip
feat(lubos-kolouch/php/ch-1.php): Challenge 153 Task 1 PHP LK
Diffstat (limited to 'challenge-153')
-rw-r--r--challenge-153/lubos-kolouch/php/ch-1.php59
1 files changed, 59 insertions, 0 deletions
diff --git a/challenge-153/lubos-kolouch/php/ch-1.php b/challenge-153/lubos-kolouch/php/ch-1.php
new file mode 100644
index 0000000000..7b7c50e199
--- /dev/null
+++ b/challenge-153/lubos-kolouch/php/ch-1.php
@@ -0,0 +1,59 @@
+<?php
+
+class LeftFactCalculator {
+
+ public function __construct() {
+ # keep seen factorials in a cache to speed things up
+ $this->fact_cache = [0 => 1];
+ $this->left_fact_cache = [0 => 0];
+ }
+
+ public function calculate_factorial(int $what) {
+
+ if (array_key_exists($what, $this->fact_cache)) {
+ return $this->fact_cache[$what];
+ }
+
+ # let's utilize the fact that we are processing the numbers in sequence
+ $this->fact_cache[$what] = $what * $this->fact_cache[$what - 1];
+
+ return $this->fact_cache[$what];
+ }
+
+ public function calculate_left_fact(int $what) {
+
+ if (array_key_exists($what, $this->left_fact_cache)) {
+ return $this->left_fact_cache[$what];
+ }
+
+ # let's utilize the fact that we are processing the numbers in sequence
+ $this->left_fact_cache[$what] = $this->calculate_factorial($what - 1) + $this->left_fact_cache[$what - 1];
+
+ return $this->left_fact_cache[$what];
+ }
+
+ public function get_left_factorial(int $what) {
+
+ $output = [];
+
+ foreach (range(1, $what) as $i) {
+ $output[] = $this->calculate_left_fact($i);
+ }
+
+ return $output;
+ }
+}
+
+$calculator = new LeftFactCalculator();
+array_diff($calculator->get_left_factorial(10), [
+ 1,
+ 2,
+ 4,
+ 10,
+ 34,
+ 154,
+ 874,
+ 5914,
+ 46234,
+ 409114,
+ ]) == [] or throw new Exception("Failed test 1");