DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 204

Challenge, My solutions

Task 1: Monotonic Array

Task

You are given an array of integers.

Write a script to find out if the given array is Monotonic. Print 1 if it is otherwise 0.

An array is Monotonic if it is either monotone increasing or decreasing.

My solution

This is relatively straight forward, so doesn't really need much explanation. If the last value is less than the first value, I reverse the array, using n[::-1] in python, or the reverse function in Perl. This means the array will be always increasing if it is monotonic.

Then I iterate from 0 to 2 less than the length of the array. For each iteration, I check that the value at that position is less than or equal to the next value. If it isn't, I return 0.

If we reach the end of iteration, we know the values are monotonic, and return 1.

Examples

$ ./ch-1.py 1 2 2 3
1

$ ./ch-1.py 1 3 2
0

$ ./ch-1.py 6 5 5 4
1
Enter fullscreen mode Exit fullscreen mode

Task 2: Reshape Matrix

Task

You are given a matrix (m x n) and two integers (r) and (c).

Write a script to reshape the given matrix in form (r x c) with the original value in the given matrix. If you can’t reshape print 0.

My solution

Sometimes part of the challenge is figuring out how to parse the input. In this case, I kinda cheat and just slurp in all the arguments, and extract the integers from it. This is because ultimately we don't actually care about the input matrix.

Once slurped, I remove the last two integers and store them as r and c. Perl has the splice method to do this. Python doesn't seem to have an equivalent, so I just pop them off one at a time.

The next step is to set if the length of the input array is the product of r and c. If it is not, I return 0 and exit.

The last step is to print the new matrix. This time Python does have the range operator that supports steps other than 1. For Perl, I used a C-style for loop.

Examples

$ ./ch-2.py "[ 1 2 ] [ 3 4 ]" 1 4
[ 1 2 3 4 ]

$ ./ch-2.py "[ 1 2 3 ] [ 4 5 6 ]" 3 2
[ 1 2 ]
[ 3 4 ]
[ 5 6 ]

$ ./ch-2.py "[ 1 2 ]" 3 2
0
Enter fullscreen mode Exit fullscreen mode

Top comments (0)