Filip_Markoski

[NP] Листа на цели броеви

Nov 24th, 2017
1,598
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.67 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.stream.Collectors;
  3.  
  4. class IntegerList {
  5.  
  6.     ArrayList<Integer> arrayList;
  7.  
  8.     IntegerList() {
  9.         arrayList = new ArrayList<>();
  10.     }
  11.  
  12.     /* конструктор коj креира листа што ги содржи елементите numbers во истиот редослед во кој тие се појавуваат во низата.     */
  13.     IntegerList(Integer... numbers) {
  14.         arrayList = new ArrayList<>(Arrays.asList(numbers));
  15.     }
  16.  
  17.     /* го додава елементот на соодветниот индекс. */
  18.     /*Доколку има други елементи после таа позиција истите се поместуваат на десно за едно место
  19.     (нивните индекси им се зголемуваат за 1).
  20.     Доколку idx е поголемо од сегашната големина на листата ја зголемуваме листата и
  21.     сите нови елементи ги иницијалираме на нула (освен тој на позиција idx кој го поставуваме на el).*/
  22.     public void add(int element, int index) {
  23.         if (index > arrayList.size()) {
  24.             int length = index - arrayList.size();
  25.             for (int i = 0; i < length; i++) {
  26.                 arrayList.add(0);
  27.             }
  28.             arrayList.add(element);
  29.         } else {
  30.             arrayList.add(index, element);
  31.         }
  32.  
  33.     }
  34.  
  35.     /* Ако индексот е негативен или поголем од тековната големина на листата фрламе исклучок ArrayIndexOutOfBoundsException.*/
  36.     public boolean validateIndex(int index) {
  37.         if (index < 0 || index > arrayList.size()) {
  38.             throw new ArrayIndexOutOfBoundsException();
  39.         }
  40.         return true;
  41.     }
  42.  
  43.     public int remove(int index) {
  44.         validateIndex(index);
  45.         return arrayList.remove(index);
  46.     }
  47.  
  48.     public void set(int element, int index) {
  49.         validateIndex(index);
  50.         arrayList.set(index, element);
  51.     }
  52.  
  53.     public int get(int index) {
  54.         validateIndex(index);
  55.         return arrayList.get(index);
  56.     }
  57.  
  58.     public int size() {
  59.         return arrayList.size();
  60.     }
  61.  
  62.     public int count(int element) {
  63.         return (int) arrayList.stream().filter(integer -> integer.equals(element)).count();
  64.     }
  65.  
  66.     public void removeDuplicates() {
  67.         for (int i = 0; i < arrayList.size(); i++) {
  68.             //System.out.println(arrayList.toString());
  69.             Integer integer = arrayList.get(i);
  70.             for (int j = 0; j < i; j++) {
  71.                 if (integer.equals(arrayList.get(j))) {
  72.                     arrayList.remove(j);
  73.                     i--;
  74.                     break;
  75.                 }
  76.             }
  77.         }
  78.     }
  79.  
  80.     private int validateCount(int count) {
  81.         if (count > arrayList.size()) {
  82.             return arrayList.size();
  83.         }
  84.         return count;
  85.     }
  86.  
  87.     public int sumFirst(int count) {
  88.         count = validateCount(count);
  89.         /*int sum = 0;
  90.         for (int i = 0; i < count; i++) {
  91.             sum += arrayList.get(i);
  92.         }
  93.         return sum;*/
  94.         return arrayList.stream()
  95.                 .limit(count)
  96.                 .mapToInt(Integer::valueOf)
  97.                 .sum();
  98.  
  99.     }
  100.  
  101.     public int sumLast(int count) {
  102.         count = validateCount(count);
  103.         /*int size = arrayList.size();
  104.         int sum = 0;
  105.         for (int i = 0; i < count; i++) {
  106.             sum += arrayList.get(size - i - 1);
  107.         }
  108.         return sum;*/
  109.         return arrayList.stream()
  110.                 .skip(arrayList.size() - count)
  111.                 .mapToInt(Integer::valueOf)
  112.                 .sum();
  113.     }
  114.  
  115.     public void shiftRight(int index, int count) {
  116.         validateIndex(index);
  117.         int shiftIndex = (index + count) % arrayList.size();
  118.         Integer element = arrayList.remove(index);
  119.         arrayList.add(shiftIndex, element);
  120.     }
  121.  
  122.     public void shiftLeft(int index, int count) {
  123.         validateIndex(index);
  124.         int shiftIndex = (index - count) % arrayList.size();
  125.         if (shiftIndex < 0) {
  126.             shiftIndex = arrayList.size() + shiftIndex;
  127.         }
  128.         Integer element = arrayList.remove(index);
  129.         arrayList.add(shiftIndex, element);
  130.     }
  131.  
  132.     public IntegerList addValue(int value) {
  133.         /*IntegerList integerList = new IntegerList();
  134.         for (int i = 0; i < this.arrayList.size(); i++) {
  135.             integerList.add(this.arrayList.get(i) + value, i);
  136.         }
  137.         return integerList;*/
  138.         return new IntegerList(
  139.                 arrayList.stream()
  140.                         .map(objectInteger -> new Integer(objectInteger + value))
  141.                         .collect(Collectors.toCollection(ArrayList::new)) //.collect(Collectors.toList()))
  142.         );
  143.     }
  144.  
  145.     IntegerList(List<Integer> list) {
  146.         this.arrayList = (ArrayList<Integer>) list;
  147.     }
  148. }
  149.  
  150. /*
  151. Со користење на ArrayList или LinkedList сакаме да развиеме класа за работа со листи од цели броеви IntegerList.
  152. Листата ги има следните вообичаени методи:
  153.  
  154. IntegerList() - конструктор кој креира празна листа.
  155.  
  156.  
  157.  
  158. remove(int idx):int - го отстранува елементот на дадена позиција од листата и истиот го враќа. Доколку после таа позиција има други елементи истите се поместуваат во лево (нивните индекси се намалуваат за 1).
  159. set(int el, int idx) - го поставува елементот на соодветната позиција.
  160. get(int idx):int - го враќа елементот на соодветната позиција.
  161. size():int - го враќа бројот на елементи во листата.
  162. Освен овие методи IntegerList треба да нуди и неколку методи згодни за работа со цели броеви:
  163.  
  164. count(int el):int - го враќа бројот на појавувања на соодветниот елемент во листата.
  165. removeDuplicates() - врши отстранување на дупликат елементите од листата. Доколку некој елемент се сретнува повеќе пати во листата ја оставаме само последната копија од него. Пр: 1,2,4,3,4,5. -> removeDuplicates() -> 1,2,3,4,5
  166. sumFirst(int k):int - ја дава сумата на првите k елементи.
  167. sumLast(int k):int - ја дава сумата на последните k елементи.
  168. shiftRight(int idx, int k) - го поместува елементот на позиција idx за k места во десно. При поместувањето листата ја третираме како да е кружна. Пр: list = [1,2,3,4]; list.shiftLeft(1,2); list = [1,3,4,2] - (листата е нула индексирана така да индексот 1 всушност се однесува на елементот 2 кој го поместуваме две места во десно) list = [1,2,3,4]; list.shiftLeft(2, 3); list = [1,3,2,4] - елементот 3 го поместуваме 3 места во десно. По две поместувања стигнуваме до крајот на листата и потоа продолжуваме да итерираме од почетокот на листата уште едно место и овде го сместуваме.
  169. shiftLeft(int idx , int k) - аналогно на shiftRight.
  170. addValue(int value):IntegerList - враќа нова листа каде елементите се добиваат од оригиналната листа со додавање на value на секој елемент. Пр: list = [1,4,3]; addValue(5) -> [6,9,8]
  171. Забелешка која важи за сите методи освен add:
  172.  
  173.  */
  174. public class IntegerListTest {
  175.  
  176.     public static void main(String[] args) {
  177.         Scanner jin = new Scanner(System.in);
  178.         int k = jin.nextInt();
  179.         if (k == 0) { //test standard methods
  180.             int subtest = jin.nextInt();
  181.             if (subtest == 0) {
  182.                 IntegerList list = new IntegerList();
  183.                 while (true) {
  184.                     int num = jin.nextInt();
  185.                     if (num == 0) {
  186.                         list.add(jin.nextInt(), jin.nextInt());
  187.                     }
  188.                     if (num == 1) {
  189.                         list.remove(jin.nextInt());
  190.                     }
  191.                     if (num == 2) {
  192.                         print(list);
  193.                     }
  194.                     if (num == 3) {
  195.                         break;
  196.                     }
  197.                 }
  198.             }
  199.             if (subtest == 1) {
  200.                 int n = jin.nextInt();
  201.                 Integer a[] = new Integer[n];
  202.                 for (int i = 0; i < n; ++i) {
  203.                     a[i] = jin.nextInt();
  204.                 }
  205.                 IntegerList list = new IntegerList(a);
  206.                 print(list);
  207.             }
  208.         }
  209.         if (k == 1) { //test count,remove duplicates, addValue
  210.             int n = jin.nextInt();
  211.             Integer a[] = new Integer[n];
  212.             for (int i = 0; i < n; ++i) {
  213.                 a[i] = jin.nextInt();
  214.             }
  215.             IntegerList list = new IntegerList(a);
  216.             while (true) {
  217.                 int num = jin.nextInt();
  218.                 if (num == 0) { //count
  219.                     System.out.println(list.count(jin.nextInt()));
  220.                 }
  221.                 if (num == 1) {
  222.                     list.removeDuplicates();
  223.                 }
  224.                 if (num == 2) {
  225.                     print(list.addValue(jin.nextInt()));
  226.                 }
  227.                 if (num == 3) {
  228.                     list.add(jin.nextInt(), jin.nextInt());
  229.                 }
  230.                 if (num == 4) {
  231.                     print(list);
  232.                 }
  233.                 if (num == 5) {
  234.                     break;
  235.                 }
  236.             }
  237.         }
  238.         if (k == 2) { //test shiftRight, shiftLeft, sumFirst, sumLast
  239.             int n = jin.nextInt();
  240.             Integer a[] = new Integer[n];
  241.             for (int i = 0; i < n; ++i) {
  242.                 a[i] = jin.nextInt();
  243.             }
  244.             IntegerList list = new IntegerList(a);
  245.             while (true) {
  246.                 int num = jin.nextInt();
  247.                 if (num == 0) { //count
  248.                     list.shiftLeft(jin.nextInt(), jin.nextInt());
  249.                 }
  250.                 if (num == 1) {
  251.                     list.shiftRight(jin.nextInt(), jin.nextInt());
  252.                 }
  253.                 if (num == 2) {
  254.                     System.out.println(list.sumFirst(jin.nextInt()));
  255.                 }
  256.                 if (num == 3) {
  257.                     System.out.println(list.sumLast(jin.nextInt()));
  258.                 }
  259.                 if (num == 4) {
  260.                     print(list);
  261.                 }
  262.                 if (num == 5) {
  263.                     break;
  264.                 }
  265.             }
  266.         }
  267.     }
  268.  
  269.     public static void print(IntegerList il) {
  270.         if (il.size() == 0) System.out.print("EMPTY");
  271.         for (int i = 0; i < il.size(); ++i) {
  272.             if (i > 0) System.out.print(" ");
  273.             System.out.print(il.get(i));
  274.         }
  275.         System.out.println();
  276.     }
  277.  
  278. }
Advertisement
Add Comment
Please, Sign In to add comment