TASK #1 › Array of Product
Task
You are given an array of positive integers @N
.
Write a script to return an array @M
where $M[i]
is the product of all elements of @N
except the index $N[i]
.
My solution
This is relatively straight forward. I calculate the product of all the numbers using List::Util's product function. For those that follow my posts, I tend to use only CPAN modules that are in core, like List::Util.
I then use the map function to loop over the numbers, diving the product by the number to give the solution.
Examples
» ./ch-1.pl 5 2 1 4 3
24, 60, 120, 30, 40
» ./ch-1.pl 2 1 4 3
12, 24, 6, 8
TASK #2 › Spiral Matrix
Task
You are given m x n
matrix of positive integers.
Write a script to print spiral matrix as list.
My solution
Initially I was quite stumped about the way to solve it. I was thinking I'd need some sort of counter to know how many values I would need to take and in which direction. After an hour of thinking about it (while watching the television), I figured out a reasonably clean solution. It will be interesting to see what other Team PWC members come up with.
It can be broken down to the following steps.
- Parse the input into an array of arrays, check that all rows are even.
- Create an array
@used
that is the same size as the input array. - Have an array
@directions
that map the x & y movements. For example[1, 0]
means to move down. - Starting at the top left moving right add the value at that position to the
@solutions
array, and mark that position as used. - If the next position is out of bounds of the array or is a value that has been used, switch directions. Continue this pattern until the
@solutions
array is completed. - Output the values to the screen.
Examples
» ./ch-2.pl "1 2 3" "4 5 6" "7 8 9"
1, 2, 3, 6, 9, 8, 7, 4, 5
» ./ch-2.pl "1 2 3 4" "5 6 7 8" "9 10 11 12" "13 14 15 16"
1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10
Top comments (0)