I have some (very limited) experience in Java 6 and decided to revisit the language. To do so I wrote a solution for the following challenge:
You are given a number N and a string S. Print all of the possible ways to write a string of length N from the characters in string S, comma delimited in alphabetical order.
The first argument will be the path to the input filename containing the test data. Each line in this file is a separate test case. Each line is in the format: N,S i.e. a positive integer, followed by a string (comma separated). E.g.
Print all of the possible ways to write a string of length N from the characters in string S comma delimited in alphabetical order, with no duplicates.
Input sample:
1,aa
2,ab
3,pop
Output sample:
a
aa,ab,ba,bb
ooo,oop,opo,opp,poo,pop,ppo,ppp
The code works but performance is pretty bad and it feels like this can be improved.
Please point out anything that is wrong with this. I'm especially interested to know if this could be written in an entirely different way using features of Java 8.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import java.util.HashSet;
import java.lang.String;
import java.lang.Integer;
public class Main
{
public static List<String> create_combinations(List<Character> alphabet, int word_length)
{
List<Integer> index = new ArrayList<Integer>(word_length);
for (int i = 0; i < word_length; ++i)
{
index.add(0);
}
List<String> results = new ArrayList<String>();
for (;;)
{
StringBuilder word = new StringBuilder();
for (int i = 0; i < index.size(); ++i)
{
word.append(alphabet.get(index.get(i)));
}
results.add(word.toString());
for (int i = index.size() - 1; ; --i)
{
if (i < 0)
{
return results;
}
index.set(i, index.get(i) + 1);
if (index.get(i) == alphabet.size())
{
index.set(i, 0);
}
else
{
break;
}
}
}
}
public static void main (String[] args) throws IOException
{
BufferedReader buffer = new BufferedReader(new FileReader(new File(args[0])));
String line;
while ((line = buffer.readLine()) != null)
{
int word_length = Integer.parseInt(line.substring(0, line.indexOf(',')));
String letters = line.substring(line.indexOf(',') + 1);
Set<Character> unique_letters = new HashSet<Character>();
for (char c : letters.toCharArray())
{
unique_letters.add(c);
}
List<Character> alphabet = new ArrayList<Character>();
alphabet.addAll(unique_letters);
Collections.sort(alphabet);
System.out.println(String.join(",", create_combinations(alphabet, word_length)));
}
}
}