credimi-challenge-permutations/src/main/java/com/fabiosalvini/permutations/PermutationsPrinter.java

60 lines
1.8 KiB
Java

package com.fabiosalvini.permutations;
import java.io.*;
import java.util.function.Consumer;
/**
* Class to print permutations represented with arrays to the given output stream.
* Each permutation is printed in a new line with each element separated by a comma.
* <p>
* Example: [123,456,789] => "123,456,789\n" (new line separator is platform-dependent).
*/
public class PermutationsPrinter implements Consumer<long[]>, Closeable {
// Defining the separator as a constructor parameter incurs in a performance penalty.
private static final String SEPARATOR = ",";
private final BufferedWriter out;
public PermutationsPrinter(OutputStream outStream) {
this.out = new BufferedWriter(new OutputStreamWriter(outStream));
}
@Override
public void accept(long[] elements) {
String result = formatElements(elements);
try {
out.write(result);
out.newLine();
} catch (IOException e) {
throw new RuntimeException("Error writing permutation to the output stream", e);
}
}
/**
* Flush and close the output stream.
*
* @throws IOException if the stream cannot be closed.
*/
@Override
public void close() throws IOException {
out.close();
}
/**
* Format the given permutation to a string.
*
* @param elements the permutation.
* @return a string where each element is separated by {@value #SEPARATOR}.
*/
private String formatElements(long[] elements) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < elements.length - 1; i++) {
sb.append(elements[i]);
sb.append(SEPARATOR);
}
sb.append(elements[elements.length - 1]);
return sb.toString();
}
}