Advertisement
JStefan

APS_LAB1_Task1

Oct 17th, 2017
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 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.     private E data[]; // declared to be an Object since it would be too
  8.     // complicated with generics
  9.     private int size;
  10.  
  11.     public Array(int size) {
  12.         data = (E[]) new Object[size];
  13.         this.size = size;
  14.     }
  15.  
  16.     public void set(int position, E o) {
  17.         if (position >= 0 && position < size)
  18.             data[position] = o;
  19.         else
  20.             System.out.println("Ne moze da se vmetne element na dadenata pozicija");
  21.     }
  22.  
  23.     public E get(int position) {
  24.         if (position >= 0 && position < size)
  25.             return data[position];
  26.         else
  27.             System.out.println("Ne e validna dadenata pozicija");
  28.         return null;
  29.     }
  30.  
  31.     public int getLength() {
  32.         return size;
  33.     }
  34.  
  35.     public static int brojDoProsek(Array<Integer> niza){
  36.         double prosek = 0;
  37.         for (int i = 0; i < niza.getLength(); i++) {
  38.             prosek += (double) niza.get(i);
  39.         }
  40.         prosek /= niza.getLength();
  41.  
  42.         int najblizokBroj = niza.get(0);
  43.         for (int i = 1; i < niza.getLength(); i++) {
  44.             if(Math.abs(niza.get(i) - prosek) < Math.abs(najblizokBroj - prosek)) {
  45.                 najblizokBroj = niza.get(i);
  46.             }
  47.             if(Math.abs(niza.get(i) - prosek) == Math.abs(najblizokBroj - prosek)) {
  48.                 if(niza.get(i) < najblizokBroj) najblizokBroj = niza.get(i);
  49.             }
  50.         }
  51.  
  52.         return najblizokBroj;
  53.     }
  54.  
  55.     public static void main(String[] args) throws IOException {
  56.         BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in));
  57.         String s = stdin.readLine();
  58.         int N = Integer.parseInt(s);
  59.  
  60.         //Vashiot kod tuka...
  61.         Array<Integer> niza = new Array<Integer>(N);
  62.  
  63.         for (int i = 0; i < N; i++) {
  64.             niza.set(i, Integer.parseInt(stdin.readLine()));
  65.         }
  66.  
  67.         System.out.println(brojDoProsek(niza));
  68.     }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement