{"id":"lists-largest","slug":"largest-and-smallest","title":"Sums, averages and the largest value","text":"A loop over the indexes can combine all the values into one result. For a sum, start from 0 and add each value:\n\n```java\nArrayList<Integer> minutes = new ArrayList<>();\nminutes.add(25);\nminutes.add(40);\nminutes.add(15);\nminutes.add(30);\n\nint total = 0;\nfor (int i = 0; i < minutes.size(); i++) {\n    total += minutes.get(i);\n}\nSystem.out.println(\"Total: \" + total);\nSystem.out.println(\"Average: \" + (double) total / minutes.size());\n```\n\n```output\nTotal: 110\nAverage: 27.5\n```\n\nThe average divides the sum by `size()`, and `(double)` keeps the decimals. (On an empty list, that divides by 0, and the average comes out as `NaN`, \"not a number\". Check the size first when the list may be empty.)\n\n### The largest value\n\nTo find the largest value, keep the largest one seen so far in a variable, and compare every value with it. Start with the **first value in the list**, not with 0:\n\n```java\nArrayList<Integer> temperatures = new ArrayList<>();\ntemperatures.add(-3);\ntemperatures.add(-8);\ntemperatures.add(-1);\ntemperatures.add(-5);\n\nint highest = temperatures.get(0);\nfor (int i = 1; i < temperatures.size(); i++) {\n    if (temperatures.get(i) > highest) {\n        highest = temperatures.get(i);\n    }\n}\nSystem.out.println(\"Highest: \" + highest);\n```\n\n```output\nHighest: -1\n```\n\nStarting with 0 would give the wrong answer here: no temperature is above 0, so the program would print `Highest: 0`, a value that isn't even in the list. The first value is always a real candidate. The loop can then start at index 1, since index 0 has been counted already. (`get(0)` needs a list with at least one value in it.)\n\nFor the smallest value, turn the comparison around, to `<`. And `highest = Math.max(highest, temperatures.get(i));` does the same as the whole `if`.\n\n### Where the largest value is\n\nSometimes the place matters more than the value: which day was the warmest? Then keep the **index** of the best value so far, and read the value with `get` when you need it:\n\n```java\nArrayList<Integer> temperatures = new ArrayList<>();\ntemperatures.add(-3);\ntemperatures.add(-8);\ntemperatures.add(-1);\ntemperatures.add(-5);\n\nint warmest = 0;\nfor (int i = 1; i < temperatures.size(); i++) {\n    if (temperatures.get(i) > temperatures.get(warmest)) {\n        warmest = i;\n    }\n}\nSystem.out.println(\"Warmest: day \" + (warmest + 1) + \", \" + temperatures.get(warmest) + \" degrees\");\n```\n\n```output\nWarmest: day 3, -1 degrees\n```\n\nWith `>`, a tie keeps the earlier index; with `>=`, the later one would win.\n","task":"A high jumper's coach wants to know how steady the jumper is. Read the heights of the jumps in centimeters, one per line, until `0`, and keep them in a list. Then print the best (highest) jump, and how many jumps came within 5 centimeters of it: at most 5 below the best, the best one included. There's always at least one jump. For the input `175`, `182`, `150`, `178` and `0` the program prints:\n\n```\nBest: 182\nClose to best: 2\n```\n\nHere 182 and 178 count, while 175 is 7 centimeters short.\n","kind":"code","seed":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<Integer> jumps = new ArrayList<>();\n\n    }\n}\n","solution":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<Integer> jumps = new ArrayList<>();\n        while (true) {\n            int jump = Integer.valueOf(scanner.nextLine());\n            if (jump == 0) {\n                break;\n            }\n            jumps.add(jump);\n        }\n        int best = jumps.get(0);\n        for (int i = 1; i < jumps.size(); i++) {\n            if (jumps.get(i) > best) {\n                best = jumps.get(i);\n            }\n        }\n        int close = 0;\n        for (int i = 0; i < jumps.size(); i++) {\n            if (best - jumps.get(i) <= 5) {\n                close++;\n            }\n        }\n        System.out.println(\"Best: \" + best);\n        System.out.println(\"Close to best: \" + close);\n    }\n}\n","hints":["Two loops over the list: the first finds the best jump, starting from `jumps.get(0)`. Only once it's known can the second loop compare every jump with it.","In the second loop, a jump counts when `best - jumps.get(i) <= 5`. Start the counter at 0 before that loop."],"tests":[{"name":"Test 1","stdin":"175\n182\n150\n178\n0\n","expect":"Best: 182\nClose to best: 2","hidden":false},{"name":"Test 2","stdin":"160\n0\n","expect":"Best: 160\nClose to best: 1","hidden":true},{"name":"Test 3","stdin":"140\n141\n139\n0\n","expect":"Best: 141\nClose to best: 3","hidden":true},{"name":"Test 4","stdin":"190\n185\n170\n195\n0\n","expect":"Best: 195\nClose to best: 2","hidden":true},{"name":"Test 5","stdin":"150\n180\n176\n174\n0\n","expect":"Best: 180\nClose to best: 2","hidden":true}],"require":[{"pattern":"\\bjumps\\.size\\s*\\(\\s*\\)","message":"Loop over the list's indexes, up to `jumps.size()`."},{"pattern":"\\bjumps\\.get\\s*\\(","message":"Compare the jumps from the list with `jumps.get(i)`."}],"forbid":[],"more":[{"task":"Fill in the blanks so the program adds up the ratings and prints their average:\n\n```\nAverage rating: 3.8\n```\n","kind":"fill","seed":"import java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<Integer> ratings = new ArrayList<>();\n        ratings.add(4);\n        ratings.add(5);\n        ratings.add(3);\n        ratings.add(2);\n        ratings.add(5);\n        int sum = 0;\n        for (int i = 0; i < [[ratings.size()]]; i++) {\n            sum [[+= ratings.get(i)‖= sum + ratings.get(i)]];\n        }\n        System.out.println(\"Average rating: \" + (double) sum / ratings.size());\n    }\n}\n","solution":"import java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<Integer> ratings = new ArrayList<>();\n        ratings.add(4);\n        ratings.add(5);\n        ratings.add(3);\n        ratings.add(2);\n        ratings.add(5);\n        int sum = 0;\n        for (int i = 0; i < ratings.size(); i++) {\n            sum += ratings.get(i);\n        }\n        System.out.println(\"Average rating: \" + (double) sum / ratings.size());\n    }\n}\n","hints":["The loop runs over every index, as long as `i < ratings.size()`.","Each round adds this round's rating to the sum: `sum += ratings.get(i)`."],"tests":[{"name":"Output","stdin":"","expect":"Average rating: 3.8","hidden":false}],"require":[],"forbid":[]},{"task":"Read the number of visitors on each day of a festival, one number per line, until `-1`. Then print the busiest day, counting days from 1, and its number of visitors. When two days tie, the earlier one counts. There's always at least one day. For the input `420`, `515`, `610`, `380` and `-1` the program prints:\n\n```\nBusiest: day 3 with 610 visitors\n```\n","kind":"code","seed":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<Integer> visitors = new ArrayList<>();\n\n    }\n}\n","solution":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<Integer> visitors = new ArrayList<>();\n        while (true) {\n            int count = Integer.valueOf(scanner.nextLine());\n            if (count == -1) {\n                break;\n            }\n            visitors.add(count);\n        }\n        int busiest = 0;\n        for (int i = 1; i < visitors.size(); i++) {\n            if (visitors.get(i) > visitors.get(busiest)) {\n                busiest = i;\n            }\n        }\n        System.out.println(\"Busiest: day \" + (busiest + 1) + \" with \" + visitors.get(busiest) + \" visitors\");\n    }\n}\n","hints":["Keep the index of the busiest day so far, starting at 0, and compare `visitors.get(i)` with `visitors.get(busiest)`.","Use `>`, not `>=`, so a tie keeps the earlier day. The day's number is `busiest + 1`."],"tests":[{"name":"Test 1","stdin":"420\n515\n610\n380\n-1\n","expect":"Busiest: day 3 with 610 visitors","hidden":false},{"name":"Test 2","stdin":"500\n700\n700\n-1\n","expect":"Busiest: day 2 with 700 visitors","hidden":true},{"name":"Test 3","stdin":"900\n100\n-1\n","expect":"Busiest: day 1 with 900 visitors","hidden":true},{"name":"Test 4","stdin":"75\n-1\n","expect":"Busiest: day 1 with 75 visitors","hidden":true},{"name":"Test 5","stdin":"10\n20\n30\n40\n-1\n","expect":"Busiest: day 4 with 40 visitors","hidden":true}],"require":[{"pattern":"\\bvisitors\\.get\\s*\\(","message":"Read the numbers from the list with `visitors.get(...)`."}],"forbid":[]}]}