Digits and doubling

Weekly challenge 261 — 18 March 2024

Week 261 - 18 Mar 2024

Task 2

You are given an array of integers, @ints and an integer $start. Write a script to do the following:

a) Look for $start in the array @ints; if found multiply the number by 2

b) If not found stop the process; otherwise repeat.

In the end return the final value.

Example 1Input: @ints = (5,3,6,1,12) and $start = 3 Output: 24 Step 1: 3 is in the array so 3 x 2 = 6 Step 2: 6 is in the array so 6 x 2 = 12 Step 3: 12 is in the array so 12 x 2 = 24 24 is not found in the array so return 24.Example 2Input: @ints = (1,2,4,3) and $start = 1 Output: 8 Step 1: 1 is in the array so 1 x 2 = 2 Step 2: 2 is in the array so 2 x 2 = 4 Step 3: 4 is in the array so 4 x 2 = 8 8 is not found in the array so return 8.Example 3Input: @ints = (5,6,7) and $start = 2 Output: 2 2 is not found in the array so return 2.

Perl doesn't (natively) have a function that will say whether
a given value occurs in an array - something like `$bool = is_in(@arr, $n)`

.

But it does have regular expressions. So let's join the elements of
`@ints`

as a string:

(1, 2, 3, 4) => ',1,2,3,4,'

Now, if `$start`

is 2 we simply need to
search for ',2,', ',4,' and ',8,', and as ',8,' isn't there, 8 is the answer.

#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2024-03-18 use utf8; # Week 261 - task 2 - Multiply by 2 use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; multiply_by_2([5, 3, 6, 1, 12], 3); multiply_by_2([1, 2, 4, 3], 1); multiply_by_2([5, 6, 7], 2); multiply_by_2([64, 256, 4, 64, 128, 2, 16, 32, 8], 2); sub multiply_by_2 { my (@ints, $start, $string); # initialise @ints = @{$_[0]}; $start = $_[1]; # join @ints as string $string = ',' . join(',', @ints) . ','; # search string as per task $start *= 2 while ($string =~ m|,$start,|); say qq[\nInput: \@ints = (] . join(', ', @ints) . qq[}, \$start = $_[1]]; say qq[Output: $start]; }

Input: @ints = (5, 3, 6, 1, 12}, $start = 3 Output: 24 Input: @ints = (1, 2, 4, 3}, $start = 1 Output: 8 Input: @ints = (5, 6, 7}, $start = 2 Output: 2 Input: @ints = (64, 256, 4, 64, 128, 2, 16, 32, 8}, $start = 2 Output: 512

Peter Campbell Smith is hereby placed in the public domain