Created
April 14, 2013 07:01
-
-
Save khoatle/5381749 to your computer and use it in GitHub Desktop.
Generate a palindrome sequence of size N
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
import java.util.*; | |
public class GeneratePalindrome { | |
public static List<String> palindromesOfLength(int N, Set<String> alphabet) { | |
List<String> result = new ArrayList<String>(); | |
if(N == 1) { | |
for(String letter : alphabet) { | |
result.add(letter); | |
} | |
} else if(N > 1) { | |
List<String> subsetPalindrome = palindromesOfLength(N - 2, alphabet); | |
for(String s : alphabet) { | |
if(! subsetPalindrome.isEmpty()) { | |
for(String palindrome : subsetPalindrome) { | |
result.add(s + palindrome + s); | |
} | |
} else { | |
result.add(s + s); | |
} | |
} | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
Set<String> alphabet = new TreeSet<String>(); | |
for(int i = 0; i < 10; i++) { | |
alphabet.add(i + ""); | |
} | |
List<String> result = GeneratePalindrome.palindromesOfLength(500, alphabet); | |
for(String s : result) { | |
System.out.println(s); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment