StefanTodorovski

[ADS/АПС] Lab 1.1: Mean Value / Средна вредност

Oct 23rd, 2018
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.Arrays;
  5.  
  6. public class Array<E> {
  7.    
  8.     private E arr[];
  9.     private int n;
  10.  
  11.     public Array(int n) {
  12.         this.arr = (E[]) new Object[n];
  13.         this.n = n;
  14.     }
  15.    
  16.     public Array(E[] arr, int n) {
  17.         this.arr = arr;
  18.         this.n = n;
  19.     }
  20.    
  21.     public int getSize() {
  22.         return n;
  23.     }
  24.    
  25.     public void set(int pos, E elem) {
  26.         if(pos < n&&pos >= 0)
  27.             arr[pos] = elem;
  28.         else System.out.println("Out of bounds");
  29.     }
  30.    
  31.     public E get(int pos) {
  32.         if(pos < n && pos >= 0)
  33.             return arr[pos];
  34.         else System.out.println("Out of bounds");
  35.         return null;
  36.     }
  37.  
  38.     public static int findClosest(double val, Array<Integer> niza) {
  39.         double dist = Math.abs(niza.get(0) - val);
  40.         int index = 0;
  41.         for(int i=1; i<niza.getSize(); i++) {
  42.             if(dist > Math.abs(niza.get(i) - val)) {
  43.                 dist = Math.abs(niza.get(i) - val);
  44.                 index = i;
  45.             } else if(dist == Math.abs(niza.get(i) - val)) {
  46.                 if(niza.get(i) < niza.get(index)) {
  47.                     index = i;
  48.                 }
  49.             }
  50.         }
  51.         return niza.get(index);
  52.     }
  53.    
  54.     public static int brojDoProsek(Array<Integer> niza){
  55.         int sum = 0;
  56.         for(int i=0; i<niza.getSize(); i++)
  57.             sum += niza.get(i);
  58.         return findClosest((double)sum/niza.getSize(), niza);
  59.     }
  60.  
  61.     public static void main(String[] args) throws IOException{
  62.         BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in));
  63.         String s = stdin.readLine();
  64.         int N = Integer.parseInt(s);
  65.        
  66.         Array<Integer> niza = new Array<Integer>(N);
  67.         for(int i=0; i<N; i++)
  68.         {
  69.             s = stdin.readLine();
  70.             niza.set(i, Integer.parseInt(s));
  71.         }
  72.        
  73.         System.out.println(brojDoProsek(niza));    
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment