Three odd things in the valleys
Weekly challenge 202 — 30 January 2023
Week 202: 30 Jan 2023
We are given an array of integers and asked for a script that prints 1 if there are three consecutive odd numbers in the given array, or otherwise print 0.
Perl can do that in one line:
say(join('', map({ $_ & 1 } @$test)) =~ m|111| ? 1 : 0);
The map converts @array to another array containing 1 for an odd entry and 0 for an even one. The join concatenates the elements of the resulting array into a string, and then it's just a case of looking for 111 in the string.
I often prefer not to use such a deeply nested statement as it's hard unravel what's happening, but this one isn't so hard.
#!/usr/bin/perl # Peter Campbell Smith - 2023-01-30 # PWC 202 task 1 use v5.28; use utf8; use warnings; # Task: You are given an array of integers. Write a script to print 1 if there are THREE consecutive odds # in the given array otherwise print 0. # Blog: https://pjcs-pwc.blogspot.com/ my (@tests, $test, @bits, $string); @tests = ([1, 5, 3, 6], [2, 6, 3, 5], [1, 2, 3, 4], [2, 3, 5, 7], [1, 11, 111], [2, 22, 222]); # loop over tests for $test (@tests) { # create a string having 1 for an odd number and 0 for an even number # and see if the string matches 111 say qq[\nInput: \@array = (] . join(', ', @$test) . ')'; say qq[Output: ] . (join('', map({ $_ & 1 } @$test)) =~ m|111| ? 1 : 0); }
Input: @array = (1, 5, 3, 6) Output: 1 Input: @array = (2, 6, 3, 5) Output: 0 Input: @array = (1, 2, 3, 4) Output: 0 Input: @array = (2, 3, 5, 7) Output: 1 Input: @array = (1, 11, 111) Output: 1 Input: @array = (2, 22, 222) Output: 0
Any content of this website which has been created by Peter Campbell Smith is in the public domain