Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Mos\Dice;
- /**
- * A trait implementing histogram for integers.
- */
- trait HistogramTrait
- {
- /**
- * @var array $serie The numbers stored in sequence.
- */
- private $serie = [];
- /**
- * Get the serie.
- *
- * @return array with the serie.
- */
- public function getHistogramSerie()
- {
- return $this->serie;
- }
- /**
- * Print out the histogram, default is to print out only the numbers
- * in the serie, but when $min and $max is set then print also empty
- * values in the serie, within the range $min, $max.
- *
- * @param int $min The lowest possible integer number.
- * @param int $max The highest possible integer number.
- *
- * @return string representing the histogram.
- */
- public function printHistogram(int $min = null, int $max = null)
- {
- $arr = $this->getHistogramSerie();
- $histogramValue = [];
- $dataHistogram = array_count_values($arr);
- if ($min && $max) {
- for ($i = $min; $i <= $max; $i++) {
- if (array_key_exists($i, $dataHistogram)) {
- echo ' <br>' . "$i. " . str_repeat("*", $dataHistogram[$i]);
- } else {
- echo ' <br>' . "$i. ";
- }
- }
- } else {
- foreach ($dataHistogram as $key => $value) {
- echo ' <br>' . "$key. " . str_repeat("*", $value);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment