How to resolve the algorithm Set consolidation step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Set consolidation step by step in the Wren programming language

Table of Contents

Problem Statement

Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned.

See also

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Set consolidation step by step in the Wren programming language

Source code in the wren programming language

import "/set" for Set

var consolidateSets = Fn.new { |sets|
    var size = sets.count
    var consolidated = List.filled(size, false)
    var i = 0
    while (i < size - 1) {
        if (!consolidated[i]) {
            while (true) {
                var intersects = 0
                for (j in i+1...size) {
                    if (!consolidated[j]) {
                        if (!sets[i].intersect(sets[j]).isEmpty) {
                            sets[i].addAll(sets[j])
                            consolidated[j] = true
                            intersects = intersects + 1
                        }
                    }
                }
                if (intersects == 0) break
            }
        }
        i = i + 1
    }
    return (0...size).where { |i| !consolidated[i] }.map { |i| sets[i] }.toList
}

var unconsolidatedSets = [
    [Set.new(["A", "B"]), Set.new(["C", "D"])],
    [Set.new(["A", "B"]), Set.new(["B", "D"])],
    [Set.new(["A", "B"]), Set.new(["C", "D"]), Set.new(["D", "B"])],
    [Set.new(["H", "I", "K"]), Set.new(["A", "B"]), Set.new(["C", "D"]),
     Set.new(["D", "B"]), Set.new(["F", "G", "H"])]
]
for (sets in unconsolidatedSets) {
    System.print("Unconsolidated: %(sets)")
    System.print("Cosolidated   : %(consolidateSets.call(sets))\n")
}

  

You may also check:How to resolve the algorithm XML/XPath step by step in the TUSCRIPT programming language
You may also check:How to resolve the algorithm Classes step by step in the Dragon programming language
You may also check:How to resolve the algorithm Collections step by step in the Maple programming language
You may also check:How to resolve the algorithm Primes - allocate descendants to their ancestors step by step in the Phix programming language
You may also check:How to resolve the algorithm Levenshtein distance/Alignment step by step in the D programming language