The weekly challenge 349 - Task 2: Meeting Point
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-349/#TASK2 3 # 4 # Task 2: Meeting Point 5 # ===================== 6 # 7 # You are given instruction string made up of U (up), D (down), L (left) and R 8 # (right). 9 # 10 # Write a script to return true if following the instruction, you meet (0,0) at 11 # any point along the sequence. 12 # 13 ## Example 1 14 ## 15 ## Input: $path = "ULD" 16 ## Output: false 17 ## 18 ## (-1,1) <- (0,1) 19 ## | ^ 20 ## v | 21 ## (-1,0) (0,0) 22 # 23 # 24 ## Example 2 25 ## 26 ## Input: $path = "ULDR" 27 ## Output: true 28 ## 29 ## (-1,1) <- (0,1) 30 ## | ^ 31 ## v | 32 ## (-1,0) -> (0,0) 33 # 34 # 35 ## Example 3 36 ## 37 ## Input: $path = "UUURRRDDD" 38 ## Output: false 39 ## 40 ## (0,3) -> (1,3) -> (2,3) -> (3,3) 41 ## ^ | 42 ## | v 43 ## (0,2) (3,2) 44 ## ^ | 45 ## | v 46 ## (0,1) (3,1) 47 ## ^ | 48 ## | v 49 ## (0,0) (3,0) 50 # 51 # 52 ## Example 4 53 ## 54 ## Input: $path = "UURRRDDLLL" 55 ## Output: true 56 ## 57 ## (0,2) -> (1,2) -> (2,2) -> (3,2) 58 ## ^ | 59 ## | v 60 ## (0,1) (3,1) 61 ## ^ | 62 ## | v 63 ## (0,0) <- (1,0) <- (1,1) <- (3,0) 64 # 65 # 66 ## Example 5 67 ## 68 ## Input: $path = "RRUULLDDRRUU" 69 ## Output: true 70 ## 71 ## (0,2) <- (1,2) <- (2,2) 72 ## | ^ 73 ## v | 74 ## (0,1) (2,1) 75 ## | ^ 76 ## v | 77 ## (0,0) -> (1,0) -> (2,1) 78 # 79 ############################################################ 80 ## 81 ## discussion 82 ## 83 ############################################################ 84 # 85 # We walk the path and check where we are. If we are back to 86 # (0, 0) at any time during the walk, we can return true already. 87 # In the end, if we didn't return true at some point, we can 88 # return false. 89 # 90 use v5.36; 91 92 meeting_point("ULD"); 93 meeting_point("ULDR"); 94 meeting_point("UUURRRDDD"); 95 meeting_point("UURRRDDLLL"); 96 meeting_point("RRUULLDDRRUU"); 97 98 sub meeting_point($path) { 99 say "Input: '$path'"; 100 my ($x, $y) = (0, 0); 101 foreach my $step (split //, $path) { 102 if($step eq "U") { 103 $y++; 104 } elsif ($step eq "D") { 105 $y--; 106 } elsif ($step eq "L") { 107 $x--; 108 } else { 109 $x++; 110 } 111 say "($x, $y)"; 112 if($x == 0 and $y == 0) { 113 return say "Output: true"; 114 } 115 } 116 say "Output: false"; 117 } 118