public static function stemAndLeafPlot(array $values, bool $print = false) : array
{
// Split each value into stem and leaf
sort($values);
$plot = array();
foreach ($values as $value) {
$stem = $value / 10;
$leaf = $value % 10;
if (!isset($plot[$stem])) {
$plot[$stem] = array();
}
$plot[$stem][] = $leaf;
}
// Fill in any empty keys in the distribution we had no stem/leaves for
$min = min(array_keys($plot));
$max = max(array_keys($plot));
for ($stem = $min; $stem <= $max; $stem++) {
if (!isset($plot[$stem])) {
$plot[$stem] = array();
}
}
ksort($plot);
// Optionally print the stem and leaf plot
if ($print === true) {
$length = max(array_map(function ($stem) {
return strlen($stem);
}, array_keys($plot)));
foreach ($plot as $stem => $leaves) {
printf("%{$length}d | %s\n", $stem, implode(' ', $leaves));
}
}
return $plot;
}