Peter’s blog ✴ Week 127 ✴ 23 August 2021

THE WEEKLY CHALLENGE
Disjoined and conflicted

The Perl Camel

Task 1

Disjoint sets

You are given two sets with unique integers. Write a script to figure out if they are disjoint. The two sets are disjoint if they don’t have any common members.

Examples


Example 1:
Input: @S1 = (1, 2, 5, 3, 4)
       @S2 = (4, 6, 7, 8, 9)
Output: 0 as the given two sets have common member 4.

Example 2:
Input: @S1 = (1, 3, 5, 7, 9)
       @S2 = (0, 2, 4, 6, 8)
Output: 1 as the given two sets do not have common member.

Analysis

I did not submit a solution at the time, but have written this later

Lots of ways to do this, but what I chose was:

  • Make a hash of the members of @set2 using $in_set2{$_} = 1 for @set2;
  • Loop $j over @set1 and output 0 if $in_set2{$j} exists
  • Else output 1

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 1, 2, 3, 4, 5



example: 9, 8, 7, 6, 5

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-08-23
use utf8;     # Week 127 - task 1 - Disjoint sets
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

disjoint_sets([1, 2, 5, 3, 4], [4, 6, 7, 8, 9]);
disjoint_sets([1, 2, 5, 3, 4], [10, 6, 7, 8, 9]);
disjoint_sets([1, 2, 5, 3, 4], [1, 3, 6, -1, 42]);
disjoint_sets([1, 2, 3], []);
disjoint_sets([], [1, 3, 6, -1, 42]);
disjoint_sets([], []);

sub disjoint_sets {
    
    my (@set1, @set2, %in_set2, $j);
    
    @set1 = @{$_[0]};
    @set2 = @{$_[1]};
    say qq[\nInput:  (] . join(', ', @set1) . ')' .
        qq[\n        (] . join(', ', @set2) .')';
        
    # check what's in set2  
    $in_set2{$_} = 1 for @set2;
    
    # false if its also in set1
    for $j (@set1) {
        if ($in_set2{$j}) {
            say qq[Output: 0 ($j in both sets)];
            return;
        }
    }
    
    # else true
    say qq[Output: 1];
}

12 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


Input:  (1, 2, 5, 3, 4)
        (4, 6, 7, 8, 9)
Output: 0 (4 in both sets)

Input:  (1, 2, 5, 3, 4)
        (10, 6, 7, 8, 9)
Output: 1

Input:  (1, 2, 5, 3, 4)
        (1, 3, 6, -1, 42)
Output: 0 (1 in both sets)

Input:  (1, 2, 3)
        ()
Output: 1

Input:  ()
        (1, 3, 6, -1, 42)
Output: 1

Input:  ()
        ()
Output: 1

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain