The weekly challenge 332 - Task 1: Binary Date
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-332/#TASK1 3 # 4 # Task 1: Binary Date 5 # =================== 6 # 7 # You are given a date in the format YYYY-MM-DD. 8 # 9 # Write a script to convert it into binary date. 10 # 11 # Example 1 12 # 13 # Input: $date = "2025-07-26" 14 # Output: "11111101001-111-11010" 15 # 16 # 17 # Example 2 18 # 19 # Input: $date = "2000-02-02" 20 # Output: "11111010000-10-10" 21 # 22 # 23 # Example 3 24 # 25 # Input: $date = "2024-12-31" 26 # Output: "11111101000-1100-11111" 27 # 28 ############################################################ 29 ## 30 ## discussion 31 ## 32 ############################################################ 33 # 34 # We split the date into its single parts, then we create the 35 # binary representation for all of those and put them together 36 # again in the end. 37 # To turn a number into its binary representation, we just check 38 # wether it is even or not so we know whether the last digit will 39 # be a "1" or a "0", and append that to the binary representation 40 # of the integer value of the number divided by 2. Of course we 41 # return an empty string in case of an input of "0" to stop 42 # processing. 43 44 use v5.36; 45 46 binary_date("2025-07-26"); 47 binary_date("2000-02-02"); 48 binary_date("2024-12-31"); 49 50 51 sub binary_date($date) { 52 say "Input: \"$date\""; 53 my @numbers = split /-/, $date; 54 my @binary_numbers = (); 55 foreach my $num (@numbers) { 56 push @binary_numbers, binary($num); 57 } 58 my $binary_date = join("-", @binary_numbers); 59 say "Output: \"$binary_date\""; 60 } 61 62 sub binary($decimal) { 63 if($decimal > 0) { 64 if($decimal % 2) { 65 return binary(int($decimal/2)) . "1"; 66 } else { 67 return binary(int($decimal/2)) . "0"; 68 } 69 } 70 return ""; 71 } 72