Skip to content

Instantly share code, notes, and snippets.

@nikialeksey
Last active December 14, 2022 07:05
Show Gist options
  • Save nikialeksey/720c1acb80484df467a380b9d35cf110 to your computer and use it in GitHub Desktop.
Save nikialeksey/720c1acb80484df467a380b9d35cf110 to your computer and use it in GitHub Desktop.
Joshua Bloch Wtf.java break-in
import org.apache.commons.math3.analysis.interpolation.NevilleInterpolator;
public class WtfCreator {
public static void main(String[] args) {
var text = "Hello, world!\n";
double[] x = new double[text.length() + 1];
double[] y = new double[text.length() + 1];
for(var i = 0; i < text.length(); i++) {
x[i] = i;
y[i] = (int) text.charAt(i);
}
x[text.length()] = text.length();
y[text.length()] = 0;
var interpolator = new NevilleInterpolator();
var function = interpolator.interpolate(x, y);
double[] coeff = function.getCoefficients();
System.out.println("static char p(int i) {");
System.out.println(" return (char) (" + coeff[0] + " + 0.5");
for(int i = 1; i < coeff.length; i++) {
System.out.println(" + i * (" + coeff[i]);
}
System.out.println(" " + ")".repeat(coeff.length) + ";");
System.out.println("}");
// Use new function like this:
// for(var i = 0; p(i) != 0; i++)
// System.out.print(p(i));
}
}
import jdk.jshell.JShell;
import org.apache.commons.math3.analysis.interpolation.NevilleInterpolator;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class WtfCreator {
public static void main(String[] args) {
var text = "Hello, world!\n";
double[] x = new double[text.length() + 1];
double[] y = new double[text.length() + 1];
for(var i = 0; i < text.length(); i++) {
x[i] = i;
y[i] = (int) text.charAt(i);
}
x[text.length()] = text.length();
y[text.length()] = 0;
var interpolator = new NevilleInterpolator();
var function = interpolator.interpolate(x, y);
double[] coeff = function.getCoefficients();
var pMethod = new StringBuilder();
pMethod.append("char p(int i) {\n");
pMethod.append(" return (char) (" + coeff[0] + " + 0.5\n");
for(int i = 1; i < coeff.length; i++) {
pMethod.append(" + i * (" + coeff[i] + "\n");
}
pMethod.append(")".repeat(coeff.length) + ";\n");
pMethod.append("}\n");
var result = new ByteArrayOutputStream();
var shell = JShell.builder().out(new PrintStream(result)).build();
shell.eval(pMethod.toString());
shell.eval("for(var i = 0; p(i) != 0; i++) System.out.print(p(i));");
shell.close();
System.out.println(result.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment