39

What is the average height of a tree in terry's front yard?

 2 years ago
source link: https://www.codeproject.com/Questions/5319812/What-is-the-average-height-of-a-tree-in-terrys-fro
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

See more:

There are N trees in Terry's front yard. He is supposed to measures the height of each tree and find the average height of trees in his yard. What is the average height of a tree in Terry's front yard?

Note:- Print your answer as floor value (average height)
Input
The first line contains N: numbers of tree.
Then follows N lines represents the height of each tree.

Constraint:-
1 <= n <= 100000
1 <= a[i] <= 100000
Output
Print the average height of all the trees in the yard

What I have tried:

Expand ▼   Copy Code
<pre>import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework

// don't change the name of this class
// you can add inner classes if needed
class Main {
	public static void main (String[] args) {
                      // Your code here
		Scanner scan = new Scanner(System.in);
		int total_trees = scan.nextInt();
		int[] tree = new int[total_trees];
		for (int i=0; i< total_trees; i++) {
			tree[i] = scan.nextInt();
		}
		Arrays.sort(tree);
		int n = 0;
		int[] a = new int[total_trees];
		for(int i =0; i< total_trees; i++) {
			while(i < total_trees -1 && tree[i]==tree[i+1]){
				i++;
			}
				a[n] = tree[i];
				n++;
		}
		int sum = 0;
		for (int i=0; i<n; i++){
			sum += a[i];
		}
		int avg = (int)Math.floor((float)sum/n);
		System.out.println(avg);

	}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK