Task 1: Consecutive Odds
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
.
My solution
This task is pretty straight forward, so doesn't need much explanation. I have a variable odds
. As I iterate through the array, I add one to the odds
variable if it is an odd number. If it is even, I reset odds
value as zero.
If at any time the odds
value is 3, I print 1
and exit. Otherwise I will print 0
if we have exited the loop without finding three consecutive odd values.
Examples
$ ./ch-1.py 1 5 3 6
1
$ ./ch-1.py 2 6 3 5
0
$ ./ch-1.py 1 2 3 4
0
$ ./ch-1.py 2 3 5 7
1
Task 2: Widest Valley
Task
Given a profile as a list of altitudes, return the leftmost widest valley. A valley is defined as a subarray of the profile consisting of two parts: the first part is non-increasing and the second part is non-decreasing. Either part can be empty.
My solution
This is a really interesting challenge, and I had a few attempts at trying to come up with the best solution. Often, the best solution is just try everything to get the correct solution. That's what I did here.
For this task, I have a variable valley
that iterates from 0 to one less than the length of the array. This is the deepest point in the valley.
From this I calculate the start point of the valley. I do this by setting start
at the current position, and working backwards until we find a decreasing number or hit the start of the array. Likewise, I calculate the end
value by doing the same rightwards.
Once I have the start
and end
point, if the difference between these values is greater than or equal to the length of the current solution
, I replace the solution
variable.
Why equals? The difference between start and end is one less than the numbers of elements it contains. For example if start is 7 and end is 9, it contains three items (7, 8 and 9), even though the difference is two.
I'll be first to admit that this could actually be optimised a lot. For example if the previous or next value is lower than the current point, we know that we aren't at the bottom of the cliff. However, when dealing with such a short list, the benefits are negligible, and adds unnecessary complications. YMMV.
Examples
$ ./ch-1.py 1 5 3 6
1
$ ./ch-1.py 2 6 3 5
0
$ ./ch-1.py 1 2 3 4
0
$ ./ch-1.py 2 3 5 7
1
$ ./ch-2.py 1 5 5 2 8
1, 5, 5
$ ./ch-2.py 2 6 8 5
2, 6, 8
$ ./ch-2.py 9 8 13 13 2 2 15 17
13, 13, 2, 2, 15, 17
$ ./ch-2.py 2 1 2 1 3
2, 1, 2
$ ./ch-2.py 1 3 3 2 1 2 3 3 2
3, 3, 2, 1, 2, 3, 3