-
-
Save jcromartie/5cd0f0f31cdd9db84199 to your computer and use it in GitHub Desktop.
sparklines in Java... WTF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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