Use HashSet to determine the result
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;
}
}
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();
}
}