aboutsummaryrefslogtreecommitdiff
path: root/challenge-032/duncan-c-white/perl5/ch-2.pl
blob: 27b1f2920785ecbdc5677d2d73fd08d65a4a5b7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/perl
#
# Challenge 2: "ASCII bar chart: Write a function that takes a hashref
# where the keys are labels and the values are integer or floating point
# values. Generate a bar graph of the data and display it to stdout.
# 
# The input could be something like:
# 
# $data = { apple => 3, cherry => 2, banana => 1 };
# generate_bar_graph($data);
# 
# And would then generate something like this:
# 
#  apple | ############
# cherry | ########
# banana | ####
# 
# If you fancy then please try this as well: (a) the function could let
# you specify whether the chart should be ordered by (1) the labels, or
# (2) the values.
# 
# My notes: easy, especially using a histogram module I wrote recently.
#

use v5.10;	# for "say"
use strict;
use warnings;
use Data::Dumper;
use List::Util qw(max);
use Function::Parameters;

#
# my $str = generate_bar_graph( $data, $width, $bylabels );
#	Generate a bar graph from the frequency data in $data (a hashref),
#	where the maximum frequency occupies $width characters,
#	either sorted by labels (if $bylabels is true) or
#	by numeric values, returning a printable string form.
#
fun generate_bar_graph( $data, $width, $bylabels )
{
	my $maxv = max( values %$data );
	my $fieldw = max( map { length($_) } keys %$data );
	my $scale = int($width/$maxv);
	#die "debug: g_b_g: maxv=$maxv, fieldw=$fieldw, scale=$scale\n";
	my @str;
	my $fw = $fieldw+2;
	my @data = sort {
		$bylabels ? $a cmp $b : $data->{$b} <=> $data->{$a}
	} keys %$data;
	foreach my $k (@data)
	{
		my $v = $data->{$k};
		my $row = sprintf( '%'.$fw.'s | ', $k ). ('#' x ($v*$scale));
		push @str, $row;
	}
	return join("\n", @str );
}

my $data = { apple => 3, cherry => 2, banana => 1 };
my $str = generate_bar_graph( $data, 40, 1 );
say $str;