Last active
July 2, 2016 08:17
-
-
Save arjunswaj/359500cc007a690bcb805bc953107f73 to your computer and use it in GitHub Desktop.
Combinations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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