How do I create a loop to generate min, max, avg for 2 array lists, i have only generated the min, max and avg with sum for single array lists so far.
These are the 2 arrays User[] & Withdrawals[]:
User, Withdrawals
1 , 90.00
2 , 85.00
4 , 75.00
5 , 65.00
2 , 40.00
1 , 80.00
3 , 50.00
5 , 85.00
4 , 80.00
1 , 70.00
size = 10
This is what i have tried, as i have no clue about 2 arrays interdependent:
double min = 0.0;
double max = 0.0;
double sum = 0.0;
double avg = 0.0;
for(int i = 0; i <size; i++){
.
.
for(int j = 0; j < Withdrawals.length; j++){
if(Withdrawals[User[i]] > max){
max = Withdrawals[j];
}
if(Withdrawals[User[i]] < min){
min = Withdrawals[j];
}
}
sum += Withdrawals[j];
avg = sum/size;
}
how do i print the min, max, avg from the no of withdrawals per user ? :S
I have already counted the number of withdrawals per user.
Conditions are: create everything from scratch instead of using available library features of Java.
Divide and conquer 🙂
Yes, I know that is a term used for an algorithm technique, in this case what I mean is… work with small parts.
First having the min, max, avg for a simple array:
Note: Since you can’t use Java libraries for your assignment, is easy to do your own versions of the min/max functions (read the Math JavaDoc)
Now you can encapsulate this code in a function, you can start by returning another array:
Using an array is a little bit ugly to read, so is better if you create a class to hold the min, max, avg. So lets refactor the code a little bit:
You don’t specify it in your question, but I assume that you have an array for each user (maybe each withdrawals is another array).
Now that you have the bottom parts, we can switch to a top-down thinking.
So your code could be something like this:
Ok, but this is just the idea, you still have the problem to relate aUser with its withdrawals. You have several options here:
Option 1:
Option 2:
Additional notes: If you are studying Computer Science, you’ll learn in the future that the loop to calculate max, min, avg has a complexity of O(n). If the values array is fully loaded in memory, doing the max/min/avg in three different functions (thus reading the array 3 times) is still an algorithm of O(n) order with a bigger constant. With the power of today’s computers the constant is so small, that most of the time you’ll not get any gain from calculating min/max/avg in the same loop. In contrast you can gain code readability, for example in Groovy the minMaxAvg code could be written like this: