Weekly Challenge 223
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.
Task 1: Count Primes
Task
You are given a positive integer, $n
.
Write a script to find the total count of primes less than or equal to the given integer.
My solution
This is nearly an identical task as the second task from challenge 198. The only difference is that challenge was to count values less than $n
, while this one is less than or equal to that value.
Therefore I copy and pasted that code, and changed the counter to include the supplied number.
Examples
$ ./ch-1.py 10
4
$ ./ch-1.py 1
0
$ ./ch-1.py 20
8
Task 2: Box Coins
Task
You are given an array representing box coins, @box.
Write a script to collect the maximum coins until you took out all boxes. If we pick box[i] then we collect the coins $box[i-1] * $box[i] * $box[i+1]
. If $box[i+1]
or $box[i-1]
is out of bound then treat it as 1 coin.
My solution
For this challenge, I have a recursive function called collect_coins
. It takes a list (array in Perl) of coins
. If there is only one coin remaining, I return that.
If there is more than one coin, I loop through the positions from 0 to one less than the number of coins, using the variable i
. For each iteration I calculate the number of coins
collect = coins[i]
if i > 0:
collect *= coins[i-1]
if i < remaining_coins - 1:
collect *= coins[i+1]
and call the function again with that coin removed.
new_coins = coins.copy()
del new_coins[i]
collect += collect_coins(new_coins)
I then record this score in the collections list. The function returns the maximum collections score.
Examples
$ ./ch-2.py 3 1 5 8
167
$ ./ch-2.py 1 5
10
Top comments (0)