The weekly challenge 360 - Task 1: Text Justifier
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-360/#TASK1 3 # 4 # Task 1: Text Justifier 5 # ====================== 6 # 7 # You are given a string and a width. 8 # 9 # Write a script to return the string that centers the text within that width 10 # using asterisks * as padding. 11 # 12 ## Example 1 13 ## 14 ## Input: $str = "Hi", $width = 5 15 ## Output: "*Hi**" 16 ## 17 ## Text length = 2, Width = 5 18 ## Need 3 padding characters total 19 ## Left padding: 1 star, Right padding: 2 stars 20 # 21 # 22 ## Example 2 23 ## 24 ## Input: $str = "Code", $width = 10 25 ## Output: "***Code***" 26 ## 27 ## Text length = 4, Width = 10 28 ## Need 6 padding characters total 29 ## Left padding: 3 stars, Right padding: 3 stars 30 # 31 # 32 ## Example 3 33 ## 34 ## Input: $str = "Hello", $width = 9 35 ## Output: "**Hello**" 36 ## 37 ## Text length = 5, Width = 9 38 ## Need 4 padding characters total 39 ## Left padding: 2 stars, Right padding: 2 stars 40 # 41 # 42 ## Example 4 43 ## 44 ## Input: $str = "Perl", $width = 4 45 ## Output: "Perl" 46 ## 47 ## No padding needed 48 # 49 # 50 ## Example 5 51 ## 52 ## Input: $str = "A", $width = 7 53 ## Output: "***A***" 54 ## 55 ## Text length = 1, Width = 7 56 ## Need 6 padding characters total 57 ## Left padding: 3 stars, Right padding: 3 stars 58 # 59 # 60 ## Example 6 61 ## 62 ## Input: $str = "", $width = 5 63 ## Output: "*****" 64 ## 65 ## Text length = 0, Width = 5 66 ## Entire output is padding 67 # 68 ############################################################ 69 ## 70 ## discussion 71 ## 72 ############################################################ 73 # 74 # Just add "*" as long as $str is still shorter than $width. 75 # Add those alternating on the right side and the left side 76 # of $str to balance them out. 77 78 use v5.36; 79 80 text_justifier("Hi", 5); 81 text_justifier("Code", 10); 82 text_justifier("Hello", 9); 83 text_justifier("Perl", 4); 84 text_justifier("A", 7); 85 text_justifier("", 5); 86 87 sub text_justifier($str, $width) { 88 say "Input: \$str = \"$str\", \$width = $width"; 89 my $where = "r"; 90 while(length($str) < $width) { 91 if($where eq "r") { 92 $where = "l"; 93 $str .= "*"; 94 } else { 95 $where = "r"; 96 $str = "*" . $str; 97 } 98 } 99 say "Output: \"$str\""; 100 }