The weekly challenge 395 - Task 1: Complex Number
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-395/#TASK1 3 # 4 # Task 1: Complex Number 5 # ====================== 6 # 7 # You are given two complex numbers as string. 8 # 9 # Write a script to return the multiplication of the given complex numbers. 10 # 11 ## Using the formula: (a + bi) x (c + di) = (ac - bd) + (ad + bc)i 12 # 13 ## Example 1 14 ## 15 ## Input: $num1 = "1+1i", $num2 = "1+1i" 16 ## Output: "0+2i" 17 # 18 ## Example 2 19 ## 20 ## Input: $num1 = "1+(-1)i", $num2 = "1+(-1)i" 21 ## Output: "0+(-2)i" 22 # 23 ## Example 3 24 ## 25 ## Input: $num1 = "0+3i", $num2 = "0+4i" 26 ## Output: "-12+0i" 27 # 28 ## Example 4 29 ## 30 ## Input: $num1 = "3+4i", $num2 = "3+(-4)i" 31 ## Output: "25+0i" 32 # 33 ## Example 5 34 ## 35 ## Input: $num1 = "50+(-20)i", $num2 = "-10+30i" 36 ## Output: "100+1700i" 37 # 38 ############################################################ 39 ## 40 ## discussion 41 ## 42 ############################################################ 43 # 44 # This is straight forward: parse the number strings, calculate the 45 # product, return it as a string. 46 47 use v5.36; 48 49 sub complex_number($num1, $num2) { 50 say "Input: \"$num1\", \"$num2\""; 51 my ($a_, $b_) = parse_num($num1); 52 my ($c, $d) = parse_num($num2); 53 my $real = $a_ * $c - $b_ * $d; 54 my $imaginary = $a_ * $d + $b_ * $c; 55 if($imaginary < 0) { 56 $imaginary = "($imaginary)"; 57 } 58 say "Output: \"$real+${imaginary}i"; 59 } 60 61 sub parse_num($num) { 62 my ($real, $imaginary); 63 $num =~ s/^(-?[\d.]+)\+//; 64 $real = $1; 65 $num =~ s/i$//; 66 $num =~ s/\(//; 67 $num =~ s/\)//; 68 $imaginary = $num; 69 return ($real, $imaginary); 70 } 71 72 complex_number("1+1i", "1+1i"); 73 complex_number("1+(-1)i", "1+(-1)i"); 74 complex_number("0+3i", "0+4i"); 75 complex_number("3+4i", "3+(-4)i"); 76 complex_number("50+(-20)i", "-10+30i");