Sets

1 problem from Rosalind — Bioinformatics Stronghold. Press Run on any block to execute it in your browser.

SETO — Introduction to Set Operations

solvedbrowser + CLI Problem statement Open in the workbench Download .bl

Set operations as groundwork. Worth having explicitly because several later problems phrase their answer as a complement or an intersection, and getting the universe wrong is a common way to be quietly off by a few elements.

# Rosalind: SETO — Introduction to Set Operations
# https://rosalind.info/problems/seto/
#
# Given: A positive integer n and two subsets A and B of {1, ..., n}.
# Return: Their union, intersection, both differences, and both complements.

let n = 10
let a = [1, 2, 3, 4, 5]
let b = [2, 8, 5, 10]

let universe = range(1, n + 1)

fn union_of(x, y) { concat(x, y) |> unique() |> sort() }
fn intersection_of(x, y) { x |> filter(|e| y |> contains(e)) |> sort() }
fn difference_of(x, y) { x |> filter(|e| !(y |> contains(e))) |> sort() }

let combined_items = union_of(a, b)
let shared_items = intersection_of(a, b)
let a_minus_b = difference_of(a, b)
let b_minus_a = difference_of(b, a)
let complement_a = difference_of(universe, a)
let complement_b = difference_of(universe, b)

fn show(label, s) { println("  " + label + ": " + (s |> map(|e| str(e)) |> join(" "))) }

println("Result:")
show("A combined_items B     ", combined_items)
show("A inter B     ", shared_items)
show("A - B         ", a_minus_b)
show("B - A         ", b_minus_a)
show("complement A  ", complement_a)
show("complement B  ", complement_b)

fn joined(s) { s |> map(|e| str(e)) |> join(" ") }

fn test_seto_set_operations() {
    assert joined(combined_items) == "1 2 3 4 5 8 10", "SETO combined_items: " + joined(combined_items)
    assert joined(shared_items) == "2 5", "SETO shared_items: " + joined(shared_items)
    assert joined(a_minus_b) == "1 3 4", "SETO A-B: " + joined(a_minus_b)
    assert joined(b_minus_a) == "8 10", "SETO B-A: " + joined(b_minus_a)
    assert joined(complement_a) == "6 7 8 9 10", "SETO ~A: " + joined(complement_a)
    assert joined(complement_b) == "1 3 4 6 7 9", "SETO ~B: " + joined(complement_b)
}