Skip to content

Instantly share code, notes, and snippets.

@jcromartie
Created November 15, 2011 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcromartie/5cd0f0f31cdd9db84199 to your computer and use it in GitHub Desktop.
Save jcromartie/5cd0f0f31cdd9db84199 to your computer and use it in GitHub Desktop.
sparklines in Java... WTF
public class spark {
public static double[] normalize(double[] nums) {
double min = nums[0];
double max = nums[0];
for (int ii = 0; ii < nums.length; ii++) {
min = Math.min(nums[ii], min);
max = Math.max(nums[ii], max);
}
double[] result = new double[nums.length];
for (int ii = 0; ii < nums.length; ii++) {
result[ii] = (nums[ii] - min) / (max - min);
}
return result;
}
public static String blocks = "▁▂▃▄▅▆▇";
public static String sparkline(double[] nums) {
double[] normalized = normalize(nums);
StringBuilder sb = new StringBuilder();
for (int ii = 0; ii < normalized.length; ii++) {
int idx = (int)Math.round(normalized[ii] * 6.0);
sb.append(blocks.substring(idx, idx + 1));
}
return sb.toString();
}
public static void main(String[] args) {
double[] nums = new double[args.length];
for (int ii = 0; ii < args.length; ii++) {
nums[ii] = Double.parseDouble(args[ii]);
}
System.out.println(sparkline(nums));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment