How to resolve the algorithm Align columns step by step in the Raku programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Align columns step by step in the Raku programming language

Table of Contents

Problem Statement

Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs:

Note that:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Align columns step by step in the Raku programming language

Source code in the raku programming language

my @lines = 
q|Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
|.lines;

my @widths;
 
for @lines { for .split('$').kv { @widths[$^key] max= $^word.chars; } }
for @lines { say |.split('$').kv.map: { (align @widths[$^key], $^word) ~ " "; } }
 
sub align($column_width, $word, $aligment = @*ARGS[0]) {
        my $lr = $column_width - $word.chars;
        my $c  = $lr / 2;
        given ($aligment) {
                when "center" { " " x $c.ceiling ~ $word ~ " " x $c.floor }
                when "right"  { " " x $lr        ~ $word                  }
                default       {                    $word ~ " " x $lr      }
        }
}


sub MAIN ($alignment where 'left'|'right', $file) {
    my @lines := $file.IO.lines.map(*.split('$').cache).cache;
    my @widths = roundrobin(|@lines).map(*».chars.max);
    my $align  = {left=>'-', right=>''}{$alignment};
    my $format = @widths.map( '%' ~ ++$ ~ '$' ~ $align ~ * ~ 's' ).join(' ') ~ "\n";
    printf $format, |$_ for @lines;
}


  

You may also check:How to resolve the algorithm String comparison step by step in the 11l programming language
You may also check:How to resolve the algorithm Simple windowed application step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Hello world/Newline omission step by step in the ML/I programming language
You may also check:How to resolve the algorithm Sort three variables step by step in the M2000 Interpreter programming language
You may also check:How to resolve the algorithm CSV to HTML translation step by step in the Vedit macro language programming language