site.base_url }}/">The Bear's Den -->

The Bear's Den

Enter at your own risk

Zippairs

Task 1: Maximum Pairs

Submitted by: Mohammad Sajid Anwar


You are given an array of distinct words, @words.

Write a script to find the maximum pairs in the given array. The words $words[i] and $words[j] can be a pair one is reverse of the other.

Example 1

Input: @words = ("ab", "de", "ed", "bc")
Output: 1

There is one pair in the given array: "de" and "ed"

Example 2

Input: @words = ("aa", "ba", "cd", "ed")
Output: 0

Example 3

Input: @words = ("uv", "qp", "st", "vu", "mn", "pq"))
Output: 2

Solution

As a word must not be paired with itself, we need to eliminate all palindromes from the list. Then taking a slice with the reversed words as subscripts from a hash containing the words as keys. As both members of a pair do exist in the hash, we need to half the number to get the count of pairs.

sub maximum_pairs {
    (\my %words)->@{@_} = map scalar reverse, @_;

    delete @words{grep $_ eq $words{$_}, keys %words};
    (grep defined, @words{values %words}) / 2;
}

See the full solution.

Task 2: Merge Strings

Submitted by: Mohammad Sajid Anwar


You are given two strings, $str1 and $str2.

Write a script to merge the given strings by adding in alternative order starting with the first string. If a string is longer than the other then append the remaining at the end.

Example 1

Input: $str1 = "abcd", $str2 = "1234"
Output: "a1b2c3d4"

Example 2

Input: $str1 = "abc", $str2 = "12345"
Output: "a1b2c345"

Example 3

Input: $str1 = "abcde", $str2 = "123"
Output: "a1b2c3de"

Solution

As long as there are remaining characters in either string, we “shift” the first from both and append it to the result.

use experimental 'signatures';

sub merge_strings ($s, $t) {
    my $zip;
	while ($s || $t) {
        $zip .= ($s && substr($s, 0, 1, '')) . ($t && substr($t, 0, 1, ''));
    }
    $zip;
}

See the full solution.