QUESTION #1:

Write a Java method that takes an array of “sets” of String objects,
and determines whether _all_ sets in the array are equivalent.

Each “set” in the input array is represented as an array of String objects, in
no particular order, and possibly containing duplicates. Nevertheless, when
determining whether two of these “sets” are equivalent, you should disregard
order and duplicates. For example, the sets represented by these arrays are
all equivalent:


{"a", "b"}
{"b", "a"}
{"a", "b", "a"}

The signature for your method should be:

public static boolean allStringSetsIdentical(String[ ][ ] sets)

Examples of the method in operation:


allStringSetsIdentical(new String[][] {{"a","b"},{"b","b","a"},{"b","a"}})
returns true

allStringSetsIdentical(new String[][] {{"a","b"},{"a"},{"b"}})
returns false

Solution:

import java.util.ArrayList;
import java.util.List;

public class Q1_Sets {
	public static boolean allStringSetsIdentical(String[][] sets) {
		if (sets.length < 2)
			return false;
		List firstLevelVariables = new ArrayList();
		boolean isFirstLevel = true;
		for (String[] set : sets) {
			if (isFirstLevel) {
				for (String s : set)
					if (firstLevelVariables.contains(s) == false)
						firstLevelVariables.add(s);
				isFirstLevel = false;
				continue;
			}
			List nextLevelVariables = new ArrayList();
			for (String s : set) {
				if (firstLevelVariables.contains(s) == false)
					return false;
				if (nextLevelVariables.contains(s) == false)
					nextLevelVariables.add(s);
			}
			if (nextLevelVariables.size() != firstLevelVariables.size())
				return false;
		}
		return true;
	}

	public static void main(String[] args) {
		System.out.println("#1. allStringSetsIdentical({a,b}, {b,b,a}, {b,a})");
		System.out.println(allStringSetsIdentical(
			new String[][] {{"a","b"},{"b","b","a"},{"b","a"}}) == true);
		
		System.out.println("#2. allStringSetsIdentical({a,b}, {a}, {b})");
		System.out.println(allStringSetsIdentical(
			new String[][] {{"a","b"},{"a"},{"b"}}) == false);
		
		System.out.println("#3. allStringSetsIdentical({a,b}, {b,a}, {a})");
		System.out.println(allStringSetsIdentical(
			new String[][] {{"a","b"},{"b", "a"}, { "a" }}) == false);
		
		System.out.println("#4. allStringSetsIdentical({a})");
		System.out.println(allStringSetsIdentical(new String[][] {{"a"}}) == false);
	}
}

Output:

#1. allStringSetsIdentical({a,b}, {b,b,a}, {b,a})
true
#2. allStringSetsIdentical({a,b}, {a}, {b})
true
#3. allStringSetsIdentical({a,b}, {b,a}, {a})
true
#4. allStringSetsIdentical({a})
true