Weekly Challenge 124
Simon Green
Posted on August 3, 2021
TASK #1 › Happy Women Day
Write a script to print the Venus Symbol, international gender symbol for women. Please feel free to use any character.
My solution
I decided not to submit a solution. Short of doing a print with a huge heredoc there doesn't actually appear to be a task. Maybe say '♀'
cuts the mustard too.
TASK #2 › Tug of War
Task
You are given a set of $n
integers (n1, n2, n3, ….).
Write a script to divide the set in two subsets of n÷2
sizes each so that the difference of the sum of two subsets is the least. If $n
is even then each subset must be of size $n÷2
each. In case $n
is odd then one subset must be ($n-1)÷2
and other must be ($n+1)÷2
.
My solution
Looking at solutions to last week's Ugly Numbers task, it's clear that I don't always write the most efficient solution. I did however note that in my blog post last week too :-) This task may also fall into that category.
This task is about doing things in half. The target (most optimal solution) means that each set has exactly half the sum of all the inputs.
I have rolled my own _get_next_combination
sub routine that works through all possible combinations of the first set. I do this because as a rule of thumb I don't use no-core Perl modules for these challenges.
For each combination, I get the sums of the values in the set and see how close it is to the target. If it is an exact match, we can exit the loop early. If the difference is less than any previous combination, I record this fact.
Finally, I get the half of positions not in the first set and display the result.
Examples
Compared to the examples, the first example has the sets switched. The second example is completely different, but both solutions produce sets of 30.
$ ./ch-2.pl 10 20 30 40 50 60 70 80 90 100
Subset 1 = (10, 20, 50, 90, 100)
Subset 2 = (30, 40, 60, 70, 80)
$ ./ch-2.pl 10 -15 20 30 -25 0 5 40 -5
Subset 1 = (10, -15, 30, 5)
Subset 2 = (20, -25, 0, 40, -5)
Posted on August 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.