Skip to content

Instantly share code, notes, and snippets.

@Roman-Port
Created September 10, 2021 18:49
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 Roman-Port/9235759dd0d397eaa8c97645a2c8650f to your computer and use it in GitHub Desktop.
Save Roman-Port/9235759dd0d397eaa8c97645a2c8650f to your computer and use it in GitHub Desktop.
// PLEASE DO NOT COPY+PASTE THIS, PLEASE!!!
// prints the biggest gainers (and ties) in the dataset
private static void examplePrintSummaryVar(Quote[] data) {
//Set up
double maxValue = 0; // stores the maximum value we've seen in the dataset so far
Quote[] ties = new Quote[data.length]; // stores all of the elements with the maximum value we've seen (PS: Using a list if you know how is more efficient)
int tiesCount = 0; // stores the number of ties we've seen so far
//Loop through everything we have in data
for (int i = 0; i < data.length; i++) {
//Calculate the value we'll be checking for
double value = data[i].getClose() - data[i].getOpen(); // <-- change this for the different summaries. this one is for the "biggest gainer"
//Check if the value we just calculated is larger than (BUT NOT EQUAL TO) the maximum one that we know of
if (value > maxValue) {
//All other ties that we know of are irrelevant now because this is larger than them
tiesCount = 0; // clear the number of ties since they are all no longer the maximum
maxValue = value; // be sure to update the stored maximum that we know of
}
//Check if the value is EQUAL to the max that we know of
if (value == maxValue) {
//This is a tie (or the first) of this value that we've seen. Store it in the array of ties
ties[tiesCount] = data[i]; // store it in the current tiesCount. On the first item, tiesCount is 0 so we would be putting it in the first "slot"
tiesCount++; // advance the ties count so we write the next one after the last
}
}
//We've found all of the maximum items now, and all of them are in "ties". We'll now start printing them
System.out.println("=== SUMMARY: BIGGEST GAINER(S) ==="); // just a label, remember to change it
//Loop through our TIES. Use the tiesCount here instead of data.length!
for (int i = 0; i < tiesCount; i++) {
System.out.printf("%-6s -> %f\n", ties[i].getTicker(), maxValue); // print the ticker (name) and the value
//He wants us to use printf for this. The "%-6s" is used to pad the name so it gets formatted nicely
//Also remember to end with "\n" so there's a new line after each
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment