The Bear's Den

Enter at your own risk

Different Counts

Task 1: Maximum Count

Submitted by: Mohammad Sajid Anwar


You are given an array of integers.

Write a script to return the maximum between the number of positive and negative integers. Zero is neither positive nor negative.

Example 1

Input: @ints = (-3, -2, -1, 1, 2, 3)
Output: 3

There are 3 positive integers.
There are 3 negative integers.
The maximum between 3 and 3 is 3.

Example 2

Input: @ints = (-2, -1, 0, 0, 1)
Output: 2

There are 1 positive integers.
There are 2 negative integers.
The maximum between 2 and 1 is 2.

Example 3

Input: @ints = (1, 2, 3, 4)
Output: 4

There are 4 positive integers.
There are 0 negative integers.
The maximum between 4 and 0 is 4.

Solution

This task invites to some math fun.

It can easily be seen that for any two (real) numbers \(a, b\) the following equation holds:

\[\max(a, b) = \frac{a + b + |a - b|}{2}\]

With

\[\operatorname{sign}(x) = \begin{cases} 1& \text{if } x > 0,\\ 0& \text{if } x = 0,\\ -1& \text{if } x < 0 \end{cases}\]

let \(s_k = \operatorname{sign}(i_k)\) be the signs of the given integers \(i_k\) and \(n\) and \(p\) the number of negative resp. positive integers from \(i_k\).

Then we have

\[\begin{aligned} p + n &= \sum |s_k| \\ p - n &= \sum s_k \end{aligned}\]

resulting in the nice formula

\[\max(p,n) = \frac{\sum |s_k| + |\sum s_k|}{2}\]

The translation into PDL is straightforward:

use strict;
use warnings;
use PDL;

sub max_count {
    my $s = long(@_)->clip(-1, 1);
    (sum(abs $s) + abs(sum $s)) / 2;
}

See the full solution to task 1.

Task 2: Sum Difference

Submitted by: Mohammad Sajid Anwar


You are given an array of positive integers.

Write a script to return the absolute difference between digit sum and element sum of the given array.

Example 1

Input: @ints = (1, 23, 4, 5)
Output: 18

Element sum: 1 + 23 + 4 + 5 => 33
Digit sum: 1 + 2 + 3 + 4 + 5 => 15
Absolute difference: | 33 - 15 | => 18

Example 2

Input: @ints = (1, 2, 3, 4, 5)
Output: 0

Element sum: 1 + 2 + 3 + 4 + 5 => 15
Digit sum: 1 + 2 + 3 + 4 + 5 => 15
Absolute difference: | 15 - 15 | => 0

Example 3

Input: @ints = (1, 2, 34)
Output: 27

Element sum: 1 + 2 + 34 => 37
Digit sum: 1 + 2 + 3 + 4 => 10
Absolute difference: | 37 - 10 | => 27

Solution

A number is never smaller than its digit sum in any base and therefore we do not need to apply the “absolute difference”.

use strict;
use warnings;
use Math::Prime::Util qw(vecsum todigits);

use constant BASE => 10;

sub sum_diff {
    vecsum(@_) - vecsum map todigits($_, BASE), @_;
}

See the full solution to task 2.


If you have a question about this post or if you like to comment on it, feel free to open an issue in my github repository.