The weekly challenge 261: Task 2: Multiply by Two
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-261/#TASK2 3 # 4 # Task 2: Multiply by Two 5 # ======================= 6 # 7 # You are given an array of integers, @ints and an integer $start. 8 # 9 # Write a script to do the followings: 10 # 11 # a) Look for $start in the array @ints, if found multiply the number by 2 12 # b) If not found stop the process otherwise repeat 13 # 14 # In the end return the final value. 15 # 16 ## Example 1 17 ## 18 ## Input: @ints = (5,3,6,1,12) and $start = 3 19 ## Output: 24 20 ## 21 ## Step 1: 3 is in the array so 3 x 2 = 6 22 ## Step 2: 6 is in the array so 6 x 2 = 12 23 ## Step 3: 12 is in the array so 12 x 2 = 24 24 ## 25 ## 24 is not found in the array so return 24. 26 # 27 ## Example 2 28 ## 29 ## Input: @ints = (1,2,4,3) and $start = 1 30 ## Output: 8 31 ## 32 ## Step 1: 1 is in the array so 1 x 2 = 2 33 ## Step 2: 2 is in the array so 2 x 2 = 4 34 ## Step 3: 4 is in the array so 4 x 2 = 8 35 ## 36 ## 8 is not found in the array so return 8. 37 # 38 ## Example 3 39 ## 40 ## Input: @ints = (5,6,7) and $start = 2 41 ## Output: 2 42 ## 43 ## 2 is not found in the array so return 2. 44 # 45 ############################################################ 46 ## 47 ## discussion 48 ## 49 ############################################################ 50 # 51 # Instead of walking the list for every round, we create a 52 # hash with the list elements as keys, which makes the lookup 53 # easier. The we just check in a loop whether the current value 54 # is still there. 55 56 use strict; 57 use warnings; 58 59 multiply_by_two( [5,3,6,1,12], 3); 60 multiply_by_two( [1,2,4,3], 1); 61 multiply_by_two( [5,6,7], 2); 62 63 sub multiply_by_two { 64 my ($ints, $start) = @_; 65 print "Input: (", join(", ", @$ints), "), $start\n"; 66 my $hash; 67 map { $hash->{$_} = 1; } @$ints; 68 while($hash->{$start}) { 69 $start *= 2; 70 } 71 print "Output: $start\n"; 72 }