Skip to content

Instantly share code, notes, and snippets.

@arjunswaj
Last active July 2, 2016 08:17
Show Gist options
  • Save arjunswaj/359500cc007a690bcb805bc953107f73 to your computer and use it in GitHub Desktop.
Save arjunswaj/359500cc007a690bcb805bc953107f73 to your computer and use it in GitHub Desktop.
Combinations
package com.asb.algos.playground;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) throws Exception {
CombinationGenerator cg = new CombinationGenerator();
cg.generateCombinations("abbcde", 3)
.forEach(s -> System.out.println(s));
}
public static class CombinationGenerator {
public Set<String> generateCombinations(String s, int number)
throws Exception {
if (null == s || number > s.length() || number < 0) {
throw new Exception("Invalid input");
}
char []str = s.toCharArray();
Arrays.sort(str);
return combination(String.copyValueOf(str), number);
}
private Set<String> combination(String s, int number) throws Exception {
if (1 == number) {
return IntStream
.range(0, s.length())
.mapToObj(i -> s.substring(i, i + 1))
.collect(Collectors.toSet());
}
return combination(s, number - 1)
.stream()
.flatMap(c -> IntStream
.range(s.lastIndexOf(c.charAt(c.length() - 1)) + 1,
s.length())
.mapToObj(i -> c + s.substring(i, i + 1)))
.collect(Collectors.toSet());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment