The Weekly Challenge 032

Count Instances & ASCII Bar Chart

Solutions on GitHub

Task 1: Count Instances

Write a script to count occurrences of unique lines read from input files or STDIN, and display a sorted summary. Include a -csv output option.

Example Output

apple 3 cherry 2 banana 1

Logic

We read lines sequentially from a file or STDIN, strip them, and store counts in a hash/dictionary map. We sort the results descending by count, then alphabetically, and print using the selected separator (tab or comma for CSV).

Perl Solution

ch-1.pl

my %count; while (my $line = <>) { chomp $line; $count{$line}++; } my $sep = $csv_output ? ',' : "\t"; for my $key (sort { $count{$b} <=> $count{$a} || $a cmp $b } keys %count) { print "$key$sep$count{$key}\n"; }

Python Solution

ch-1.py

count = {} with fileinput.input(files=args if args else ("-",)) as f: for line in f: word = line.strip() if word: count[word] = count.get(word, 0) + 1 sorted_items = sorted(count.items(), key=lambda x: (-x[1], x[0]))

Task 2: ASCII Bar Chart

Write a function to generate a horizontal ASCII bar graph from hash/dictionary data representing labels and values. Supports sorting by labels or values.

Example Output

apple | #################### cherry | ############# banana | ######

Logic

First, we calculate the maximum label length to right-align all labels nicely. Then, we find the maximum value to scale the bars proportionally (scaled to 20 characters max). We sort keys by labels or values depending on parameters, and output format templates.

Perl Solution

ch-2.pl

sub generate_bar_chart { my ($data, $sort_by) = @_; my $max_length = max(map { length } keys %$data); my $max_value = max(values %$data); my @sorted_keys; if ($sort_by eq 'values') { @sorted_keys = sort { $data->{$a} <=> $data->{$b} } keys %$data; } elsif ($sort_by eq 'values_desc') { @sorted_keys = sort { $data->{$b} <=> $data->{$a} } keys %$data; } else { @sorted_keys = sort { $a cmp $b } keys %$data; } for my $key (@sorted_keys) { my $bar_length = int(($data->{$key} / $max_value) * 20); $bar_length = 1 if $bar_length < 1; printf "%${max_length}s | %s\n", $key, '#' x $bar_length; } }

Python Solution

ch-2.py

def generate_bar_chart(data, sort_by="labels"): max_length = max(len(str(key)) for key in data.keys()) max_value = max(data.values()) if sort_by == "values": sorted_items = sorted(data.items(), key=lambda x: x[1]) elif sort_by == "values_desc": sorted_items = sorted(data.items(), key=lambda x: -x[1]) else: sorted_items = sorted(data.items(), key=lambda x: x[0]) for key, value in sorted_items: bar_length = int((value / max_value) * 20) bar_length = max(1, bar_length) print(f"{key:>{max_length}} | {'#' * bar_length}")