Skip to content

Instantly share code, notes, and snippets.

@elvismetaphor
Created May 31, 2018 04:39
Show Gist options
  • Save elvismetaphor/340a49a140b3969ad89ff1570ca35fab to your computer and use it in GitHub Desktop.
Save elvismetaphor/340a49a140b3969ad89ff1570ca35fab to your computer and use it in GitHub Desktop.

Concept:

Use HashSet to determine the result

Solution:

public class SubsetChecker {

    public boolean isSubset(char[] first, char[] second) {
        Set<Character> set = generateCharacterSet(first);
        return containsAll(set, second);
    }

    private Set<Character> generateCharacterSet(char[] chars) {
        Set<Character> result = new HashSet();
        for (char c : chars) {
            result.add(c);
        }

        return result;
    }

    private boolean containsAll(Set<Character> set, char[] targets) {
        for (char target : targets) {
            if (!set.contains(target)) return false;
        }

        return true;
    }
}

Unit Tests

public class SubsetCheckerTest {

    @Test
    public void When_BothEmpty_Should_ReturnTrue() {
        // Arrange
        SubsetChecker testee = createSubsetChecker();
        char[] first = {};
        char[] second = {};

        // Action
        boolean result = testee.isSubset(first, second);

        // Assert
        Assert.assertTrue(result);
    }

    @Test
    public void When_SecondIsASubsetOfFirst_Should_ReturnTrue() {
        // Arrange
        SubsetChecker testee = createSubsetChecker();
        char[] first = {'A', 'B', 'C', 'D', 'E'};
        char[] second = {'A', 'E', 'D', 'A'};

        // Action
        boolean result = testee.isSubset(first, second);

        // Assert
        Assert.assertTrue(result);
    }

    @Test
    public void When_SecondIsNotASubsetOfFirst_Should_ReturnFalse() {
        // Arrange
        SubsetChecker testee = createSubsetChecker();
        char[] first = {'A', 'B', 'C', 'D', 'E'};
        char[] second = {'Z', 'A', 'D'};

        // Action
        boolean result = testee.isSubset(first, second);

        // Assert
        Assert.assertFalse(result);
    }

    private SubsetChecker createSubsetChecker() {
        return new SubsetChecker();
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment