Challenge 7
26/02/26 09:19
package net.p3consulting.so.challenges;
// https://stackoverflow.com/beta/challenges/79767716/challenge-7-pangram-checker-completed
import org.json.JSONArray;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.regex.Pattern;
public class Challenge7 {
private static String readFile(final String filePath) {
final InputStream is = Challenge14.class.getResourceAsStream(filePath);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
String content ;
try {
byte[] byteChunk = new byte[4096];
int n;
while ((n = is.read(byteChunk)) > 0) {
baos.write(byteChunk, 0, n);
}
content = baos.toString(StandardCharsets.UTF_8.name());
}
catch (final IOException e) {
throw new RuntimeException(e);
}
return content ;
}
protected static void solve(final JSONArray problems) {
final Pattern checkPangram = Pattern.compile("a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t+u+v+w+x+y+z+");
problems.forEach(
s -> {
final String stripped = ((String)s).toLowerCase().replaceAll("[^a-z]", "") ;
char chars[] = new char[stripped.length()];
stripped.getChars(0, stripped.length(), chars, 0);
Arrays.sort(chars);
final String sorted = new String(chars);
final boolean perfectPangram = "abcdefghijklmnopqrstuvwxyz".equals(sorted);
final boolean pangram = perfectPangram || (sorted.length() > 26 && checkPangram.matcher(sorted).matches());
System.out.println(String.format("'%s'; isPangram %b; isPerfectPangram %b",s,
pangram, perfectPangram));
}
);
}
public static void main(final String[] args) {
final String classPath = System.getProperty("java.class.path", ".");
final String[] classPathElements = classPath.split(System.getProperty("path.separator"));
final File dir = new File(classPathElements[0]);
final Pattern pattern = Pattern.compile(".*/challenge7_\\d+.json");
Arrays.stream(dir.listFiles()).sorted().forEach(
file -> {
String fileName = null;
try {
fileName = file.getCanonicalPath();
if (pattern.matcher(fileName).matches()) {
fileName = fileName.substring(fileName.lastIndexOf('/'));
System.out.println(fileName);
JSONArray problems = new JSONArray( readFile(fileName) );
solve(problems);
}
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
}
) ;
}
}