diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..e7bedf3 --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/ArrayForMargeSort.txt b/ArrayForMargeSort.txt new file mode 100644 index 0000000..770ac0a --- /dev/null +++ b/ArrayForMargeSort.txt @@ -0,0 +1 @@ +[9, 5, 8, 1, 2] \ No newline at end of file diff --git a/Text.txt b/Text.txt new file mode 100644 index 0000000..50524ca --- /dev/null +++ b/Text.txt @@ -0,0 +1 @@ +Hello Java!!! \ No newline at end of file diff --git a/TextTest.txt b/TextTest.txt new file mode 100644 index 0000000..fa294c1 --- /dev/null +++ b/TextTest.txt @@ -0,0 +1 @@ +Hello Sidney. \ No newline at end of file diff --git a/gojavaonline.iml b/gojavaonline.iml index c90834f..3a8ffcf 100644 --- a/gojavaonline.iml +++ b/gojavaonline.iml @@ -7,5 +7,15 @@ + + + + + + + + + + \ No newline at end of file diff --git a/result.txt b/result.txt new file mode 100644 index 0000000..dc1e146 --- /dev/null +++ b/result.txt @@ -0,0 +1,38 @@ ++-----------------------------------------------------------------------------------------------+ +| add get remove contains populate iter.add iter.remove | ++-----------------------------------------------------------------------------------------------+ +| ArrayList: 2 3 824 16267 16267 18128 19926 | +| LinkedList: 2 5404 10608 25711 455593 455614 455622 | +| TreeSet: 1 2 3 4 | +| HashSet: 1 5 6 6 | ++-----------------------------------------------------------------------------------------------+ +Collection type add get remove contains populate iterator.add iterator.remove + (Results for 10K elements in the collection) + +ArrayList 15042 2418 18237 273202 658710 25760 550263 +LinkedList 36943 23605 24154 214500 984790 4810 72186 +HashSet 468 n/a 6403 2922 1454461 n/a n/a +TreeSet 1209 n/a 19946 5381 8354638 n/a n/a + + + +Collection type add get remove contains populate iterator.add iterator.remove + (Results for 10K elements in the collection) + +ArrayList 25417 3641 22271 320118 860128 25961 783609 +LinkedList 43315 21548 23841 530790 1873334 6747 108562 +HashSet 1066 n/a 10553 5421 2403901 n/a n/a +TreeSet 2436 n/a 28746 17161 7957590 n/a n/a + + + +Collection type add get remove contains populate iterator.add iterator.remove + (Results for 100K elements in the collection) + +ArrayList 114617 3873 204991 3097672 9024633 268967 36143716 +LinkedList 367360 376632 441848 2209695 34071427 5113 264492 +HashSet 1008 n/a 6309 3355 33759376 n/a n/a +TreeSet 2008 n/a 26157 3748 160855050 n/a n/a + + + diff --git a/src/CollectionFramework/ArrayListToSimpleArrayPage583.java b/src/CollectionFramework/ArrayListToSimpleArrayPage583.java new file mode 100644 index 0000000..e26eb7a --- /dev/null +++ b/src/CollectionFramework/ArrayListToSimpleArrayPage583.java @@ -0,0 +1,24 @@ +package CollectionFramework; + +import java.util.ArrayList; + +public class ArrayListToSimpleArrayPage583 { + public static void main(String[] args) { + ArrayList arrayList = new ArrayList<>(); + + for (int i = 1; i < 5; i++) { + arrayList.add(i); + } + + System.out.println("Содержимое списка массива: " + arrayList); + + Integer[] simpleArray = new Integer[arrayList.size()]; + simpleArray = arrayList.toArray(simpleArray); + + int sum = 0; + + for (int i : simpleArray) sum += i; + System.out.println("Сумма: " + sum); + } +} + diff --git a/src/CollectionFramework/SaveDataCollectionsPage600.java b/src/CollectionFramework/SaveDataCollectionsPage600.java new file mode 100644 index 0000000..be9704f --- /dev/null +++ b/src/CollectionFramework/SaveDataCollectionsPage600.java @@ -0,0 +1,43 @@ +package CollectionFramework; + +import java.util.LinkedList; + +public class SaveDataCollectionsPage600 { + public static void main(String[] args) { + LinkedList
addresses = new LinkedList<>(); + addresses.add(new Address("J.W West", "11 Oak Ave", "Urbana", "1L", "61801")); + addresses.add(new Address("P.D East", "12 Oak Ave", "Urbana", "9L", "61966")); + addresses.add(new Address("O.K South", "13 Oak Ave", "Urbana", "6L", "77777")); + + for (Address element : addresses) { + System.out.print(element + "\n"); + } + } +} + +class Address { + private String name; + private String street; + private String city; + private String state; + private String code; + + public Address(String name, String street, String city, String state, String code) { + this.name = name; + this.street = street; + this.city = city; + this.state = state; + this.code = code; + } + + @Override + public String toString() { + return "Address{" + + "name='" + name + '\'' + + ", street='" + street + '\'' + + ", city='" + city + '\'' + + ", state='" + state + '\'' + + ", code='" + code + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/CollectionFramework/UseArrayDequePage590.java b/src/CollectionFramework/UseArrayDequePage590.java new file mode 100644 index 0000000..5fb78dc --- /dev/null +++ b/src/CollectionFramework/UseArrayDequePage590.java @@ -0,0 +1,23 @@ +package CollectionFramework; + +import java.util.ArrayDeque; + +public class UseArrayDequePage590 { + public static void main(String[] args) { + ArrayDeque arrayDeque = new ArrayDeque<>(); + + arrayDeque.push("A"); + arrayDeque.push("B"); + arrayDeque.push("D"); + arrayDeque.push("E"); + arrayDeque.push("F"); + + System.out.println("Извлечение из стека: "); +//выводится по умолчанию начиная с последнего эллемента + while (arrayDeque.peek() != null) { + System.out.print(arrayDeque.pop() + " "); + + System.out.println(); + } + } +} diff --git a/src/CollectionFramework/UseArrayListPage581.java b/src/CollectionFramework/UseArrayListPage581.java new file mode 100644 index 0000000..849496d --- /dev/null +++ b/src/CollectionFramework/UseArrayListPage581.java @@ -0,0 +1,25 @@ +package CollectionFramework; + + +import java.util.ArrayList; + +public class UseArrayListPage581 { + public static void main(String[] args) { + + ArrayList arrayList = new ArrayList<>(); + System.out.println("Начальный размер списочного массива arrayList: " + arrayList.size()); + arrayList.add("C"); + arrayList.add("A"); + arrayList.add("E"); + arrayList.add("B"); + arrayList.add("D"); + arrayList.add("F"); + arrayList.add(1, "A2"); + System.out.println("Содержимое списочного массива: " + arrayList); + arrayList.remove("F"); + arrayList.remove(2); + System.out.println("Размер списочного массива arrayList после удаления элементов: " + arrayList.size()); + System.out.println("Содержимое списочного массива: " + arrayList); + + } +} diff --git a/src/CollectionFramework/UseForEachPage595.java b/src/CollectionFramework/UseForEachPage595.java new file mode 100644 index 0000000..d60656c --- /dev/null +++ b/src/CollectionFramework/UseForEachPage595.java @@ -0,0 +1,24 @@ +package CollectionFramework; + +import java.util.ArrayList; + +public class UseForEachPage595 { + public static void main(String[] args) { + ArrayList arrayList = new ArrayList<>(); + + for (int i = 1; i < 6; i++) { + arrayList.add(i); + } + //вывод содержимого коллекции + for (int value : arrayList) { + System.out.print(value + " "); + } + System.out.println(); + //сумирование чисел + int sum = 0; + for (int value : arrayList) { + sum+= value; + } + System.out.println(sum); + } +} diff --git a/src/CollectionFramework/UseHashSetPage586.java b/src/CollectionFramework/UseHashSetPage586.java new file mode 100644 index 0000000..859d6a8 --- /dev/null +++ b/src/CollectionFramework/UseHashSetPage586.java @@ -0,0 +1,19 @@ +package CollectionFramework; + +import java.util.HashSet; + +public class UseHashSetPage586 { + public static void main(String[] args) { + HashSet hashSet = new HashSet<>(); + hashSet.add("Бета"); + hashSet.add("Альфа"); + hashSet.add("Эта"); + hashSet.add("Гамма"); + hashSet.add("Эпсилон"); + hashSet.add("Омега"); + + //порядок вызова эллементов может варироваться + System.out.println(hashSet); + + } +} diff --git a/src/CollectionFramework/UseIteratorPage594.java b/src/CollectionFramework/UseIteratorPage594.java new file mode 100644 index 0000000..ca51215 --- /dev/null +++ b/src/CollectionFramework/UseIteratorPage594.java @@ -0,0 +1,48 @@ +package CollectionFramework; + +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.ListIterator; + +public class UseIteratorPage594 { + public static void main(String[] args) { + AbstractList arrayList = new ArrayList<>(); + arrayList.add("C"); + arrayList.add("A"); + arrayList.add("E"); + arrayList.add("B"); + arrayList.add("D"); + arrayList.add("F"); + + System.out.print("Исходное содержимое списочного массива: "); + Iterator listIterator = arrayList.listIterator(); + while (listIterator.hasNext()) { + String element = listIterator.next(); + System.out.print(element + " "); + } + System.out.println(); + + + //видоизменить перебираемые эллементы + ListIterator stringListIterator = arrayList.listIterator(); + while (stringListIterator.hasNext()) { + String element = stringListIterator.next(); + System.out.print(element + "+"); + } + System.out.println(); + + while (listIterator.hasNext()) { + String element = listIterator.next(); + System.out.print(element + " "); + } + System.out.println(); + //отобразить список в обратном порядке + System.out.print("Изменить содержимое списочного массива в обратном порядке: "); + while (stringListIterator.hasPrevious()) { + String element = stringListIterator.previous(); + System.out.print(element + " "); + } + System.out.println(); + } +} diff --git a/src/CollectionFramework/UseLinkedHashSetPage587.java b/src/CollectionFramework/UseLinkedHashSetPage587.java new file mode 100644 index 0000000..43beb01 --- /dev/null +++ b/src/CollectionFramework/UseLinkedHashSetPage587.java @@ -0,0 +1,18 @@ +package CollectionFramework; + +import java.util.LinkedHashSet; + +public class UseLinkedHashSetPage587 { + public static void main(String[] args) { + LinkedHashSet hashSet = new LinkedHashSet<>(); + hashSet.add("Бета"); + hashSet.add("Альфа"); + hashSet.add("Эта"); + hashSet.add("Гамма"); + hashSet.add("Эпсилон"); + hashSet.add("Омега"); + + //В отличие от HashSet порядок эллементов отображается так как был введен + System.out.println(hashSet); + } +} diff --git a/src/CollectionFramework/UseLinkedListPage584.java b/src/CollectionFramework/UseLinkedListPage584.java new file mode 100644 index 0000000..52c4913 --- /dev/null +++ b/src/CollectionFramework/UseLinkedListPage584.java @@ -0,0 +1,35 @@ +package CollectionFramework; + +import java.util.LinkedList; + +public class UseLinkedListPage584 { + public static void main(String[] args) { + LinkedList linkedList = new LinkedList<>(); + + linkedList.add("F"); + linkedList.add("B"); + linkedList.add("D"); + linkedList.add("E"); + linkedList.add("C"); + linkedList.addLast("Z"); + linkedList.addFirst("A"); + linkedList.add(1, "A2"); + + System.out.println("Исходное содержимое связаного списка: " + linkedList); + + linkedList.remove("F"); + linkedList.remove(2); + + System.out.println("Содержимое спска после удалления элементов: " + linkedList); + + linkedList.removeFirst(); + linkedList.removeLast(); + + System.out.println("Содержимое спска после удалления первого и последнего элементов: " + linkedList); + + String val = linkedList.get(2); + linkedList.set(2, val + " изменено"); + + System.out.println("Содержимое списка после изменения: " + linkedList); + } +} diff --git a/src/CollectionFramework/UseSpliterator.java b/src/CollectionFramework/UseSpliterator.java new file mode 100644 index 0000000..eb40634 --- /dev/null +++ b/src/CollectionFramework/UseSpliterator.java @@ -0,0 +1,30 @@ +package CollectionFramework; + +import java.util.ArrayList; +import java.util.Spliterator; + +public class UseSpliterator { + public static void main(String[] args) { + ArrayList arrayList = new ArrayList<>(); + arrayList.add(1.0); + arrayList.add(2.0); + arrayList.add(3.0); + arrayList.add(4.0); + arrayList.add(5.0); + + //вызов метода tryAdvance для вывода содержимого списосчного массива + Spliterator spliterator = arrayList.spliterator(); + while (spliterator.tryAdvance((n) -> System.out.println(n))) ; + System.out.println(); + + //создать новый списочный массив содержащий квадратные корни числовых значений из arrayList + spliterator = arrayList.spliterator(); + ArrayList sqrt = new ArrayList<>(); + while (spliterator.tryAdvance((n) -> sqrt.add(Math.sqrt(n)))) ; + System.out.println(); + + //вызвать метод forEachRemaining для вывода содержимого списочного массива + spliterator = sqrt.spliterator(); + spliterator.forEachRemaining((n) -> System.out.println(n)); + } +} diff --git a/src/CollectionFramework/UseTreeMapPage611.java b/src/CollectionFramework/UseTreeMapPage611.java new file mode 100644 index 0000000..6b3be16 --- /dev/null +++ b/src/CollectionFramework/UseTreeMapPage611.java @@ -0,0 +1,30 @@ +package CollectionFramework; + +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +public class UseTreeMapPage611 { + public static void main(String[] args) { + TreeMap tm = new TreeMap<>(); + tm.put("Джон, Доу", new Double(3434.34)); + tm.put("Том, Смит", new Double(99.34)); + tm.put("Джейн, Бейкер", new Double(126.56)); + + //получить множество записей + Set> set = tm.entrySet(); + + //вывести множество + for (Map.Entry me : set) { + System.out.print(me.getKey() + ": "); + System.out.println(me.getValue()); + } + + System.out.println(); + + //внести сумму 1000 на счет Джона Доу + double balance = tm.get("Джон Доу"); + tm.put("Джон Доу", balance + 1000.00); + System.out.println("Новый остаток на счете Джона Доу: " + tm.get("Джон Доу")); + } +} diff --git a/src/CollectionFramework/UseTreeSetPage588.java b/src/CollectionFramework/UseTreeSetPage588.java new file mode 100644 index 0000000..4e43893 --- /dev/null +++ b/src/CollectionFramework/UseTreeSetPage588.java @@ -0,0 +1,22 @@ +package CollectionFramework; + +import java.util.TreeSet; + +public class UseTreeSetPage588 { + public static void main(String[] args) { + TreeSet treeSet = new TreeSet<>(); + + treeSet.add("D"); + treeSet.add("Z"); + treeSet.add("Y"); + treeSet.add("A"); + treeSet.add("W"); + treeSet.add("H"); + treeSet.add("О"); + //Сразу заполняеет и выводит в отсортированом виде. + System.out.println(treeSet); + + //можно выводить отдельное множество + System.out.println(treeSet.subSet("D", "Y")); + } +} diff --git a/src/CollectionFramework/use_Comparator/CompDemo.java b/src/CollectionFramework/use_Comparator/CompDemo.java new file mode 100644 index 0000000..9f53d25 --- /dev/null +++ b/src/CollectionFramework/use_Comparator/CompDemo.java @@ -0,0 +1,20 @@ +package CollectionFramework.use_Comparator; + +import java.util.TreeSet; + +public class CompDemo { + public static void main(String[] args) { + TreeSet treeSet = new TreeSet(new MyComp()); + treeSet.add("A"); + treeSet.add("Z"); + treeSet.add("X"); + treeSet.add("W"); + treeSet.add("K"); + treeSet.add("O"); + + for (String element : treeSet) { + System.out.print(element + " "); + System.out.println(); + } + } +} diff --git a/src/CollectionFramework/use_Comparator/MyComp.java b/src/CollectionFramework/use_Comparator/MyComp.java new file mode 100644 index 0000000..74a334a --- /dev/null +++ b/src/CollectionFramework/use_Comparator/MyComp.java @@ -0,0 +1,15 @@ +package CollectionFramework.use_Comparator; + +import java.util.Comparator; + +class MyComp implements Comparator { + @Override + public int compare(String a, String b) { + String aStr, bStr; + aStr = a; + bStr = b; + //выполнить сравнение в обратном порядке + return bStr.compareTo(aStr); + } +} + diff --git a/src/CollectionFramework/use_Comparator/UseLiambda.java b/src/CollectionFramework/use_Comparator/UseLiambda.java new file mode 100644 index 0000000..fd6d822 --- /dev/null +++ b/src/CollectionFramework/use_Comparator/UseLiambda.java @@ -0,0 +1,15 @@ +package CollectionFramework.use_Comparator; + +import java.util.TreeSet; + +public class UseLiambda { + public static void main(String[] args) { + MyComp aStr = new MyComp(); + MyComp bStr = new MyComp(); + + //передать компаратор с обратным упорядочением древовидному множеству TreeSet + + // TreeSet ts = new TreeSet(aStr, bStr) -> bStr.compareTo(aStr)); + + } +} diff --git a/src/mergeSort/ArrayReader.java b/src/mergeSort/ArrayReader.java new file mode 100644 index 0000000..739e271 --- /dev/null +++ b/src/mergeSort/ArrayReader.java @@ -0,0 +1,5 @@ +package mergeSort; + +public interface ArrayReader { + public abstract void read(); +} diff --git a/src/mergeSort/ArrayWriter.java b/src/mergeSort/ArrayWriter.java new file mode 100644 index 0000000..5a1686c --- /dev/null +++ b/src/mergeSort/ArrayWriter.java @@ -0,0 +1,5 @@ +package mergeSort; + +public interface ArrayWriter { + public abstract void write(); +} diff --git a/src/mergeSort/ConsoleInOut.java b/src/mergeSort/ConsoleInOut.java new file mode 100644 index 0000000..cc0de5d --- /dev/null +++ b/src/mergeSort/ConsoleInOut.java @@ -0,0 +1,48 @@ +package mergeSort; + + +import java.util.Scanner; + +public class ConsoleInOut implements ArrayReader, ArrayWriter { + + private int size; + private int array[]; + + public int[] getArray() { + return array; + } + + public void setArray(int[] array) { + this.array = array; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + @Override + + public void write() { + + Scanner input = new Scanner(System.in); + System.out.println("Ведите длину массива: "); + setSize(input.nextInt()); + setArray(new int[getSize()]); + System.out.println("Заполните массив числами: "); + for (int i = 0; i < size; i++) { + array[i] = input.nextInt(); + } + } + + @Override + public void read() { + System.out.print("Заполненный массив состоит из следующих чисел:"); + for (int i = 0; i < size; i++) { + System.out.print(" " + array[i]); + } + } +} diff --git a/src/mergeSort/FileInOut.java b/src/mergeSort/FileInOut.java new file mode 100644 index 0000000..985d477 --- /dev/null +++ b/src/mergeSort/FileInOut.java @@ -0,0 +1,62 @@ +package mergeSort; + + +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Arrays; +import java.util.Scanner; + +public class FileInOut implements ArrayWriter, ArrayReader { + private int size; + private int array[]; + String fileName = "ArrayForMargeSort.txt"; + + public int[] getArray() { + return array; + } + + public void setArray(int[] array) { + this.array = array; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + @Override + public void write() { + Scanner input = new Scanner(System.in); + System.out.println("Ведите длину массива: "); + setSize(input.nextInt()); + setArray(new int[getSize()]); + System.out.println("Заполните массив числами: "); + for (int i = 0; i < size; i++) { + array[i] = input.nextInt(); + } + + try (FileWriter writer = new FileWriter(fileName)) { + writer.write(Arrays.toString(array)); + writer.flush(); + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + } + + @Override + public void read() { + try (FileReader reader = new FileReader(fileName)) { + int c; + System.out.print("Заполненный массив состоит из следующих чисел:"); + while ((c = reader.read()) != -1) { + System.out.print((char) c); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + } +} diff --git a/src/mergeSort/MergeSort.java b/src/mergeSort/MergeSort.java new file mode 100644 index 0000000..1c2a867 --- /dev/null +++ b/src/mergeSort/MergeSort.java @@ -0,0 +1,35 @@ +package mergeSort; + +import java.util.Arrays; + +public class MergeSort { + + public static int[] sort(int[] arr) { + if (arr.length < 2) return arr; + int m = arr.length / 2; + int[] arr1 = Arrays.copyOfRange(arr, 0, m); + int[] arr2 = Arrays.copyOfRange(arr, m, arr.length); + return merge(sort(arr1), sort(arr2)); + } + + public static int[] merge(int[] arr1, int arr2[]) { + int n = arr1.length + arr2.length; + int[] arr = new int[n]; + int i1 = 0; + int i2 = 0; + for (int i = 0; i < n; i++) { + if (i1 == arr1.length) { + arr[i] = arr2[i2++]; + } else if (i2 == arr2.length) { + arr[i] = arr1[i1++]; + } else { + if (arr1[i1] < arr2[i2]) { + arr[i] = arr1[i1++]; + } else { + arr[i] = arr2[i2++]; + } + } + } + return arr; + } +} \ No newline at end of file diff --git a/src/mergeSort/MergeSortDrive.java b/src/mergeSort/MergeSortDrive.java new file mode 100644 index 0000000..1575c2d --- /dev/null +++ b/src/mergeSort/MergeSortDrive.java @@ -0,0 +1,32 @@ +package mergeSort; + +import java.util.Arrays; + +public class MergeSortDrive { + public static void main(String[] args) { + + try { + MergeSort mergeSort = new MergeSort(); + System.out.println("Первый вариант - считывание данных для сортировки с консоли."); + ConsoleInOut consoleArrayReader = new ConsoleInOut(); + consoleArrayReader.write(); + consoleArrayReader.read(); + System.out.println(); + System.out.print("Отсортированный массив методом слияния: "); + System.out.println(Arrays.toString(mergeSort.sort(consoleArrayReader.getArray())) + '\n'); + + System.out.println("Второй вариант - считывание данных для сортировки с файла."); + FileInOut fileArrayReader = new FileInOut(); + fileArrayReader.write(); + fileArrayReader.read(); + System.out.println(); + System.out.print("Отсортированный массив методом слияния: "); + System.out.println(Arrays.toString(mergeSort.sort(fileArrayReader.getArray()))); + } catch (Exception e) { + System.out.println("Вы ввели недопустимый символ." + '\n' + + "Длина массива должна иметь цыфровое значение и быть больше ноля." + '\n' + + "Заполнять массив можно только цыфрами значения меньше ноля допускаются." + '\n' + + "Перезагрузите пожалуйста приложение и введите данные заново."); + } + } +} diff --git a/src/mergeSort/MergeSortTest.java b/src/mergeSort/MergeSortTest.java new file mode 100644 index 0000000..6691838 --- /dev/null +++ b/src/mergeSort/MergeSortTest.java @@ -0,0 +1,26 @@ +package mergeSort; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +public class MergeSortTest { + @Test + public void testSort() throws Exception { + int[] arr = {2, 1, 9, 3}; + int[] correctArr = {1, 2, 3, 9}; + MergeSort mergeSort = new MergeSort(); + Assert.assertArrayEquals(correctArr, mergeSort.sort(arr)); + } + + @Test + public void testMerge() throws Exception { + int[] arrFirst = {2, 9, 1}; + int[] arrSecond = {8, 1, 7}; + + MergeSort mergeSort = new MergeSort(); + System.out.println(Arrays.toString(mergeSort.merge(arrFirst, arrSecond))); + } +} + diff --git a/src/module10/CaesarCipherTestDrive.java b/src/module10/CaesarCipherTestDrive.java new file mode 100644 index 0000000..ea4710b --- /dev/null +++ b/src/module10/CaesarCipherTestDrive.java @@ -0,0 +1,25 @@ +package module10; + +import java.io.*; +import java.util.Scanner; + +public class CaesarCipherTestDrive { + public static void main(String[] args) throws IOException { + + CeasarCipher ceasarCipher = new CeasarCipher(); + Scanner scanner = new Scanner(System.in); + System.out.println("Print text:"); + String text = scanner.nextLine(); + System.out.println("Print key:"); + int key = scanner.nextInt(); + System.out.println(); + System.out.println("Caesar Cipher in work:"); + + FileUtil fileUtil = new FileUtil(); + fileUtil.write("Text.txt", ceasarCipher.encrypt(text, key)); + fileUtil.read("Text.txt"); + System.out.println(); + fileUtil.write("Text.txt", ceasarCipher.decrypt(ceasarCipher.encrypt(text, key), key)); + fileUtil.read("Text.txt"); + } +} \ No newline at end of file diff --git a/src/module10/CeasarCipher.java b/src/module10/CeasarCipher.java new file mode 100644 index 0000000..13129d7 --- /dev/null +++ b/src/module10/CeasarCipher.java @@ -0,0 +1,45 @@ +package module10; + + +public class CeasarCipher { + + public static String encrypt(String str, int keyLength) { + String encrypted = ""; + for (int i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c + (keyLength % 26); + if (c > 'Z') + c = c - 26; + } else if (Character.isLowerCase(c)) { + c = c + (keyLength % 26); + + if (c > 'z') + c = c - 26; + } + encrypted = encrypted + (char) c; + } + return encrypted; + } + + public static String decrypt(String str, int keyLength) { + String decrypted = ""; + for (int i = 0; i < str.length(); i++) { + + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c - (keyLength % 26); + + if (c < 'A') + c = c + 26; + } else if (Character.isLowerCase(c)) { + c = c - (keyLength % 26); + + if (c < 'a') + c = c + 26; + } + decrypted = decrypted + (char) c; + } + return decrypted; + } +} diff --git a/src/module10/FileUtil.java b/src/module10/FileUtil.java new file mode 100644 index 0000000..f96038a --- /dev/null +++ b/src/module10/FileUtil.java @@ -0,0 +1,28 @@ +package module10; + +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +public class FileUtil { + + public void read(String fileName) { + try (FileReader reader = new FileReader(fileName)) { + int c; + while ((c = reader.read()) != -1) { + System.out.print((char) c); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + } + + public void write(String filename, String textToWrite) { + try (FileWriter writer = new FileWriter(filename)) { + writer.write(textToWrite); + writer.flush(); + } catch (IOException ex) { + System.out.println("Decrypt: " + ex.getMessage()); + } + } +} diff --git a/src/module2_1/ArrayListMeasurements.java b/src/module2_1/ArrayListMeasurements.java new file mode 100644 index 0000000..916c7af --- /dev/null +++ b/src/module2_1/ArrayListMeasurements.java @@ -0,0 +1,85 @@ +package module2_1; + +import java.util.ArrayList; +import java.util.ListIterator; +import java.util.Random; + +public class ArrayListMeasurements { + + private static final int COUNT_LIST_TEST_METHODS = 7; + private static final int NUMBER_OF_TESTS = 10; + + private long[][] measurementsArrayList = new long[COUNT_LIST_TEST_METHODS][NUMBER_OF_TESTS]; + private long[] resultTimersArrayList = new long[COUNT_LIST_TEST_METHODS]; + + private ArrayList arrayList = new ArrayList<>(); + + void initialisation(int size) { + + for (int i = 0; i < size; i++) { + arrayList.add(i); + } + + measureArrayList(); + + MainFirstEEmodule.temp = calculateArrayListTimers(); + } + + private long[] calculateArrayListTimers() { + long res = measurementsArrayList[0][0]; + + for (int j = 0; j < measurementsArrayList.length; j++) { + for (int i = 1; i < NUMBER_OF_TESTS - 1; i++) { + + res += measurementsArrayList[j][i]; + } + resultTimersArrayList[j] = res / NUMBER_OF_TESTS; + } + return resultTimersArrayList; + } + + public long[] getResultTimersArrayList() { + return resultTimersArrayList; + } + + private void measureArrayList() { + Random randomNumber = new Random(); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + + int rnd = randomNumber.nextInt(arrayList.size() + 1); + + long timerAdd = System.nanoTime(); + arrayList.add(rnd); + measurementsArrayList[0][i] = System.nanoTime() - timerAdd; + + long timerGet = System.nanoTime(); + arrayList.get(rnd); + measurementsArrayList[1][i] = System.nanoTime() - timerGet; + + long timerRemove = System.nanoTime(); + arrayList.remove(rnd); + measurementsArrayList[2][i] = System.nanoTime() - timerRemove; + + long timerContains = System.nanoTime(); + arrayList.contains(rnd); + measurementsArrayList[3][i] = System.nanoTime() - timerContains; + + long timerPopulate = System.nanoTime(); + measurementsArrayList[4][i] = System.nanoTime() - timerPopulate; + + long timerIterAdd = System.nanoTime(); + ListIterator iterator = arrayList.listIterator(); + iterator.next(); + iterator.add(rnd); + + measurementsArrayList[5][i] = System.nanoTime() - timerIterAdd; + + long timerIterRemove = System.nanoTime(); + ListIterator iter = arrayList.listIterator(); + iter.next(); + iter.remove(); + + measurementsArrayList[6][i] = System.nanoTime() - timerIterRemove; + } + } +} diff --git a/src/module2_1/HashSetMeasurements.java b/src/module2_1/HashSetMeasurements.java new file mode 100644 index 0000000..99d0dfc --- /dev/null +++ b/src/module2_1/HashSetMeasurements.java @@ -0,0 +1,67 @@ +package module2_1; + +import java.util.HashSet; +import java.util.Random; +import java.util.Set; + +public class HashSetMeasurements { + + private static final int COUNT_SET_TEST_METHODS = 4; + private static final int NUMBER_OF_TESTS = 10; + + private long[][] measurementsHashSet = new long[COUNT_SET_TEST_METHODS][NUMBER_OF_TESTS]; + private long[] resultTimersHashSet = new long[COUNT_SET_TEST_METHODS]; + + private final Set hashSet = new HashSet<>(); + + void initialization(int size) { + for (int i = 0; i < size; i++) { + hashSet.add(i); + } + + measureHashSet(); + + MainFirstEEmodule.temp = calculateHashSetTimers(); + } + + private long[] calculateHashSetTimers() { + long res = measurementsHashSet[0][0]; + + for (int j = 0; j < measurementsHashSet.length; j++) { + for (int i = 1; i < NUMBER_OF_TESTS - 1; i++) { + + res += measurementsHashSet[j][i]; + } + resultTimersHashSet[j] = res / NUMBER_OF_TESTS; + } + return resultTimersHashSet; + } + + long[] getResultTimersHashSet() { + return resultTimersHashSet; + } + + private void measureHashSet() { + Random randomNumber = new Random(); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + + int rnd = randomNumber.nextInt(hashSet.size() + 1); + + long timerAdd = System.nanoTime(); + hashSet.add(rnd); + measurementsHashSet[0][i] = System.nanoTime() - timerAdd; + + long timerRemove = System.nanoTime(); + hashSet.remove(rnd); + measurementsHashSet[1][i] = System.nanoTime() - timerRemove; + + long timerContains = System.nanoTime(); + hashSet.contains(rnd); + measurementsHashSet[2][i] = System.nanoTime() - timerContains; + + hashSet.clear(); + long timerPopulate = System.nanoTime(); + measurementsHashSet[3][i] = System.nanoTime() - timerPopulate; + } + } +} \ No newline at end of file diff --git a/src/module2_1/LinkedListMeasurements.java b/src/module2_1/LinkedListMeasurements.java new file mode 100644 index 0000000..e5fd396 --- /dev/null +++ b/src/module2_1/LinkedListMeasurements.java @@ -0,0 +1,87 @@ +package module2_1; + +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; +import java.util.Random; + +class LinkedListMeasurements { + + private static final int COUNT_LIST_TEST_METHODS = 7; + private static final int NUMBER_OF_TESTS = 10; + + private long[][] measurementsLinkedList = new long[COUNT_LIST_TEST_METHODS][NUMBER_OF_TESTS]; + private long[] resultTimersLinkedList = new long[COUNT_LIST_TEST_METHODS]; + + private LinkedList linkedList = new LinkedList<>(); + + void initialisation(int size) { + + for (int i = 0; i < size; i++) { + linkedList.add(i); + } + + measureLinkedList(); + + MainFirstEEmodule.temp = calculateLinkedListTimers(); + } + + private long[] calculateLinkedListTimers() { + long res = measurementsLinkedList[0][0]; + + for (int j = 0; j < measurementsLinkedList.length; j++) { + for (int i = 1; i < NUMBER_OF_TESTS; i++) { + + res += measurementsLinkedList[j][i]; + } + resultTimersLinkedList[j] = res / NUMBER_OF_TESTS; + } + return resultTimersLinkedList; + } + + long[] getResultTimersLinkedList() { + return resultTimersLinkedList; + } + + private void measureLinkedList() { + Random randomNumber = new Random(); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + + int rnd = randomNumber.nextInt(linkedList.size() + 1); + + long timerAdd = System.nanoTime(); + linkedList.add(rnd); + measurementsLinkedList[0][i] = System.nanoTime() - timerAdd; + + long timerGet = System.nanoTime(); + linkedList.get(rnd); + measurementsLinkedList[1][i] = System.nanoTime() - timerGet; + + long timerRemove = System.nanoTime(); + linkedList.remove(rnd); + measurementsLinkedList[2][i] = System.nanoTime() - timerRemove; + + long timerContains = System.nanoTime(); + linkedList.contains(rnd); + measurementsLinkedList[3][i] = System.nanoTime() - timerContains; + + long timerPopulate = System.nanoTime(); + List newLinkedList = new LinkedList(linkedList); + measurementsLinkedList[4][i] = System.nanoTime() - timerPopulate; + + long timerIterAdd = System.nanoTime(); + ListIterator iterator = linkedList.listIterator(); + iterator.next(); + iterator.add(rnd); + + measurementsLinkedList[5][i] = System.nanoTime() - timerIterAdd; + + long timerIterRemove = System.nanoTime(); + iterator = linkedList.listIterator(); + iterator.next(); + iterator.remove(); + + measurementsLinkedList[6][i] = System.nanoTime() - timerIterRemove; + } + } +} diff --git a/src/module2_1/MainFirstEEmodule.java b/src/module2_1/MainFirstEEmodule.java new file mode 100644 index 0000000..436b6d7 --- /dev/null +++ b/src/module2_1/MainFirstEEmodule.java @@ -0,0 +1,73 @@ +package module2_1; + + +public class MainFirstEEmodule { + private static final int COUNT_LIST_TEST_METHODS = 7; + private static final int COUNT_SET_TEST_METHODS = 4; + + private static final int NUM10K = 10000; + private static final int NUM100K = 100000; + private static final int NUM1000K = 1000000; + + + static long[] temp = new long[7]; + + public static void main(String[] args) { + long[] resArray = new long[COUNT_LIST_TEST_METHODS]; + long[] resLinked = new long[COUNT_LIST_TEST_METHODS]; + long[] resTree = new long[COUNT_SET_TEST_METHODS]; + long[] resHash = new long[COUNT_SET_TEST_METHODS]; + + LinkedListMeasurements linkedListMeasurements = new LinkedListMeasurements(); + ArrayListMeasurements arrayListMeasurements = new ArrayListMeasurements(); + TreeSetMeasurements treeSetMeasurements = new TreeSetMeasurements(); + HashSetMeasurements hashSetMeasurements = new HashSetMeasurements(); + + linkedListMeasurements.initialisation(NUM10K); + long[] resTemp10k = linkedListMeasurements.getResultTimersLinkedList(); + linkedListMeasurements.initialisation(NUM100K); + long[] resTemp100k = linkedListMeasurements.getResultTimersLinkedList(); + linkedListMeasurements.initialisation(NUM1000K); + long[] resTemp1000k = linkedListMeasurements.getResultTimersLinkedList(); + + for (int i = 0; i < resLinked.length; i++) { + resLinked[i] = (resTemp10k[i] + resTemp100k[i] + resTemp1000k[i]) / 3; + } + + arrayListMeasurements.initialisation(NUM10K); + resTemp10k = arrayListMeasurements.getResultTimersArrayList(); + arrayListMeasurements.initialisation(NUM100K); + resTemp100k = arrayListMeasurements.getResultTimersArrayList(); + arrayListMeasurements.initialisation(NUM1000K); + resTemp1000k = arrayListMeasurements.getResultTimersArrayList(); + + for (int i = 0; i < resArray.length; i++) { + resArray[i] = (resTemp10k[i] + resTemp100k[i] + resTemp1000k[i]) / 3; + } + treeSetMeasurements.Initialization(NUM10K); + resTemp10k = treeSetMeasurements.getResultTimersTreeSet(); + treeSetMeasurements.Initialization(NUM100K); + resTemp100k = treeSetMeasurements.getResultTimersTreeSet(); + treeSetMeasurements.Initialization(NUM1000K); + resTemp1000k = treeSetMeasurements.getResultTimersTreeSet(); + + for (int i = 0; i < resTree.length; i++) { + resTree[i] = (resTemp10k[i] + resTemp100k[i] + resTemp1000k[i]) / 3; + } + hashSetMeasurements.initialization(NUM10K); + resTemp10k = hashSetMeasurements.getResultTimersHashSet(); + hashSetMeasurements.initialization(NUM100K); + resTemp100k = hashSetMeasurements.getResultTimersHashSet(); + hashSetMeasurements.initialization(NUM1000K); + resTemp1000k = hashSetMeasurements.getResultTimersHashSet(); + + for (int i = 0; i < resHash.length; i++) { + resHash[i] = (resTemp10k[i] + resTemp100k[i] + resTemp1000k[i]) / 3; + } + + Print.printToConsole(resArray, resLinked, resTree, resHash); + Print.printToFile(resArray,resLinked,resTree,resHash); + } + + +} diff --git a/src/module2_1/Print.java b/src/module2_1/Print.java new file mode 100644 index 0000000..28b03a3 --- /dev/null +++ b/src/module2_1/Print.java @@ -0,0 +1,79 @@ +package module2_1; +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.Writer; + +public class Print { + static private String strip = "+-----------------------------------------------------------------------------------------------+"; + + static void printToConsole(long[] arrayList, long[] linkedList, long[] treeSet, long[] hashSet) { + System.out.println(strip); + printHead(); + + System.out.println(strip); + printArrayList("ArrayList", arrayList); + printLinkedList("LinkedList", linkedList); + + printSet("TreeSet", treeSet); + printSet("HashSet", hashSet); + + System.out.println(strip); + + } + + static void printToFile(long[] arrayList, long[] linkedList, long[] treeSet, long[] hashSet) { + + try (Writer writer = new BufferedWriter(new FileWriter("result.txt", true))) { + writer.flush(); + writer.write(strip + "\n"); + writer.write("|\t\t\t\t" + "add" + "\t\t" + "get" + "\t\t\t" + "remove" + "\t\t" + + "contains" + "\t" + "populate" + "\t" + "iter.add" + "\t" + "iter.remove" + " | \n"); + writer.write(strip + "\n"); + + writer.write("| " + "ArrayList" + ":\t" + arrayList[0] / 1000 + "\t\t" + arrayList[1] / 1000 + "\t\t\t" + + arrayList[2] / 1000 + "\t\t\t" + arrayList[3] / 1000 + "\t\t" + arrayList[4] / 1000 + "\t\t" + + arrayList[5] / 1000 + "\t\t" + arrayList[6] / 1000 + "\t\t| \n"); + + writer.write("| " + "LinkedList" + ":\t" + linkedList[0] / 1000 + "\t\t" + linkedList[1] / 1000 + "\t\t" + + linkedList[2] / 1000 + "\t\t" + linkedList[3] / 1000 + "\t\t" + linkedList[4] / 1000 + "\t\t" + + linkedList[5] / 1000 + "\t\t" + linkedList[6] / 1000 + "\t\t| \n"); + + writer.write("| " + "TreeSet" + ":\t\t" + treeSet[0] / 1000 + "\t\t\t\t\t" + treeSet[1] / 1000 + "\t\t\t" + + treeSet[2] / 1000 + "\t\t\t" + treeSet[3] / 1000 + "\t\t\t\t\t\t\t\t\t" + "| \n"); + + writer.write("| " + "HashSet" + ":\t\t" + hashSet[0] / 1000 + "\t\t\t\t\t" + hashSet[1] / 1000 + "\t\t\t" + + hashSet[2] / 1000 + "\t\t\t" + hashSet[3] / 1000 + "\t\t\t\t\t\t\t\t\t" + "| \n"); + + writer.write(strip + "\n"); + + } catch (Exception ex) { + System.out.println("Error saving data to file Result.txt"); + } + } + + + private static void printHead() { + System.out.println("|\t\t\t\t" + "add" + "\t\t" + "get" + "\t\t\t" + "remove" + "\t\t" + + "contains" + "\t" + "populate" + "\t" + "iter.add" + "\t" + "iter.remove" + " |"); + } + + private static void printArrayList(String name, long[] result) { + System.out.print("| " + name + ":\t" + result[0] / 1000 + "\t\t" + result[1] / 1000 + "\t\t\t" + + result[2] / 1000 + "\t\t\t" + result[3] / 1000 + "\t\t" + result[4] / 1000 + "\t\t" + + result[5] / 1000 + "\t\t" + result[6] / 1000 + "\t\t|"); + System.out.println(); + } + + private static void printLinkedList(String name, long[] result) { + System.out.print("| " + name + ":\t" + result[0] / 1000 + "\t\t" + result[1] / 1000 + "\t\t" + + result[2] / 1000 + "\t\t" + result[3] / 1000 + "\t\t" + result[4] / 1000 + "\t\t" + + result[5] / 1000 + "\t\t" + result[6] / 1000 + "\t\t|"); + System.out.println(); + } + + private static void printSet(String name, long[] result) { + System.out.print("| " + name + ":\t\t" + result[0] / 1000 + "\t\t\t\t\t" + result[1] / 1000 + "\t\t\t" + + result[2] / 1000 + "\t\t\t" + result[3] / 1000 + "\t\t\t\t\t\t\t\t\t" + "|"); + System.out.println(); + } +} \ No newline at end of file diff --git a/src/module2_1/TreeSetMeasurements.java b/src/module2_1/TreeSetMeasurements.java new file mode 100644 index 0000000..e7d8d3d --- /dev/null +++ b/src/module2_1/TreeSetMeasurements.java @@ -0,0 +1,69 @@ +package module2_1; + +import java.util.Random; +import java.util.Set; +import java.util.TreeSet; + +class TreeSetMeasurements { + + private static final int COUNT_SET_TEST_METHODS = 4; + private static final int NUMBER_OF_TESTS = 10; + + private long[][] measurementsTreeSet = new long[COUNT_SET_TEST_METHODS][NUMBER_OF_TESTS]; + private long[] resultTimersTreeSet = new long[COUNT_SET_TEST_METHODS]; + + private final Set treeSet = new TreeSet<>(); + + void Initialization(int size) { + for (int i = 0; i < size; i++) { + treeSet.add(i); + } + + measureTreeSet(); + + MainFirstEEmodule.temp = calculateTreeSetTimers(); + } + + + private long[] calculateTreeSetTimers() { + long res = measurementsTreeSet[0][0]; + + for (int j = 0; j < measurementsTreeSet.length; j++) { + for (int i = 1; i < NUMBER_OF_TESTS - 1; i++) { + + res += measurementsTreeSet[j][i]; + } + resultTimersTreeSet[j] = res / NUMBER_OF_TESTS; + } + return resultTimersTreeSet; + } + + long[] getResultTimersTreeSet() { + return resultTimersTreeSet; + } + + private void measureTreeSet() { + Random randomNumber = new Random(); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + + int rnd = randomNumber.nextInt(treeSet.size() + 1); + + long timerAdd = System.nanoTime(); + treeSet.add(rnd); + measurementsTreeSet[0][i] = System.nanoTime() - timerAdd; + + long timerRemove = System.nanoTime(); + treeSet.remove(rnd); + measurementsTreeSet[1][i] = System.nanoTime() - timerRemove; + + long timerContains = System.nanoTime(); + treeSet.contains(rnd); + measurementsTreeSet[2][i] = System.nanoTime() - timerContains; + + treeSet.clear(); + long timerPopulate = System.nanoTime(); + measurementsTreeSet[3][i] = System.nanoTime() - timerPopulate; + } + + } +} \ No newline at end of file diff --git a/src/module2_1/build.xml b/src/module2_1/build.xml new file mode 100644 index 0000000..faf3103 --- /dev/null +++ b/src/module2_1/build.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/module2_2/DoubleTask.java b/src/module2_2/DoubleTask.java new file mode 100644 index 0000000..7ca3ddf --- /dev/null +++ b/src/module2_2/DoubleTask.java @@ -0,0 +1,31 @@ +package module2_2; + +public class DoubleTask implements Task { + private Double value; + private Double result; + + public DoubleTask(Double value) { + this.value = value; + } + + @Override + public void execute() { + String s = value.toString(); + int lastNumberAfterPoint = s.charAt(s.length() - 1) - '0'; + if (lastNumberAfterPoint % 2 == 1) { + result = 1.0; + } else { + result = 0.0; + } + } + + @Override + public Double getResult() { + return result; + } + + @Override + public Double getValue() { + return value; + } +} \ No newline at end of file diff --git a/src/module2_2/Executor.java b/src/module2_2/Executor.java new file mode 100644 index 0000000..d084c49 --- /dev/null +++ b/src/module2_2/Executor.java @@ -0,0 +1,28 @@ +package module2_2; + +import java.util.List; + +public interface Executor { + + // Добавить таск на выполнение. Результат таска будет доступен через метод getValidResults(). + // Бросает Эксепшн если уже был вызван метод execute() + void addTask(Task task); + + // Добавить таск на выполнение и валидатор результата. Результат таска будет записан в ValidResults если validator.isValid вернет true для этого результата + // Результат таска будет записан в InvalidResults если validator.isValid вернет false для этого результата + // Бросает Эксепшн если уже был вызван метод execute() + void addTask(Task task, Validator validator); //предполагалось использовать в валидаторе + //но мое мнение - это не принципиально. + + // Выполнить все добавленые таски + void execute(); + + // Получить валидные результаты. Бросает Эксепшн если не был вызван метод execute() + List getValidResults(); + + // Получить невалидные результаты. Бросает Эксепшн если не был вызван метод execute() + List getInvalidResults(); + + // Только для теста + List> getTasks(); +} \ No newline at end of file diff --git a/src/module2_2/ExecutorImpl.java b/src/module2_2/ExecutorImpl.java new file mode 100644 index 0000000..3b76f91 --- /dev/null +++ b/src/module2_2/ExecutorImpl.java @@ -0,0 +1,94 @@ +package module2_2; + +import java.util.ArrayList; +import java.util.List; + +public class ExecutorImpl implements Executor { + private List> tasks = new ArrayList<>(); + + private ArrayList validResults = new ArrayList<>(); + private ArrayList invalidResults = new ArrayList<>(); + + boolean isExecuteActivate; + + { + tasks = new ArrayList<>(); + validResults = new ArrayList<>(); + invalidResults = new ArrayList<>(); + } + + @Override + public void addTask(Task task) { + try { + if (isExecuteActivate) { + throw new Exception("[ERROR]: Method execute() was activated!"); + } + tasks.add(task); + } catch (Exception exception) { + exception.getMessage(); + } + } + + @Override + public void addTask(Task task, Validator validator) { + try { + if (isExecuteActivate) { + throw new Exception("[ERROR]: Method execute() was activated!"); + } + task.execute(); + if (validator.isValid(task.getResult())) { + validResults.add(task.getValue()); + } else { + invalidResults.add(task.getValue()); + } + } catch (Exception exception) { + exception.getMessage(); + } + } + + @Override + public void execute() { + Validator validator = new NumberValidator(); + for (Task task : tasks) { + task.execute(); + if (validator.isValid((Number) task.getResult())) { + validResults.add(task.getValue()); + } else { + invalidResults.add(task.getValue()); + } + } + isExecuteActivate = true; + } + + @Override + public List getValidResults() { + try { + if (isExecuteActivate) { + return validResults; + } else { + throw new Exception("[ERROR]: Method execute() does not activate!"); + } + } catch (Exception exception) { + exception.getMessage(); + } + return null; + } + + @Override + public List getInvalidResults() { + try { + if (isExecuteActivate) { + return invalidResults; + } else { + throw new Exception("[ERROR]: Method execute() does not activate!"); + } + } catch (Exception exception) { + exception.getMessage(); + } + return null; + } + + public List> getTasks() { + return tasks; + } +} \ No newline at end of file diff --git a/src/module2_2/IntegerTask.java b/src/module2_2/IntegerTask.java new file mode 100644 index 0000000..62161d4 --- /dev/null +++ b/src/module2_2/IntegerTask.java @@ -0,0 +1,25 @@ +package module2_2; + +public class IntegerTask implements Task { + private Integer value; + private Integer result; + + public IntegerTask(Integer value) { + this.value = value; + } + + @Override + public void execute() { + result = value % 2; + } + + @Override + public Integer getResult() { + return result; + } + + @Override + public Integer getValue() { + return value; + } +} \ No newline at end of file diff --git a/src/module2_2/LongTask.java b/src/module2_2/LongTask.java new file mode 100644 index 0000000..05f58c2 --- /dev/null +++ b/src/module2_2/LongTask.java @@ -0,0 +1,26 @@ +package module2_2; + +public class LongTask implements Task { + private Long value; + private Long result; + + public LongTask(Long value) { + this.value = value; + } + + @Override + public void execute() { + result = value % 2; + } + + @Override + public Long getResult() { + return result; + } + + @Override + public Long getValue() { + return value; + } + +} \ No newline at end of file diff --git a/src/module2_2/NumberValidator.java b/src/module2_2/NumberValidator.java new file mode 100644 index 0000000..6229bc2 --- /dev/null +++ b/src/module2_2/NumberValidator.java @@ -0,0 +1,9 @@ +package module2_2; + + +public class NumberValidator implements Validator { + @Override + public boolean isValid(Number result) { + return result.intValue() <= 0; + } +} \ No newline at end of file diff --git a/src/module2_2/Run.java b/src/module2_2/Run.java new file mode 100644 index 0000000..3ff1908 --- /dev/null +++ b/src/module2_2/Run.java @@ -0,0 +1,31 @@ +package module2_2; + +public class Run { + public static void main(String[] args) { + Task[] intTasks = new IntegerTask[5]; + intTasks[0] = new IntegerTask(25); + intTasks[1] = new IntegerTask(32); + intTasks[2] = new IntegerTask(47); + intTasks[3] = new IntegerTask(19); + intTasks[4] = new IntegerTask(48); + + Executor numberExecutor = new ExecutorImpl<>(); + + for (Task intTask : intTasks) { + numberExecutor.addTask(intTask); + } + numberExecutor.addTask(new LongTask(10L), new NumberValidator()); + numberExecutor.addTask(new DoubleTask(39.2389)); // if number after point % 2 == 0 than doubleNumber is ValidResult + + numberExecutor.execute(); + + System.out.println("Valid results:"); + for (Number number : numberExecutor.getValidResults()) { + System.out.println(number); + } + System.out.println("Invalid results:"); + for (Number number : numberExecutor.getInvalidResults()) { + System.out.println(number); + } + } +} \ No newline at end of file diff --git a/src/module2_2/Task.java b/src/module2_2/Task.java new file mode 100644 index 0000000..a21401a --- /dev/null +++ b/src/module2_2/Task.java @@ -0,0 +1,13 @@ +package module2_2; + + +public interface Task { + + // Метода запускает таск на выполнение + void execute(); + + // Возвращает результат выполнения + T getResult(); + + T getValue(); +} \ No newline at end of file diff --git a/src/module2_2/Validator.java b/src/module2_2/Validator.java new file mode 100644 index 0000000..98aaa3b --- /dev/null +++ b/src/module2_2/Validator.java @@ -0,0 +1,6 @@ +package module2_2; + +public interface Validator { + // Валидирует переданое значение + boolean isValid(T result); +} \ No newline at end of file diff --git a/src/module2_2/build.xml b/src/module2_2/build.xml new file mode 100644 index 0000000..79caa8c --- /dev/null +++ b/src/module2_2/build.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/module2_3_1/MySemaphore.java b/src/module2_3_1/MySemaphore.java new file mode 100644 index 0000000..048f14b --- /dev/null +++ b/src/module2_3_1/MySemaphore.java @@ -0,0 +1,91 @@ +package module2_3_1; + +class MySemaphore implements Semaphore { + private volatile int permitsAvailable; + private final int ACQUIRE = 1; + private final Object lock; + private String threadName = Thread.currentThread().getName(); + + + MySemaphore(int permitsAvailable) { + this.permitsAvailable = permitsAvailable; + this.lock = new Object(); + } + + @Override + public void acquire() throws InterruptedException { + synchronized (lock) { + while (true) { + System.out.println(threadName + " checking available acquire."); + + + if (tryAcquire(ACQUIRE)) { + System.out.println(threadName + " was acquired."); + permitsAvailable--; + Thread.sleep(5000); + break; + } else { + System.out.println(threadName + " is waiting."); + Thread.currentThread().wait(); /// + System.out.println(threadName + " woke up"); + Thread.sleep(1000); + } + } + } + } + + @Override + public void acquire(int permits) throws InterruptedException { + synchronized (lock) { + while (true) { + System.out.println(threadName + " checking available acquire."); + if (tryAcquire(permits)) { + System.out.println(threadName + " was acquired."); + permitsAvailable -= permits; + Thread.sleep(5000); + break; + } else { + System.out.println(threadName + " is waiting."); + lock.wait(); + System.out.println(threadName + " woke up."); + Thread.sleep(1000); + } + } + } + } + + private boolean tryAcquire(int perm) { + return permitsAvailable - perm >= 0; + } + + @Override + public void release() { + synchronized (lock) { + if (permitsAvailable + 1 > 0) { + permitsAvailable++; + lock.notify(); + System.out.println("Threads was notified by " + threadName); + } else { + System.out.println("Threads did not notify, available permits: " + permitsAvailable); + } + } + } + + @Override + public void release(int permits) { + synchronized (lock) { + if (permitsAvailable + permits > 0) { + permitsAvailable += permits; + lock.notifyAll(); + System.out.println("All threads was notified by " + threadName); + } else { + System.out.println("Threads did not notify, available permits: " + permitsAvailable); + } + } + } + + @Override + public int getAvailablePermits() { + return permitsAvailable; + } +} \ No newline at end of file diff --git a/src/module2_3_1/Semaphore.java b/src/module2_3_1/Semaphore.java new file mode 100644 index 0000000..ec01bcd --- /dev/null +++ b/src/module2_3_1/Semaphore.java @@ -0,0 +1,25 @@ +package module2_3_1; + +public interface Semaphore { + // Запрашивает разрешение. Если есть свободное захватывает его. Если нет - приостанавливает поток до тех пор пока не появится свободное разрешение. + + public void acquire() throws InterruptedException; + + // Запрашивает переданое количество разрешений. Если есть переданое количество свободных разрешений захватывает их. + + // Если нет - приостанавливает поток до тех пор пока не появится переданое колтчество свободных разрешений. + + public void acquire(int permits) throws InterruptedException; + + // Отпускает разрешение возвращая его семафору. + + public void release(); + + // Отпускает переданое количество разрешений возварщая их семафору. + + public void release(int permits); + + // Возвращает количество свободных разрешений на данный момент. + + public int getAvailablePermits(); +} diff --git a/src/module2_3_1/SemaphoreTestDrive.java b/src/module2_3_1/SemaphoreTestDrive.java new file mode 100644 index 0000000..4bd5b6d --- /dev/null +++ b/src/module2_3_1/SemaphoreTestDrive.java @@ -0,0 +1,36 @@ +package module2_3_1; + +public class SemaphoreTestDrive { + private static MySemaphore mySemaphore; + + public static void main(String[] args) throws InterruptedException { + + int threads = 3; + mySemaphore = new MySemaphore(5); + + for (int i = 0; i < threads; i++) { + new Thread(new WorkerForParametrizedAcquire()).start(); + } + + while (WorkerForParametrizedAcquire.counter < threads) { + Thread.sleep(3000); + } + } + + private static class WorkerForParametrizedAcquire implements Runnable { + static int counter = 0; + private int acquireIsNeeded = 5; + + @Override + public void run() { + try { + mySemaphore.acquire(acquireIsNeeded); + Thread.sleep(3000); + mySemaphore.release(acquireIsNeeded); + counter++; + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} diff --git a/src/module2_3_1/build.xml b/src/module2_3_1/build.xml new file mode 100644 index 0000000..3edc153 --- /dev/null +++ b/src/module2_3_1/build.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/module2_3_2/MySquareSumImpl.java b/src/module2_3_2/MySquareSumImpl.java new file mode 100644 index 0000000..39dab5c --- /dev/null +++ b/src/module2_3_2/MySquareSumImpl.java @@ -0,0 +1,66 @@ +package module2_3_2; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.*; +import java.util.stream.IntStream; +/* +Домашнее задание к модулю 3.2 +Grade: N/A +View Grade Information. Opens a dialogue +Используя Phaser и Executors реализовать класс, который бы считал сумму квадратов элементов массива параллельно в заданном количестве потоков + +interface SquareSum { + long getSquareSum(int[] values, int numberOfThreads); +} +Идея в том, чтобы разбить массив на равные части и найти сумму квадратов в каждом кусочке в отдельном потоке параллельно. +Используя Phaser, дождаться результатов всех вычислений и сложить их, получив конечный результат. + */ + +public class MySquareSumImpl implements SquareSum { + private List> tasks = new ArrayList<>(); + private List> sums = new ArrayList<>(); + private final Phaser phaser = new Phaser(); + private long finalSum; + + @Override + public long getSquareSum(int[] values, int numberOfThreads) { + IntStream.range(0, numberOfThreads).forEach(i -> tasks.add(() -> { + long sum = 0; + + phaser.register(); + + int from = (i * values.length) / numberOfThreads; + int to = ((i + 1) * values.length) / numberOfThreads; + + for (int k = from; k < to; k++) { + sum += StrictMath.pow(values[k], 2); + } + + phaser.arriveAndAwaitAdvance(); + phaser.arriveAndDeregister(); + return sum; + })); + + ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); + + try { + sums = executorService.invokeAll(tasks); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + for (Future sum : sums) { + try { + finalSum += (long) sum.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } + executorService.shutdown(); + + return finalSum; + } +} + + diff --git a/src/module2_3_2/MySquareSumImplTest.java b/src/module2_3_2/MySquareSumImplTest.java new file mode 100644 index 0000000..7e0a92a --- /dev/null +++ b/src/module2_3_2/MySquareSumImplTest.java @@ -0,0 +1,14 @@ +package module2_3_2; + +public class MySquareSumImplTest { + public static void main(String[] args) { + int[] array1 = {9, 2, 3, 3, 4, 1, 5, 5, 8}; + int[] array2 = {6, 2, 1, 3, 9, 4, 9, 7, 9}; + + long squareSum1 = new MySquareSumImpl().getSquareSum(array1, 3); + long squareSum2 = new MySquareSumImpl().getSquareSum(array2, 4); + + System.out.println(squareSum1); + System.out.println(squareSum2); + } +} \ No newline at end of file diff --git a/src/module2_3_2/SquareSum.java b/src/module2_3_2/SquareSum.java new file mode 100644 index 0000000..dd6242f --- /dev/null +++ b/src/module2_3_2/SquareSum.java @@ -0,0 +1,6 @@ +package module2_3_2; + + +interface SquareSum { + long getSquareSum(int[] values, int numberOfThreads); +} diff --git a/src/module2_3_2/build.xml b/src/module2_3_2/build.xml new file mode 100644 index 0000000..d666b80 --- /dev/null +++ b/src/module2_3_2/build.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/module4/ex1_square/CalculateSquareTestDrive.java b/src/module4/ex1_square/CalculateSquareTestDrive.java index 0c1f678..9e19766 100644 --- a/src/module4/ex1_square/CalculateSquareTestDrive.java +++ b/src/module4/ex1_square/CalculateSquareTestDrive.java @@ -2,17 +2,19 @@ public class CalculateSquareTestDrive { public static void main(String[] args) { - CircleSquare circleSquare = new CircleSquare(); - TriangleSquare triangleSquare = new TriangleSquare(); - RectangleSquare rectangleSquare = new RectangleSquare(); - circleSquare.setRadius(6); + CircleSquare circleSquare = new CircleSquare(5); + TriangleSquare triangleSquare = new TriangleSquare(5, 5); + RectangleSquare rectangleSquare = new RectangleSquare(9, 8); + + /* circleSquare.setRadius(6); triangleSquare.setHeightOfTriangle(5); triangleSquare.setSideOfTriangle(5); rectangleSquare.setHeightOfRectangle(9); rectangleSquare.setWidthOfRectangle(8); + */ - System.out.println("Площадь треугольника = " + circleSquare.countCircleSquare() + ";"); //Triangle Square - System.out.println("Площадь прямоугольника = " + triangleSquare.countTriangleSquare() + ";"); //Rectangle Square - System.out.println("Площадь круга = " + rectangleSquare.countRectangleSquare() + ";"); //Circle Square + System.out.println("Площадь треугольника = " + triangleSquare.countTriangleSquare() + ";"); //Triangle Square + System.out.println("Площадь прямоугольника = " + rectangleSquare.countRectangleSquare() + ";"); //Rectangle Square + System.out.println("Площадь круга = " + circleSquare.countCircleSquare() + ";"); //Circle Square } } diff --git a/src/module4/ex1_square/CircleSquare.java b/src/module4/ex1_square/CircleSquare.java index 462a393..fd5db1f 100644 --- a/src/module4/ex1_square/CircleSquare.java +++ b/src/module4/ex1_square/CircleSquare.java @@ -1,19 +1,17 @@ package module4.ex1_square; -public class CircleSquare { +import java.math.BigDecimal; +import java.math.RoundingMode; - private int radius; //radius of circle +public class CircleSquare { - public int getRadius() { - return radius; - } + private double radius; //radius of circle - public void setRadius(int radius) { + public CircleSquare(double radius) { this.radius = radius; } - public int countCircleSquare() { - int circleSqure = (int) (Math.PI * radius); - return circleSqure; + public double countCircleSquare() { + return new BigDecimal(Math.PI * (radius * radius)).setScale(3, RoundingMode.UP).doubleValue(); } } diff --git a/src/module4/ex1_square/RectangleSquare.java b/src/module4/ex1_square/RectangleSquare.java index dd65761..19fd843 100644 --- a/src/module4/ex1_square/RectangleSquare.java +++ b/src/module4/ex1_square/RectangleSquare.java @@ -1,27 +1,18 @@ package module4.ex1_square; -public class RectangleSquare { - private int heightOfRectangle; - private int widthOfRectangle; +import java.math.BigDecimal; +import java.math.RoundingMode; - public int getHeightOfRectangle() { - return heightOfRectangle; - } +public class RectangleSquare { + private double heightOfRectangle; + private double widthOfRectangle; - public void setHeightOfRectangle(int heightOfRectangle) { + public RectangleSquare(double heightOfRectangle, double widthOfRectangle) { this.heightOfRectangle = heightOfRectangle; - } - - public int getWidthOfRectangle() { - return widthOfRectangle; - } - - public void setWidthOfRectangle(int widthOfRectangle) { this.widthOfRectangle = widthOfRectangle; } - public int countRectangleSquare() { - int rectangleSqure = heightOfRectangle * widthOfRectangle; - return rectangleSqure; + public double countRectangleSquare() { + return new BigDecimal((heightOfRectangle * widthOfRectangle) / 2).setScale(3, RoundingMode.UP).doubleValue(); } } diff --git a/src/module4/ex1_square/TriangleSquare.java b/src/module4/ex1_square/TriangleSquare.java index 9219a5a..6d58cf8 100644 --- a/src/module4/ex1_square/TriangleSquare.java +++ b/src/module4/ex1_square/TriangleSquare.java @@ -1,27 +1,19 @@ package module4.ex1_square; -public class TriangleSquare { - private int sideOfTriangle; - private int heightOfTriangle; //the height of a triangle lowered on the side "sideOfTriangle" - - public int getHeightOfTriangle() { - return heightOfTriangle; - } +import java.math.BigDecimal; +import java.math.RoundingMode; - public void setHeightOfTriangle(int heightOfTriangle) { - this.heightOfTriangle = heightOfTriangle; - } +public class TriangleSquare { - public int getSideOfTriangle() { - return sideOfTriangle; - } + private double sideOfTriangle; + private double heightOfTriangle; //the height of a triangle lowered on the side "sideOfTriangle" - public void setSideOfTriangle(int sideOfTriangle) { + public TriangleSquare(double sideOfTriangle, double heightOfTriangle) { this.sideOfTriangle = sideOfTriangle; + this.heightOfTriangle = heightOfTriangle; } - public int countTriangleSquare() { - int triangleSqure = (sideOfTriangle * heightOfTriangle) / 2; - return triangleSqure; + public double countTriangleSquare() { + return new BigDecimal((sideOfTriangle * heightOfTriangle) / 2).setScale(3, RoundingMode.UP).doubleValue(); } } diff --git a/src/module5/ArrMinMaxSortTestDrive.java b/src/module5/ArrMinMaxSortTestDrive.java index c93eeb6..2d6edd6 100644 --- a/src/module5/ArrMinMaxSortTestDrive.java +++ b/src/module5/ArrMinMaxSortTestDrive.java @@ -14,6 +14,11 @@ public static void main(String[] args) { System.out.println("Max Array's value is " + getMaxValue(arr)); System.out.println("Min Array's value is " + getMinValue(arr)); + + System.out.println("Sort arr using 'bubble sort':" + Arrays.toString(doBubbleSort(arr))); + } + + public static int[] doBubbleSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { @@ -21,13 +26,11 @@ public static void main(String[] args) { arr[j] = arr[j + 1]; arr[j + 1] = tmp; } - } } - System.out.println("Sort arr using 'bubble sort':" + Arrays.toString(arr)); + return arr; } - public static int getMaxValue(int[] arr) { int maxValue = arr[0]; for (int i = 0; i < arr.length; i++) { diff --git a/src/module6/Directory.java b/src/module6/Directory.java deleted file mode 100644 index 9d753d3..0000000 --- a/src/module6/Directory.java +++ /dev/null @@ -1,29 +0,0 @@ -package module6; - - -public class Directory { - private TextFile textFile; - private ImgFile imgFile; - private AudioFile audioFile; - - public Directory() { - this.textFile = new TextFile(); - textFile.setSizeOfKeeping("99 megabytes"); - this.imgFile = new ImgFile(); - imgFile.setSizeOfKeeping("919 megabytes"); - this.audioFile = new AudioFile(); - audioFile.setSizeOfKeeping("929 megabytes"); - } - - public String getTextFile() { - return textFile.getSizeOfKeeping(); - } - - public String getImgFile() { - return imgFile.getSizeOfKeeping(); - } - - public String getAudioFile() { - return audioFile.getSizeOfKeeping(); - } -} diff --git a/src/module6/File.java b/src/module6/File.java deleted file mode 100644 index 72a7d88..0000000 --- a/src/module6/File.java +++ /dev/null @@ -1,8 +0,0 @@ -package module6; - -abstract public class File { - public abstract void printFileDetails(); -} - - - diff --git a/src/module6/FileTestDrive.java b/src/module6/FileTestDrive.java deleted file mode 100644 index 145cc29..0000000 --- a/src/module6/FileTestDrive.java +++ /dev/null @@ -1,56 +0,0 @@ -package module6; - -import java.util.Scanner; - -public class FileTestDrive { - public static void main(String[] args) { - Directory directory = new Directory(); - Scanner scanner = new Scanner(System.in); - System.out.println(); - try { - System.out.println("Gues what type of file is right:"); - System.out.println("These are our variants: "); - System.out.println("AudioFile"); - System.out.println("ImgFile"); - System.out.println("TextFile"); - System.out.println("Media"); - System.out.println("Your answer"); - System.out.println(); - System.out.println("Write your answer:"); - String answer = scanner.nextLine(); - if (answer.contains("AudioFile") || answer.contains("ImgFile") || answer.contains("TextFile")) { - System.out.println("Wright answer!!!"); - } else { - throw new WrongCharException(answer); - } - } catch (WrongCharException e) { - System.out.println("Fatal Error: you'v wrote " + "\"" + e.getType() + "\"" + " and it is wrong answer so we will die!!! :)))"); - } - System.out.println(); - - File[] files = new File[3]; - files[0] = new AudioFile(); - files[1] = new TextFile(); - files[2] = new ImgFile(); - String[] arrCheckSizeOfKeeping = new String[3]; - arrCheckSizeOfKeeping[0] = directory.getAudioFile(); - arrCheckSizeOfKeeping[1] = directory.getImgFile(); - arrCheckSizeOfKeeping[2] = directory.getTextFile(); - - System.out.println("There such types of files in Directory as:"); - try { - for (int i = 0; i < files.length; i++) { - files[i].printFileDetails(); - } - } catch (Exception e) { - System.out.println(e); - } - - - System.out.println(); - System.out.println("Some others information about files:"); - System.out.println("AudioFile - max size of keeping is " + directory.getAudioFile() + ";"); - System.out.println("TextFile - max size of keeping is " + directory.getImgFile() + ";"); - System.out.println("ImgFile - max size of keeping is " + directory.getTextFile() + "."); - } -} diff --git a/src/module6/WrongCharException.java b/src/module6/WrongCharException.java deleted file mode 100644 index 7d40010..0000000 --- a/src/module6/WrongCharException.java +++ /dev/null @@ -1,17 +0,0 @@ -package module6; - -public class WrongCharException extends Exception { - private String type; - - public WrongCharException(String type) { - this.type = type; - } - - public void setType(String type) { - this.type = type; - } - - public String getType() { - return type; - } -} diff --git a/src/module6/AudioFile.java b/src/module6/ex1_aboutfile_Exception/AudioFile.java similarity index 55% rename from src/module6/AudioFile.java rename to src/module6/ex1_aboutfile_Exception/AudioFile.java index fa8f908..8bb353b 100644 --- a/src/module6/AudioFile.java +++ b/src/module6/ex1_aboutfile_Exception/AudioFile.java @@ -1,24 +1,17 @@ -package module6; +package module6.ex1_aboutfile_Exception; public class AudioFile extends File { - private String type; private String sizeOfKeeping; - AudioFile() { - this.type = "AudioFile"; + public AudioFile() { this.sizeOfKeeping = "100 megabytes"; } + // we put @Override annotation to confirm that we indeed implementing (overrding) + // parrent's method. + @Override public void printFileDetails() { - System.out.println("Type: " + getType() + "; "); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; + System.out.println("Type: " + getType() + "; sizeOfKeeping=" + sizeOfKeeping); } public void setSizeOfKeeping(String sizeOfKeeping) { diff --git a/src/module6/ex1_aboutfile_Exception/Directory.java b/src/module6/ex1_aboutfile_Exception/Directory.java new file mode 100644 index 0000000..30cc2af --- /dev/null +++ b/src/module6/ex1_aboutfile_Exception/Directory.java @@ -0,0 +1,34 @@ +package module6.ex1_aboutfile_Exception; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Directory { + // Usually directory contains just list of files + // you can deal with files (create, copy, delete), you can list directory to + // find out how many files it contains, or what files it contains. + // I removed methods like getSizeOfKeeping, because directory doesn't care + // what kinds of files it contains and how large they can be. + // Directory can be empty, so there can be no files inside. + private List files; + + public Directory() { + files = new ArrayList(); + } + + public void putFile(File file) { + files.add(file); + } + + public List listFiles() { + return Collections.unmodifiableList(files); + } + + public void printFilesDetails() { + System.out.println("There such types of files in Directory as:"); + for (File file : files) { + file.printFileDetails(); + } + } +} diff --git a/src/module6/ex1_aboutfile_Exception/File.java b/src/module6/ex1_aboutfile_Exception/File.java new file mode 100644 index 0000000..d2c5332 --- /dev/null +++ b/src/module6/ex1_aboutfile_Exception/File.java @@ -0,0 +1,22 @@ +package module6.ex1_aboutfile_Exception; + +abstract public class File { + // type is protected, so it will be available for all subclasses + protected String type; + + // the super constructor is called before subclass constructor, so type will + // be initialized when we create new TextFile() or new AudioFile or new + // ImgFile() objects + public File() { + this.type = this.getClass().getSimpleName(); + } + + public abstract void printFileDetails(); + + public String getType() { + return type; + } +} + + + diff --git a/src/module6/ex1_aboutfile_Exception/FileTestDrive.java b/src/module6/ex1_aboutfile_Exception/FileTestDrive.java new file mode 100644 index 0000000..85f41d9 --- /dev/null +++ b/src/module6/ex1_aboutfile_Exception/FileTestDrive.java @@ -0,0 +1,50 @@ +package module6.ex1_aboutfile_Exception; + +import java.util.Scanner; + +public class FileTestDrive { + public static void main(String[] args) { + // extracted logic into different methods to make it easier to read. + testConsoleReadNoExceptions(); + testDirectory(); + } + + private static void testConsoleReadNoExceptions() { + try { + readUsersAnswer(); + } catch (WrongCharException e) { + e.printStackTrace(); + } + System.out.println(); + } + + private static void readUsersAnswer() throws WrongCharException { + // this is auto-closable try-catch, it will close resources opened in + // try() + try (Scanner scanner = new Scanner(System.in);) { + System.out.println("Gues what type of file is right:"); + System.out.println("These are our variants: "); + System.out.println("AudioFile"); + System.out.println("ImgFile"); + System.out.println("TextFile"); + System.out.println("Media"); + System.out.println("Your answer"); + System.out.println(); + System.out.println("Write your answer:"); + String answer = scanner.nextLine(); + if (answer.contains("AudioFile") || answer.contains("ImgFile") || answer.contains("TextFile")) { + System.out.println("Wright answer!!!"); + } else { + throw new WrongCharException("Fatal Error: you'v wrote " + "\"" + answer + "\"" + " and it is wrong answer so we will die!!! :)))"); + } + } + } + + private static void testDirectory() { + Directory directory = new Directory(); + directory.putFile(new AudioFile()); + directory.putFile(new TextFile()); + directory.putFile(new ImgFile()); + directory.printFilesDetails(); + } +} \ No newline at end of file diff --git a/src/module6/ImgFile.java b/src/module6/ex1_aboutfile_Exception/ImgFile.java similarity index 56% rename from src/module6/ImgFile.java rename to src/module6/ex1_aboutfile_Exception/ImgFile.java index 54c3b82..76b9d38 100644 --- a/src/module6/ImgFile.java +++ b/src/module6/ex1_aboutfile_Exception/ImgFile.java @@ -1,24 +1,15 @@ -package module6; +package module6.ex1_aboutfile_Exception; public class ImgFile extends File { - String type; private String sizeOfKeeping; - ImgFile() { - this.type = "ImgFile"; + public ImgFile() { this.sizeOfKeeping = "50 megabytes"; } + @Override public void printFileDetails() { - System.out.println("Type: " + getType() + "; "); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; + System.out.println("Type: " + getType() + "; sizeOfKeeping=" + sizeOfKeeping); } public void setSizeOfKeeping(String sizeOfKeeping) { diff --git a/src/module6/TextFile.java b/src/module6/ex1_aboutfile_Exception/TextFile.java similarity index 56% rename from src/module6/TextFile.java rename to src/module6/ex1_aboutfile_Exception/TextFile.java index b791aa6..9731ec2 100644 --- a/src/module6/TextFile.java +++ b/src/module6/ex1_aboutfile_Exception/TextFile.java @@ -1,24 +1,15 @@ -package module6; +package module6.ex1_aboutfile_Exception; public class TextFile extends File { - String type; private String sizeOfKeeping; - TextFile() { - this.type = "TextFile"; + public TextFile() { this.sizeOfKeeping = "25 megabytes"; } + @Override public void printFileDetails() { - System.out.println("Type: " + getType() + "; "); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; + System.out.println("Type: " + getType() + "; sizeOfKeeping=" + sizeOfKeeping); } public void setSizeOfKeeping(String sizeOfKeeping) { diff --git a/src/module6/ex1_aboutfile_Exception/WrongCharException.java b/src/module6/ex1_aboutfile_Exception/WrongCharException.java new file mode 100644 index 0000000..636b5a9 --- /dev/null +++ b/src/module6/ex1_aboutfile_Exception/WrongCharException.java @@ -0,0 +1,25 @@ +package module6.ex1_aboutfile_Exception; + +public class WrongCharException extends Exception { + // Exception is designed to keep message and other exceptions details + // When we create new Exception's class, usually we initialize all types of + // constructor as Exception class has. + // Исключением разработан, чтобы хранить сообщение и другие детали исключения + // Когда мы создаем новый класс Исключения, обычно мы инициализируем все виды + // конструкторов которые имеет класс Исключение. + public WrongCharException(String message) { + super(message); + } + + public WrongCharException() { + super(); + } + + public WrongCharException(String message, Throwable cause) { + super(message, cause); + } + + public WrongCharException(Throwable cause) { + super(cause); + } +} diff --git a/src/module6/ex2_musicinstruments_exception/Guitar.java b/src/module6/ex2_musicinstruments_exception/Guitar.java new file mode 100644 index 0000000..b30471a --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/Guitar.java @@ -0,0 +1,9 @@ +package module6.ex2_musicinstruments_exception; + +public class Guitar extends MusicInstruments { + + @Override + public String getType() { + return "guitar"; + } +} diff --git a/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java new file mode 100644 index 0000000..a036dbe --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java @@ -0,0 +1,60 @@ +package module6.ex2_musicinstruments_exception; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MusicInstrumentTestDrive { + public static void main(String[] args) { + MusicStore musicStore = new MusicStore(); + musicStore.setGuitars(52); + musicStore.setPianos(26); + musicStore.setTrumpets(89); + + System.out.println(musicStore); + + Map order = new HashMap<>(); + order.put("guitar", 1); + order.put("piano", 6); + order.put("trumpet", 1); + + List guitarsToRemove = prepareOrder(musicStore, order); + System.out.println("removed guitars " + guitarsToRemove.size()); + List pianosToRemove = prepareOrder(musicStore, order); + System.out.println("removed pianos " + pianosToRemove.size()); + List trumpetsToRemove = prepareOrder(musicStore, order); + System.out.println("removed trumpets " + trumpetsToRemove.size()); + + System.out.println(musicStore + " after removed."); + } + + private static List prepareOrder(MusicStore musicStore, Map order) { + int numberOfGuitarsToRemove = order.get("guitar"); + int numberOfPianosToRemove = order.get("piano"); + int numberOfTrumpetsToRemove = order.get("trumpet"); + + if (musicStore.getGuitars() < numberOfGuitarsToRemove) + throw new IllegalStateException("There no such amount instruments in the store."); + if (musicStore.getPianos() < numberOfPianosToRemove) + throw new IllegalStateException("There no such amount instruments in the store."); + if (musicStore.getTrumpets() < numberOfTrumpetsToRemove) + throw new IllegalStateException("There no such amount instruments in the store."); + + musicStore.setGuitars(musicStore.getGuitars() - numberOfGuitarsToRemove); + musicStore.setPianos(musicStore.getPianos() - numberOfPianosToRemove); + musicStore.setTrumpets(musicStore.getTrumpets() - numberOfTrumpetsToRemove); + + List result = new ArrayList<>(); + for (int i = 0; i < numberOfGuitarsToRemove; i++) { + result.add(new Guitar()); + } + for (int i = 0; i < numberOfPianosToRemove; i++) { + result.add(new Piano()); + } + for (int i = 0; i < numberOfTrumpetsToRemove; i++) { + result.add(new Trumpet()); + } + return result; + } +} \ No newline at end of file diff --git a/src/module6/ex2_musicinstruments_exception/MusicInstruments.java b/src/module6/ex2_musicinstruments_exception/MusicInstruments.java new file mode 100644 index 0000000..5de0199 --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/MusicInstruments.java @@ -0,0 +1,13 @@ +package module6.ex2_musicinstruments_exception; + +abstract public class MusicInstruments { + public abstract String getType(); + + @Override + public String toString() { + return "MusicInstrument {" + getType() + "}"; + } + +} + + diff --git a/src/module6/ex2_musicinstruments_exception/MusicStore.java b/src/module6/ex2_musicinstruments_exception/MusicStore.java new file mode 100644 index 0000000..0df9436 --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/MusicStore.java @@ -0,0 +1,39 @@ +package module6.ex2_musicinstruments_exception; + +public class MusicStore { + int pianos; + int guitars; + int trumpets; + + public void setPianos(int pianos) { + this.pianos = pianos; + } + + public void setGuitars(int guitars) { + this.guitars = guitars; + } + + public void setTrumpets(int trumpets) { + this.trumpets = trumpets; + } + + public int getPianos() { + return pianos; + } + + public int getGuitars() { + return guitars; + } + + public int getTrumpets() { + return trumpets; + } + + @Override + public String toString() { + return "MusicStore contains " + "guitars=" + guitars + ", pianos=" + pianos + ", trumpets=" + trumpets; + + } +} + + diff --git a/src/module6/ex2_musicinstruments_exception/Piano.java b/src/module6/ex2_musicinstruments_exception/Piano.java new file mode 100644 index 0000000..44ed863 --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/Piano.java @@ -0,0 +1,9 @@ +package module6.ex2_musicinstruments_exception; + +public class Piano extends MusicInstruments { + + @Override + public String getType() { + return "piano"; + } +} \ No newline at end of file diff --git a/src/module6/ex2_musicinstruments_exception/Trumpet.java b/src/module6/ex2_musicinstruments_exception/Trumpet.java new file mode 100644 index 0000000..ac40a1e --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/Trumpet.java @@ -0,0 +1,9 @@ +package module6.ex2_musicinstruments_exception; + +public class Trumpet extends MusicInstruments { + + @Override + public String getType() { + return "trumpet"; + } +} \ No newline at end of file diff --git a/src/module8/Guitar.java b/src/module8/Guitar.java new file mode 100644 index 0000000..26fb20d --- /dev/null +++ b/src/module8/Guitar.java @@ -0,0 +1,24 @@ +package module8; + +public class Guitar extends MusicInstruments { + private String typeOfInstruments; + private int priceOfInstruments; + + public Guitar(String typeOfInstruments, int priceOfInstruments) { + this.typeOfInstruments = typeOfInstruments; + this.priceOfInstruments = priceOfInstruments; + } + + public int getPriceOfInstruments() { + return priceOfInstruments; + } + + public String getTypeOfInstruments() { + return typeOfInstruments; + } + + @Override + public String toString() { + return typeOfInstruments + " " + priceOfInstruments; + } +} diff --git a/src/module8/MusicInstrumentByPriceComparator.java b/src/module8/MusicInstrumentByPriceComparator.java new file mode 100644 index 0000000..3228b12 --- /dev/null +++ b/src/module8/MusicInstrumentByPriceComparator.java @@ -0,0 +1,16 @@ +package module8; + +import java.util.Comparator; + +class MusicInstrumentByPriceComparator implements Comparator { + + public int compare(MusicInstruments a, MusicInstruments b) { + if (a.getPriceOfInstruments() > b.getPriceOfInstruments()) + return 1; + else if (a.getPriceOfInstruments() < b.getPriceOfInstruments()) + return -1; + else + return 0; + } +} + diff --git a/src/module8/MusicInstrumentTestDrive.java b/src/module8/MusicInstrumentTestDrive.java new file mode 100644 index 0000000..9278c70 --- /dev/null +++ b/src/module8/MusicInstrumentTestDrive.java @@ -0,0 +1,60 @@ +package module8; +/* +Выбрать иерархию классов из ДЗ по теме OOP in Java и создать несколько коллекций объектов из данной иерархии. +Хотя бы одна коллекция должна содержать в себе объекты разных классов. +Создать класс, который печатает созданные коллекции на экран в виде таблицы. + +Колонки таблицы соответствуют полям объектов. Каждая строка в таблице соответствует объекту из коллекции. + +Создать упорядоченный список объектов из ДЗ по теме OOP in Java не прибегая к использованию Collections.sort(). +*/ + +import java.util.*; + +public class MusicInstrumentTestDrive { + public static void main(String[] args) { + ArrayList guitarList = new ArrayList<>(); + ArrayList pianoList = new ArrayList<>(); + ArrayList trumpetList = new ArrayList<>(); + MusicStore musicStore = new MusicStore(); + + System.out.println("Sort Music Instruments list:"); + makeSort(); + + System.out.println(); + musicStore.putMusicInstrument(new Guitar("Best guitar", 656)); + musicStore.putMusicInstrument(new Piano("Best piano", 56)); + musicStore.putMusicInstrument(new Trumpet("Best trumpet", 56)); + + pianoList.add(new Piano("My piano", 25)); + pianoList.add(new Piano("Your piano", 66)); + pianoList.add(new Piano("Our piano", 77)); + + guitarList.add(new Guitar("My guitar", 2)); + guitarList.add(new Guitar("Your guitar", 6)); + guitarList.add(new Guitar("Our guitar", 7)); + + trumpetList.add(new Trumpet("My trumpet", 256)); + trumpetList.add(new Trumpet("Your trumpet", 666)); + trumpetList.add(new Trumpet("Our trumpet", 776)); + + System.out.println("List of Collections"); + System.out.println("Type of instruments " + "Price of instruments"); + + guitarList.stream().forEach(instrument -> System.out.println(instrument + " ")); + pianoList.stream().forEach(instrument -> System.out.println(instrument + " ")); + trumpetList.stream().forEach(instrument -> System.out.println(instrument + " ")); + musicStore.printMusicInstrumentDetails(); + } + + public static void makeSort() { + Comparator musicInstrumentsComparator = new MusicInstrumentByPriceComparator().thenComparing(new MusicInstrumentByPriceComparator()); + + TreeSet musicInstrumentses = new TreeSet(musicInstrumentsComparator); + musicInstrumentses.add(new Piano("Jack's piano ", 56)); + musicInstrumentses.add(new Guitar("Nick's guitar ", 22)); + musicInstrumentses.add(new Trumpet("Alice's trumpet", 23)); + + musicInstrumentses.stream().forEach(instrument -> System.out.println(instrument + " ")); + } +} diff --git a/src/module8/MusicInstruments.java b/src/module8/MusicInstruments.java new file mode 100644 index 0000000..110db8a --- /dev/null +++ b/src/module8/MusicInstruments.java @@ -0,0 +1,18 @@ +package module8; + +abstract public class MusicInstruments { + protected String typeOfInstruments; + protected int priceOfInstruments; + + public int getPriceOfInstruments() { + return priceOfInstruments; + } + + public String getTypeOfInstruments() { + return typeOfInstruments; + } + + public MusicInstruments() { + this.typeOfInstruments = this.getClass().getSimpleName(); + } +} diff --git a/src/module8/MusicStore.java b/src/module8/MusicStore.java new file mode 100644 index 0000000..9504b30 --- /dev/null +++ b/src/module8/MusicStore.java @@ -0,0 +1,26 @@ +package module8; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class MusicStore { + + private List musicInstruments; + + public MusicStore() { + musicInstruments = new ArrayList(); + } + + public void putMusicInstrument(MusicInstruments musicInstrument) { + musicInstruments.add(musicInstrument); + } + + public List listMusicInstruments() { + return Collections.unmodifiableList(musicInstruments); + } + + public void printMusicInstrumentDetails() { + for (MusicInstruments musicInstrument : musicInstruments) System.out.println(musicInstrument); + } +} diff --git a/src/module8/Piano.java b/src/module8/Piano.java new file mode 100644 index 0000000..fdf1c10 --- /dev/null +++ b/src/module8/Piano.java @@ -0,0 +1,33 @@ +package module8; + +import java.util.Comparator; + +public class Piano extends MusicInstruments implements Comparable { + private String typeOfInstruments; + private int priceOfInstruments; + + public Piano(String typeOfInstruments, int priceOfInstruments) { + this.typeOfInstruments = typeOfInstruments; + this.priceOfInstruments = priceOfInstruments; + } + + public int getPriceOfInstruments() { + return priceOfInstruments; + } + + public String getTypeOfInstruments() { + return typeOfInstruments; + } + + @Override + public String toString() { + return typeOfInstruments + " " + priceOfInstruments; + } + + public int compareTo(Piano p) { + + return typeOfInstruments.compareTo(p.getTypeOfInstruments()); + } +} + + diff --git a/src/module8/Trumpet.java b/src/module8/Trumpet.java new file mode 100644 index 0000000..2a923dc --- /dev/null +++ b/src/module8/Trumpet.java @@ -0,0 +1,24 @@ +package module8; + +public class Trumpet extends MusicInstruments { + private String typeOfInstruments; + private int priceOfInstruments; + + public Trumpet(String typeOfInstruments, int priceOfInstruments) { + this.typeOfInstruments = typeOfInstruments; + this.priceOfInstruments = priceOfInstruments; + } + + public int getPriceOfInstruments() { + return priceOfInstruments; + } + + public String getTypeOfInstruments() { + return typeOfInstruments; + } + + @Override + public String toString() { + return typeOfInstruments + " " + priceOfInstruments; + } +} \ No newline at end of file diff --git a/src/module9/AudioFile.java b/src/module9/AudioFile.java new file mode 100644 index 0000000..246f70a --- /dev/null +++ b/src/module9/AudioFile.java @@ -0,0 +1,20 @@ +package module9; + +public class AudioFile extends File { + + private String typeOfFile; + + public AudioFile(String typeOfFile) { + this.typeOfFile = typeOfFile; + } + + public String getTypeOfFile() { + return typeOfFile; + } + + @Override + public String toString() { + return typeOfFile; + } + +} \ No newline at end of file diff --git a/src/module9/CezarTestDrive.java b/src/module9/CezarTestDrive.java new file mode 100644 index 0000000..af59560 --- /dev/null +++ b/src/module9/CezarTestDrive.java @@ -0,0 +1,59 @@ +package module9; + +import java.util.ArrayList; +import java.util.List; + +public class CezarTestDrive { + public static void main(String[] args) { + List files = new ArrayList<>(); + files.add(new AudioFile("Audio file")); + files.add(new TextFile("Text file")); + + System.out.println("File\'s List: " + files + "\n"); + System.out.println("Encrypt File's List: "); + System.out.println(encrypt((files.toString()), 2) + "\n"); + System.out.println("Decrypt File's List: "); + System.out.println(decrypt((encrypt((files.toString()), 2)), 2)); + } + + public static String encrypt(String str, int keyLength) { + String encrypted = ""; + for (int i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c + (keyLength % 26); + if (c > 'Z') + c = c - 26; + } else if (Character.isLowerCase(c)) { + c = c + (keyLength % 26); + + if (c > 'z') + c = c - 26; + } + encrypted = encrypted + (char) c; + } + return encrypted; + } + + public static String decrypt(String str, int keyLength) { + String decrypted = ""; + for (int i = 0; i < str.length(); i++) { + + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c - (keyLength % 26); + + if (c < 'A') + c = c + 26; + } else if (Character.isLowerCase(c)) { + c = c - (keyLength % 26); + + if (c < 'a') + c = c + 26; + } + decrypted = decrypted + (char) c; + } + return decrypted; + } +} + diff --git a/src/module9/Directory.java b/src/module9/Directory.java new file mode 100644 index 0000000..f2f735b --- /dev/null +++ b/src/module9/Directory.java @@ -0,0 +1,35 @@ +package module9; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Directory { + + + + public Directory() { + files = new ArrayList(); + } + + public void putFile(File file) { + files.add(file); + } + + public List listFiles() { + return Collections.unmodifiableList(files); + } + + public List getFiles() { + return files; + } + + @Override + public String toString() { + return "Directory{" + + "files=" + files + + '}'; + } + + private List files; +} \ No newline at end of file diff --git a/src/module9/File.java b/src/module9/File.java new file mode 100644 index 0000000..43e3283 --- /dev/null +++ b/src/module9/File.java @@ -0,0 +1,17 @@ +package module9; + +abstract public class File { + protected String typeOfFile; + + public File() { + this.typeOfFile = this.getClass().getSimpleName(); + } + + public String getTypeOfFile() { + return typeOfFile; + } +} + + + + diff --git a/src/module9/TextFile.java b/src/module9/TextFile.java new file mode 100644 index 0000000..ae97a3d --- /dev/null +++ b/src/module9/TextFile.java @@ -0,0 +1,20 @@ +package module9; + +public class TextFile extends File { + + private String typeOfFile; + + public TextFile(String typeOfFile) { + this.typeOfFile = typeOfFile; + } + + public String getTypeOfFile() { + return typeOfFile; + } + + @Override + public String toString() { + return typeOfFile; + } + +} \ No newline at end of file diff --git a/src/practice_five/BSTSearch.java b/src/practice_five/BSTSearch.java new file mode 100644 index 0000000..4aa9eca --- /dev/null +++ b/src/practice_five/BSTSearch.java @@ -0,0 +1,31 @@ +package practice_five; + +/** + * Знайти число в бінарному дереві пошуку і повернути true якщо воно присутнє, інакше повернути false. + */ +public class BSTSearch { + public boolean exist(TreeNode root, int target) { + boolean result = false; + if(root != null){ + if(root.value == target){ + result = true; + } else if(root.value > target){ + result = exist(root.left, target); + } else { + result = exist(root.right, target); + } + } + return result; + } +} + +class TreeNode { + int value; + TreeNode left, right; + + public TreeNode(int value, TreeNode left, TreeNode right) { + this.value = value; + this.left = left; + this.right = right; + } +} \ No newline at end of file diff --git a/src/practice_five/KmpSmallestPeriod.java b/src/practice_five/KmpSmallestPeriod.java new file mode 100644 index 0000000..2453d08 --- /dev/null +++ b/src/practice_five/KmpSmallestPeriod.java @@ -0,0 +1,29 @@ +package practice_five; + +/** + Найменший Період + + A character string is said to have period k if it can be formed by concatenating one or more repetitions of another string of length k. + For example, the string "abcabcabcabc" has period 3, since it is formed by 4 repetitions of the string "abc". + It also has periods 6 (two repetitions of "abcabc") and 12 (one repetition of "abcabcabcabc"). + Write a program to read a character string and determine its smallest period + Return (String) substring; + */ +public class KmpSmallestPeriod { + public String findSmalletstPeriod(String input) { + String result; + int start = 0; + int end = 1; + + while (true){ + result = input.substring(start, end); + String stringToCompare = input.substring(end, end + result.length()); + if(result.equals(stringToCompare)){ + break; + } else { + end++; + } + } + return result; + } +} diff --git a/src/practice_five/KmpSubMove.java b/src/practice_five/KmpSubMove.java new file mode 100644 index 0000000..447b86d --- /dev/null +++ b/src/practice_five/KmpSubMove.java @@ -0,0 +1,40 @@ +package practice_five; + +/** + Циклічний Зсув + + Дается строка в которой делается несколько циклических сдвигов + (под циклическим сдвигом понимается перенос последней буквы в начало) + Дается также получившаяся строка + нужно вернуть минимальное количество сдвигов(int) которым можно получить из 1-й строки итоговую + если строку получить циклическим сдвигом нельзя то вывести -1 + + Например + Дано: + abcd + cdab + + ответ: 2 + */ +public class KmpSubMove { + public int subMoveQuantity(String inputStr, String resultStr) { + int count = 0; + + StringBuilder str = new StringBuilder(inputStr); + + while (count < inputStr.length()){ + if(inputStr.equals(resultStr)){ + return count; + } else { + str.delete(0, str.length()); + str.append(inputStr.substring(inputStr.length()-1)); + str.append(inputStr.substring(0, inputStr.length() - 1)); + + inputStr = str.toString(); + count++; + } + } + + return -1; + } +} diff --git a/src/practice_four/ColorChain.java b/src/practice_four/ColorChain.java new file mode 100644 index 0000000..ddcc03d --- /dev/null +++ b/src/practice_four/ColorChain.java @@ -0,0 +1,24 @@ +package practice_four; + +/* +Условие: +Дано цепи трёх цветов: белого длиной 1 м, желтого - 2 м и красного - 3 м. Каким количеством способов можно собрать из них цепь длиной N. +Количество цепей каждого цвета считать бесконечным. +Результат задачи: ссылка на задачу, которая успешно прошла все тесты в системе Codegym, загружена как ответ на это задание. + */ +public class ColorChain { + public int count(int N) { + int[] results = new int[N + 1]; + results[0] = 1; + if (N >= 1) results[1] = 1; + if (N >= 2) results[2] = 2; + if (N >= 3) results[3] = 4; + if (N >= 4) results[4] = 7; + if (N >= 5) { + for (int i = 5; i <= N; i++) { + results[i] = results[i - 1] + results[i - 2] + results[i - 3]; + } + } + return results[N]; + } +} \ No newline at end of file diff --git a/src/practice_four/JoinCharacters.java b/src/practice_four/JoinCharacters.java new file mode 100644 index 0000000..b8f2e00 --- /dev/null +++ b/src/practice_four/JoinCharacters.java @@ -0,0 +1,14 @@ +package practice_four; + +/** + * Злиття Цифр + * З'єднати масив символів в число. + * Приклад: + * Для [ '1', '2', '3'] повернути 123 + */ +public class JoinCharacters { + public int join(char[] input) { + String s = new String(input); + return Integer.parseInt(s); + } +} \ No newline at end of file diff --git a/src/practice_four/WordNumber.java b/src/practice_four/WordNumber.java new file mode 100644 index 0000000..fa33c28 --- /dev/null +++ b/src/practice_four/WordNumber.java @@ -0,0 +1,32 @@ +package practice_four; + +import java.util.Arrays; +import java.util.List; + +/** + * Злічити Слова + *

+ * Дано рядок. Порахувати кількість слів. + * Словом вважається послідовність символів англійського алфавіту [a-zA-Z]. + *

+ * Алгоритм повинен працювати за O(N) часу, тому RegExp використовувати не можна. + */ +public class WordNumber { + public int count(String input) { + input = input.toLowerCase(); + System.out.println(input); + char[] inputsChar = input.toCharArray(); + int res = 0; + boolean word = false; + for (char c : inputsChar) { + if (c >= 'a' && c <= 'z') { + word = true; + } else if (word) { + word = false; + res++; + } + } + if (word) res++; + return res; + } +} \ No newline at end of file diff --git a/src/practice_one/FindMaxNumber.java b/src/practice_one/FindMaxNumber.java new file mode 100644 index 0000000..3cb49d5 --- /dev/null +++ b/src/practice_one/FindMaxNumber.java @@ -0,0 +1,18 @@ +package practice_one; + +/** + * Знайти максимальне число в масиві. + * Гарантується, що масив завжди не пустий. + */ +public class FindMaxNumber { + public int max(int[] input) { + + int maxNumber = input[0]; + for (int i = 0; i < input.length; i++) { + if (maxNumber < input[i]) { + maxNumber = input[i]; + } + } + return maxNumber; + } +} \ No newline at end of file diff --git a/src/practice_one/FirstOddNumber.java b/src/practice_one/FirstOddNumber.java new file mode 100644 index 0000000..71c25d9 --- /dev/null +++ b/src/practice_one/FirstOddNumber.java @@ -0,0 +1,18 @@ +package practice_one; + +/** + * Знайти перше непарне число і повернути його індекс. + * Якщо такого немає, повернути -1 + */ +public class FirstOddNumber { + public int find(int[] input) { + int result = -1; + for (int i = 0; i < input.length; i++) { + if (input[i] % 2!= 0) { + result = i; + break; + } + } + return result; + } +} \ No newline at end of file diff --git a/src/practice_one/JoinCharacters.java b/src/practice_one/JoinCharacters.java new file mode 100644 index 0000000..1c313d6 --- /dev/null +++ b/src/practice_one/JoinCharacters.java @@ -0,0 +1,13 @@ +package practice_one; + + +public class JoinCharacters { + public int join(char[] input) { + int result = 0; + for (int i = 0; i < input.length; i++) { + result = result * 10 + (input[i] - '0'); + } + return result; + } +} + diff --git a/src/practice_one/MatrixSnakeTraversal.java b/src/practice_one/MatrixSnakeTraversal.java new file mode 100644 index 0000000..3a04017 --- /dev/null +++ b/src/practice_one/MatrixSnakeTraversal.java @@ -0,0 +1,31 @@ +package practice_one; + +/** + * Обійти матрицю "змійкою" і повернути всі числа в одномірному масиві. + * Наприклад: + * Для + * [[ 1, 2, 3 ], + * [ 4, 5, 6 ], + * [ 7, 8, 9 ]] + * повернути + * [1, 4, 7, 8, 5, 2, 3, 6, 9] + */ +public class MatrixSnakeTraversal { + public int[] print(int[][] input) { + if (input.length == 0) return new int[]{}; + int[] simpleArr = new int[input.length * input[0].length]; + int index = 0; + int i = 0; + int n = 1; + for (int j = 0; j < input[0].length; j++) { + while (i >= 0 && i < input.length) { + simpleArr[index] = input[i][j]; + index++; + i += n; + } + n = -1 * n; + i += n; + } + return simpleArr; + } +} diff --git a/src/practice_one/MatrixTraversal.java b/src/practice_one/MatrixTraversal.java new file mode 100644 index 0000000..afa838c --- /dev/null +++ b/src/practice_one/MatrixTraversal.java @@ -0,0 +1,59 @@ +package practice_one; + +/*Обійти матрицю по спіралі і записати всі числа в одмірний масив. + Для матриці + [[1, 2, 3, 4], + [5, 6, 7, 8] + [9, 10, 11, 12] + [13, 14, 15, 16]] + вивести [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10] +*/ +public class MatrixTraversal { + public int[] print(int[][] input) { + + int m = input.length; + int n = input[0].length; + int[] matrix = new int[m * n]; + int x = 0; + int y = 0; + int index = 0; + while (m > 0 && n > 0) { + if (m == 1) { + for (int i = 0; i < n; i++) { + matrix[index] = input[x][y++]; + index++; + } + break; + } else if (n == 1) { + for (int i = 0; i < m; i++) { + matrix[index] = input[x++][y]; + index++; + } + break; + } + for (int i = 0; i < n - 1; i++) { + matrix[index] = input[x][y++]; + index++; + } + for (int i = 0; i < m - 1; i++) { + matrix[index] = input[x++][y]; + index++; + } + for (int i = 0; i < n - 1; i++) { + matrix[index] = input[x][y--]; + index++; + } + for (int i = 0; i < m - 1; i++) { + matrix[index] = input[x--][y]; + index++; + } + x++; + y++; + m = m - 2; + n = n - 2; + } + return matrix; + } + +} + diff --git a/src/practice_one/SumDigits.java b/src/practice_one/SumDigits.java new file mode 100644 index 0000000..7a068a9 --- /dev/null +++ b/src/practice_one/SumDigits.java @@ -0,0 +1,21 @@ +package practice_one; + +/*Обчислити суму цифр числа. + Наприклад сума цифр числа 123 дорівнює 6. +*/ +public class SumDigits { + public int sum(int number) { + int n; + int sum = 0; + if (number >= 0) { + for (n = number; n != 0; n /= 10) { + sum = sum + (n % 10); + } + } else { + for (n = number; n != 0; n /= 10) { + sum = sum - (n % 10); + } + } + return sum; + } +} diff --git a/src/practice_three/LongestStabilityPeriod.java b/src/practice_three/LongestStabilityPeriod.java new file mode 100644 index 0000000..5a680eb --- /dev/null +++ b/src/practice_three/LongestStabilityPeriod.java @@ -0,0 +1,42 @@ +package practice_three; + +/** + * Найдовший Період Стабільності + *

+ * Дано масив чисел в якому знаходяться значення ВВП за кожен місяць в мільярдах доларів США. + * Необхідно знайти найдовший період стабільності. + * Період стабільності - період часу де всі значення ВВП попарно відрізняються один від одного максимум на 1. + * Повернути кількість місяців. + */ +public class LongestStabilityPeriod { + public int count(int[] gdp) { + if (gdp.length == 0) return 0; + if (gdp.length == 1) return 1; + + int max = 0; + + for (int i = 0; i < gdp.length; i++) { + int countA = goWithDiff(gdp, i, 1); + int countB = goWithDiff(gdp, i, -1); + int count = countA > countB ? countA + 1 : countB + 1; + if (count > max) max = count; + } + + return max; + } + + private int goWithDiff(int[] gdp, int i, int diff) { + int j; + int countB = 0; + j = i + diff; + int inc = 0; + while (j >= 0 && j < gdp.length) { + if (Math.abs(gdp[j] - gdp[i]) > 1) break; + if (inc == 0) inc = gdp[j] - gdp[i]; + else if (gdp[j] - gdp[i] == -1 * inc) break; + countB++; + j += diff; + } + return countB; + } +} diff --git a/src/practice_three/RPN.java b/src/practice_three/RPN.java new file mode 100644 index 0000000..affe88d --- /dev/null +++ b/src/practice_three/RPN.java @@ -0,0 +1,57 @@ +package practice_three; +import java.util.LinkedList; + +public class RPN{ + public static void evalRPN(String expr){ + String cleanExpr = cleanExpr(expr); + LinkedList stack = new LinkedList(); + System.out.println("Input\tOperation\tStack after"); + for(String token:cleanExpr.split("\\s")){ + System.out.print(token+"\t"); + Double tokenNum = null; + try{ + tokenNum = Double.parseDouble(token); + }catch(NumberFormatException e){} + if(tokenNum != null){ + System.out.print("Push\t\t"); + stack.push(Double.parseDouble(token+"")); + }else if(token.equals("*")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(firstOperand * secondOperand); + }else if(token.equals("/")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(firstOperand / secondOperand); + }else if(token.equals("-")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(firstOperand - secondOperand); + }else if(token.equals("+")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(firstOperand + secondOperand); + }else if(token.equals("^")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(Math.pow(firstOperand, secondOperand)); + }else{//just in case + System.out.println("Error"); + return; + } + System.out.println(stack); + } + System.out.println("Final answer: " + stack.pop()); + } + + private static String cleanExpr(String expr){ + //remove all non-operators, non-whitespace, and non digit chars + return expr.replaceAll("[^\\^\\*\\+\\-\\d/\\s]", ""); + } + +} \ No newline at end of file diff --git a/src/practice_three/ReversePolishNotation.java b/src/practice_three/ReversePolishNotation.java new file mode 100644 index 0000000..b9d916f --- /dev/null +++ b/src/practice_three/ReversePolishNotation.java @@ -0,0 +1,66 @@ +package practice_three; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Stack; +import java.util.function.BiFunction; + +/** + * Дано арифметичний вираз у вигляді Польського Інверсного запису. + * Необхідно обчислити значення виразу і повернути його. + * Вираз складається лише з цілих чисел і операцій +, -, *, /. Гарантується, що результат також ціне число. + */ +public class ReversePolishNotation { + public int evaluate(String expression) { + String cleanExpr = cleanExpr(expression); + LinkedList stack = new LinkedList(); + System.out.println("Input\tOperation\tStack after"); + for(String token:cleanExpr.split("\\s")){ + System.out.print(token+"\t"); + Integer tokenNum = null; + try{ + tokenNum = Integer.parseInt(token); + }catch(NumberFormatException e){} + if(tokenNum != null){ + System.out.print("Push\t\t"); + stack.push(Integer.parseInt(token+"")); + }else if(token.equals("*")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push(firstOperand * secondOperand); + }else if(token.equals("/")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push(firstOperand / secondOperand); + }else if(token.equals("-")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push(firstOperand - secondOperand); + }else if(token.equals("+")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push(firstOperand + secondOperand); + }else if(token.equals("^")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push((int) Math.pow(firstOperand, secondOperand)); + }else{//just in case + System.out.println("Error"); + return 0; + } + System.out.println(stack); + } + System.out.println("Final answer: " + stack.pop()); + return Integer.valueOf(stack.pop()); + } + + private static String cleanExpr(String expr){ + //remove all non-operators, non-whitespace, and non digit chars + return expr.replaceAll("[^\\^\\*\\+\\-\\d/\\s]", ""); + } +} \ No newline at end of file diff --git a/src/practice_three/UnixPath.java b/src/practice_three/UnixPath.java new file mode 100644 index 0000000..951f7c4 --- /dev/null +++ b/src/practice_three/UnixPath.java @@ -0,0 +1,33 @@ +package practice_three; + +import java.util.LinkedList; + +/** + * Дано повний шлях до файла в Unix системі. + * Наприклад /home/../var/./lib//file.txt + * Необхідно повернути спрощений варіант. (/var/lib/file.txt) + */ +public class UnixPath { + public String simplify(String input) { + if (input == null || input.length() == 0) return "/"; + + LinkedList list = new LinkedList<>(); + String[] splits = input.trim().trim().split("/"); + for (String s : splits) { + if (s == null || s.length() == 0 || s.equals(".")) continue; + else if (s.equals("..")) { + if (list.size() > 0) list.pop(); + } else { + list.push(s); + } + } + if (list.isEmpty()) return "/"; + StringBuffer stringBuffer = new StringBuffer(); + while (!list.isEmpty()) { + stringBuffer.insert(0, list.pop()); + stringBuffer.insert(0, "/"); + } + return stringBuffer.toString(); + } +} + diff --git a/src/practice_two/AbcNumber.java b/src/practice_two/AbcNumber.java new file mode 100644 index 0000000..f44318a --- /dev/null +++ b/src/practice_two/AbcNumber.java @@ -0,0 +1,21 @@ +package practice_two; + +/** + * Дано рядок отриманий шляхом заміни цифр 0,1,2,...,9 певного числа на букви a,b,c,..,j. + * Необхідно повернути початкове число маючи конвертований рядок. + * Наприклад: + * Для "bcd" повернути 123 + */ +public class AbcNumber { + public int convert(String num) { + String[] alphab = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; + String[] codes = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"}; + + String strOut = num; + for (int i = 0; i < alphab.length; i++) { + strOut = strOut.replaceAll(alphab[i], codes[i]); + } + int finalResult = Integer.parseInt(strOut); + return finalResult; + } +} diff --git a/src/practice_two/AddBinary.java b/src/practice_two/AddBinary.java new file mode 100644 index 0000000..b4b7174 --- /dev/null +++ b/src/practice_two/AddBinary.java @@ -0,0 +1,38 @@ +package practice_two; + +/** + * Додайте два беззнакових числа, що передаються як рядки. + * "101" + "100" = "1001" + */ +public class AddBinary { + public String add(String a, String b) { + if (a == null || b == null) return ""; + int first = a.length() - 1; + int second = b.length() - 1; + StringBuilder sb = new StringBuilder(); + int carry = 0; + while (first >= 0 || second >= 0) { + int sum = carry; + if (first >= 0) { + sum += a.charAt(first) - '0'; + first--; + } + if (second >= 0) { + sum += b.charAt(second) - '0'; + second--; + } + carry = sum >> 1; + sum = sum & 1; + sb.append(sum == 0 ? '0' : '1'); + } + if (carry > 0) + sb.append('1'); + + sb.reverse(); + return String.valueOf(sb); + } +} + // Integer.toBinaryString(Integer.parseInt(a, 2) + Integer.parseInt(b, 2)); + + + diff --git a/src/practice_two/AddNumberBase36.java b/src/practice_two/AddNumberBase36.java new file mode 100644 index 0000000..8d16784 --- /dev/null +++ b/src/practice_two/AddNumberBase36.java @@ -0,0 +1,121 @@ +package practice_two; + +import java.util.ArrayList; + +/** + * Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. + * Повернути суму чисел, також в системі 36. + * Наприклад: + * "9" + "1" = "a" + * "z" + "1" = "10" + */ +public class AddNumberBase36 { + public final static int base = 36; + + public String add(String a, String b) { + + return intToBase36(base36ToInt(a) + base36ToInt(b)); + } + + public static int base36ToInt(String str) { + + + str = str.toUpperCase(); + + int result = 0; + double frontVal = 0; + double lastVal = 0; + int size = str.length(); + boolean started = false; + + + frontVal = char36ToInt(str.charAt(0)); + for (int i = 0; i < size; i++) { + + if (i + 1 < size && (started || frontVal > 0.0)) { + lastVal = char36ToInt(str.charAt(i + 1)); + frontVal = (frontVal + (lastVal / ((double) base))) * ((double) base); + } else if (!started) { + if (frontVal == 0.0 && i + 1 < size) { + lastVal = char36ToInt(str.charAt(i + 1)); + if (lastVal > 0.0) { + frontVal = lastVal; + started = true; + } + + } + } + + } + result = (int) Math.round(frontVal); + return result; + } + + public static String intToBase36(int n) { + String result = ""; + ArrayList list = new ArrayList(); + int frontVal = 0; + int lastVal = 0; + int val = n; + frontVal = val; + + while (val >= base) { + frontVal = val / base; + lastVal = val % base; + list.add(Character.toString(intToChar36(lastVal))); + val = frontVal; + + } + + if (frontVal > 0) + list.add(Character.toString(intToChar36(frontVal))); + + for (int i = list.size() - 1; i >= 0; i--) + result += list.get(i).toLowerCase(); + + return result; + } + + public static char intToChar36(int n) { + + char result = (char) 0; + + if (n >= 0 && n <= 9) + result = (char) (48 + n); + else if (n > 9 && n < base) { + result = (char) (65 - 10 + n); + } + return result; + } + + public static char intToChar35(int n) { + char result = (char) 0; + if (n >= 0 && n <= 9) + result = (char) (48 + n); + else if (n > 9 && n < 14) { + result = (char) (65 - 10 + n); + } else if (n > 13 && n < 36) + result = (char) (65 - 10 + n + 1); + return result; + } + + public static int char36ToInt(char c) { + + int result = 0; + if (Character.isDigit(c)) + result = (int) c - 48; + else if (Character.isAlphabetic(c)) { + if ((int) c <= 90) { + result = (int) c - (65 - 10); + } + } + return result; + } + + public static int char35ToInt(char c) { + int result = char36ToInt(c); + if (result > 13) + result--; + return result; + } +} \ No newline at end of file diff --git a/src/practice_two/AverageNumber.java b/src/practice_two/AverageNumber.java new file mode 100644 index 0000000..2bddee0 --- /dev/null +++ b/src/practice_two/AverageNumber.java @@ -0,0 +1,18 @@ +package practice_two; +/* +Знайти середнє значення двох цілих чисел. +Приклади: +average( 4, 6 ) = 5 +average( -4, -7 ) = -5 +average( -4, 7 ) = 1 + */ + +public class AverageNumber { + public static int average(int a, int b) { + long c = 2; + long averageNumberFirst = ((long) a + b) / c; + int averageNumberLast = (int) averageNumberFirst; + return averageNumberLast; + } +} + diff --git a/src/practice_two/CountBits.java b/src/practice_two/CountBits.java new file mode 100644 index 0000000..3cb343c --- /dev/null +++ b/src/practice_two/CountBits.java @@ -0,0 +1,17 @@ +package practice_two; + +/** + * Для даного числа порахувати кількість біт. + * Наприклад: + * Для числа 13 в бінарному вигляді 1101 повернути 3. + */ +public class CountBits { + public int count(int num) { + int count = 0; + while (num != 0) { + count++; + num = num & (num - 1); + } + return count; + } +} \ No newline at end of file diff --git a/src/practice_two/PositiveAverageNumber.java b/src/practice_two/PositiveAverageNumber.java new file mode 100644 index 0000000..49eb5d1 --- /dev/null +++ b/src/practice_two/PositiveAverageNumber.java @@ -0,0 +1,28 @@ +package practice_two; + +/** + * Знайти середнє арифметике двух додатніх чисел. + * Наприклад: + * average( 2, 4 ) = 3 + * average( 4, 7 ) = 5 + */ +public class PositiveAverageNumber { + public static int average(int a, int b) { + long c = 2; + long a1 = a; + long b1 = b; + long averageNumberFirst = (a1 + b1) / c; + int averageNumberLast = (int) averageNumberFirst; + return averageNumberLast; + } +} + +/* + BigInteger c = BigInteger.valueOf(2); + BigInteger a1 = BigInteger.valueOf(a); + BigInteger b1 = BigInteger.valueOf(b); + BigInteger sum = a1.add(b1); + BigInteger averageNumberFirst = sum.divide(c); + + int averageNumberLast = averageNumberFirst.intValue(); + */ \ No newline at end of file diff --git a/src/practice_two/SetZero.java b/src/practice_two/SetZero.java new file mode 100644 index 0000000..10309ca --- /dev/null +++ b/src/practice_two/SetZero.java @@ -0,0 +1,32 @@ +package practice_two; + +/** + * Дано число. Треба замінити i-й біт замінити на нуль. + * Наприклад: + * для числа 6 в бінарному вигляді 110, + * замінивши 2-й біт на нуль отримаємо 100 тобто 4. + * 1<= i <= 32 + */ +public class SetZero { + + public int set(int num, int i) { + char[] arr = new char[32]; + for (int index = 0; index < 32; index++) { + if (index == 32 - i) arr[index] = '0'; + else arr[index] = '1'; + } + String str = new String(arr); + Long mask = Long.parseLong(str, 2); + return num & mask.intValue(); + } +} + + +/* +String binaryString = Integer.toBinaryString(num); + char[] chars = binaryString.toCharArray(); + chars[i - 1] = '0'; + String stringNum = String.valueOf(chars); + int finalResult = Integer.parseInt(stringNum, 2); + return finalResult; + */ \ No newline at end of file diff --git a/src/some/Numbers.java b/src/some/Numbers.java new file mode 100644 index 0000000..3bf2f3a --- /dev/null +++ b/src/some/Numbers.java @@ -0,0 +1,22 @@ +package some; + +/** + * Создайте программу, выводящую на экран все четырёхзначные числа последовательности 1000 1003 1006 1009 1012 1015 …. + */ +public class Numbers { + public static void main(String[] args) { + + int[] arr = new int[10]; + numbers(arr); + } + + public static void numbers(int[] arr) { + + int num = 1000; + for (int i = 0; i < arr.length; i++) { + arr[i] = num; + System.out.println(arr[i]); + num = num + 3; + } + } +} diff --git a/src/some/Test.java b/src/some/Test.java new file mode 100644 index 0000000..b5d7ab0 --- /dev/null +++ b/src/some/Test.java @@ -0,0 +1,17 @@ +package some; + + +import java.util.Random; +import java.util.concurrent.*; +import java.util.stream.IntStream; + +public class Test { + public static void main(String[] args) { +new Test().test(); + } + public void test () { + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + System.out.println("Task scheduled"); + executorService.scheduleAtFixedRate(() -> System.out.println("Task executed"), 1, 1, TimeUnit.SECONDS); + } + } diff --git a/src/some/toBase36.java b/src/some/toBase36.java new file mode 100644 index 0000000..b5ae03f --- /dev/null +++ b/src/some/toBase36.java @@ -0,0 +1,257 @@ +package some; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +/** + * Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. + * Повернути суму чисел, також в системі 36. + * Наприклад: + * "9" + "1" = "a" + * "z" + "1" = "10" + */ +public class toBase36 { + public static final BigInteger C36 = BigInteger.valueOf(36); + public static void main(String[] args) { + System.out.println(new toBase36().add("zjfghfhdsdfathjjhgjhghjfjfjhjhdsrreqqklhu456hfz5", "wsfgsgds56346263fgfhghfghfhgfsrr5476hjfgdhdhg3N")); + } + public String add(String a, String b) { + BigInteger ad = toDecimal(a.toLowerCase()); + BigInteger bd = toDecimal(b.toLowerCase()); + BigInteger sum = ad.add(bd); + return fromDecimal(sum); + } + + public BigInteger toDecimal(String s){ + BigInteger result = new BigInteger("0"); + char[] chars = s.toCharArray(); + for(char c: chars){ + int diff = c>='0' && c<='9' + ? c-'0' + : c-'a'+10; + result=result.multiply(C36).add(BigInteger.valueOf(diff)); + } + return result; + } + + public String fromDecimal(BigInteger i){ + StringBuilder sb = new StringBuilder(); + + BigInteger n=i; + while(n.compareTo(BigInteger.valueOf(0))>0){ + BigInteger modBI = n.mod(C36); + int mod = modBI.intValue(); + char c = (char)(mod<=9 + ? mod+'0' + : mod+'a'-10); + sb.append(c); + n=n.divide(C36); + }; + + return sb.reverse().toString(); + } +} + + +/* + public String add(String a, String b) { + + return intToBase36(base36ToInt(a) + base36ToInt(b)); + } + + public static int base36ToInt(String str) { + + + //make sure that each case is upper + str = str.toUpperCase(); + //This function will convert a base36 string to it's int equivalent + int result = 0; + double frontVal = 0; + double lastVal = 0; + int size = str.length(); + boolean started = false; + + + frontVal = char36ToInt(str.charAt(0)); + for (int i = 0; i < size; i++) { + //TODO: log this println("frontVal = " + frontVal); + + if (i + 1 < size && (started || frontVal > 0.0)) { + lastVal = char36ToInt(str.charAt(i + 1)); + //TODO: log this println("lastVal = " + lastVal); + //should contain the temp result: + frontVal = (frontVal + (lastVal / ((double) base))) * ((double) base); + //TODO: log this println("new frontVal = " + frontVal); + } else if (!started) { + if (frontVal == 0.0 && i + 1 < size) { + lastVal = char36ToInt(str.charAt(i + 1)); + if (lastVal > 0.0) { + frontVal = lastVal; + started = true; + } + + } + } + + } + result = (int) Math.round(frontVal); + return result; + } + + public static String intToBase36(int n) {//passed test for base36! + //Converts an int value to a base36 string + String result = ""; + ArrayList list = new ArrayList(); + int frontVal = 0; + int lastVal = 0; + int val = n;//preserve input + frontVal = val; + + while (val >= base) { + + //val is greater than the base; so we need to continue loop until it is not + + frontVal = val / base;//store the front part + lastVal = val % base;//store the last part + //TODO log thisprintln("val = " + val + "\tfrontVal = " +frontVal + "\tlastVal = " + lastVal); + list.add(Character.toString(intToChar36(lastVal))); + val = frontVal; + + } + + //add last base36 digit + if (frontVal > 0) + list.add(Character.toString(intToChar36(frontVal))); + + //fill the rest of the string with 0s + // for (int i = list.size(); i < MAX_digits; i++) + // list.add("0"); + + //convert list to string, in order. + for (int i = list.size() - 1; i >= 0; i--) + result += list.get(i).toLowerCase(); + + return result; + } + + public static char intToChar36(int n) {//passed test! + //Converts the integer value to the equivalent base 36 character + char result = (char) 0; + + if (n >= 0 && n <= 9) + result = (char) (48 + n); + else if (n > 9 && n < base) { + result = (char) (65 - 10 + n); + } + return result; + } + + public static char intToChar35(int n) {//passed test! + //Same as intToChar36; however it removes the 'E' char + //Converts the integer value to the equivalent base 36 character + char result = (char) 0; + + if (n >= 0 && n <= 9) + result = (char) (48 + n); + else if (n > 9 && n < 14) { + result = (char) (65 - 10 + n); + } else if (n > 13 && n < 36) + result = (char) (65 - 10 + n + 1); + return result; + } + + public static int char36ToInt(char c) {//passed test! + //Converts a base 36 character into its equivalent value in integer + int result = 0; + if (Character.isDigit(c)) + result = (int) c - 48; + else if (Character.isAlphabetic(c)) { + //-10 because 0-9 are our 1st 10 in base36 + if ((int) c <= 90) { + result = (int) c - (65 - 10); + + } + } + return result; + } + + public static int char35ToInt(char c) {//passed test! + int result = char36ToInt(c); + if (result > 13) + result--; + return result; + + } +} +*/ + + + +/* + public static int base36ToBase10(String text) { + + String code = "0123456789abcdefghijklmnopqrstuvwxyz"; + int num = 0; + int j = text.length(); + for (int i = 0; i < j; i++) { + num += code.indexOf(text.charAt(0)) * Math.pow(code.length(), i); + text = text.substring(1); + } + return num; + } + + + public static String base10ToBase36(int num) { + String code = "0123456789abcdefghijklmnopqrstuvwxyz"; + String text = ""; + int j = (int) Math.ceil(Math.log(num) / Math.log(code.length())); + for (int i = 0; i < j; i++) { + //i goes to log base code.length() of num (using change of base formula) + text += code.charAt(num % code.length()); + num /= code.length(); + } + return text; + } +}*/ + /* public String add(String a, String b){ + return base10ToBase36(base36ToBase10(a) + base36ToBase10(b)); + } + private static String codeBase36 = "0123456789abcdefghijklmnopqrstuvwxyz"; + + //"0123456789 abcdefghij klmnopqrst uvwxyz" + //"0123456789 0123456789 0123456789 012345" + + + private static String max36=base10ToBase36(Integer.MAX_VALUE); + + public static String base10ToBase36(int inNum) { + if(inNum<0) { + throw new NumberFormatException("Value "+inNum +" to small"); + } + int num = inNum; + String text = ""; + int j = (int)Math.ceil(Math.log(num)/Math.log(codeBase36.length())); + for(int i = 0; i < j; i++){ + text = codeBase36.charAt(num%codeBase36.length())+text; + num /= codeBase36.length(); + } + return text; + } + public static int base36ToBase10(String in) { + String text = in.toLowerCase(); + if(text.compareToIgnoreCase(max36)>0) { + throw new NumberFormatException("Value "+text+" to big"); + } + + if(!text.replaceAll("(\\W)","").equalsIgnoreCase(text)){ + throw new NumberFormatException("Value "+text+" false format"); + } + int num=0; + int j = text.length(); + for(int i = 0; i < j; i++){ + num += codeBase36.indexOf(text.charAt(text.length()-1))*Math.pow(codeBase36.length(), i); + text = text.substring(0,text.length()-1); + } + return num; + }*/ diff --git a/src/test/module10/CeaserCipherTest.java b/src/test/module10/CeaserCipherTest.java new file mode 100644 index 0000000..be06bf6 --- /dev/null +++ b/src/test/module10/CeaserCipherTest.java @@ -0,0 +1,51 @@ +package test.module10; + +import com.sun.prism.shader.Texture_Color_AlphaTest_Loader; +import module10.*; +import org.junit.Assert; +import org.junit.Test; + + +public class CeaserCipherTest { + + @Test(timeout = 3000) + public void testEncrypt() throws Exception { + + final String string = "Hello Java!!!"; + final int key = 2; + + CeasarCipher ceasarCipher = new CeasarCipher(); + final String encryptString = ceasarCipher.encrypt(string, key); + + Assert.assertEquals("Jgnnq Lcxc!!!", encryptString); + } + + @Test(timeout = 3000) + public void testDeEncrypt() throws Exception { + + final String string = "Jgnnq Lcxc!!!"; + final int key = 2; + + CeasarCipher ceasarCipher = new CeasarCipher(); + final String decryptString = ceasarCipher.decrypt(string, key); + + Assert.assertEquals("Hello Java!!!", decryptString); + } + + @Test(timeout = 3000) + public void testFileUtil() throws Exception { + + FileUtil fileUtil = new FileUtil(); + try { + fileUtil.write("TextTest.txt", "Hello Sidney."); + } catch (Exception e) { + e.printStackTrace(); + } + + try { + fileUtil.read("TextTest.txt"); + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/test/module2_2/ExecutorImplTest.java b/src/test/module2_2/ExecutorImplTest.java new file mode 100644 index 0000000..f5bc2d6 --- /dev/null +++ b/src/test/module2_2/ExecutorImplTest.java @@ -0,0 +1,30 @@ +package test.module2_2; + +import module2_2.*; +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ExecutorImplTest { + + + @Test + public void testExecuteWithoutValidator() throws Exception { + ExecutorImpl executor = new ExecutorImpl<>(); + Task[] intTasks = new IntegerTask[1]; + intTasks[0] = new IntegerTask(2); + Executor numberExecutor = new ExecutorImpl<>(); + + for (Task intTask : intTasks) { + numberExecutor.addTask(intTask); + } + + numberExecutor.addTask(new LongTask(10L), new NumberValidator()); + numberExecutor.addTask(new DoubleTask(39.2389)); // if number after point % 2 == 0 than doubleNumber is ValidResult + + Assert.assertEquals(numberExecutor.getValidResults().get(1), Integer.valueOf(0)); + } + + +} \ No newline at end of file diff --git a/src/test/module4/ex1_square/CalculateSquareTest.java b/src/test/module4/ex1_square/CalculateSquareTest.java new file mode 100644 index 0000000..70e7e3c --- /dev/null +++ b/src/test/module4/ex1_square/CalculateSquareTest.java @@ -0,0 +1,41 @@ +package test.module4.ex1_square; + +import module4.ex1_square.*; + +import org.junit.Assert; +import org.junit.Test; + +public class CalculateSquareTest { + + @Test(timeout = 3000) + public void testCountCircleSquare() throws Exception { + final double radius = 5; + + CircleSquare circleSquare = new CircleSquare(radius); + final double resultCircleSquare = circleSquare.countCircleSquare(); + + Assert.assertEquals(78.54, resultCircleSquare, 0.01); + } + + @Test(timeout = 3000) + public void testCountRectangleSquare() throws Exception { + final double heightOfRectangle = 9; + final double widthOfRectangle = 8; + + RectangleSquare rectangleSquare = new RectangleSquare(heightOfRectangle, widthOfRectangle); + final double resultRectangleSquare = rectangleSquare.countRectangleSquare(); + + Assert.assertEquals(36, resultRectangleSquare, 0.01); + } + + @Test(timeout = 3000) + public void testCountTriangleSquare() throws Exception { + final double sideOfTriangle = 5; + final double heightOfTriangle = 5; + + TriangleSquare triangleSquare = new TriangleSquare(sideOfTriangle, heightOfTriangle); + final double resultTriangleSquare = triangleSquare.countTriangleSquare(); + + Assert.assertEquals(12.5, resultTriangleSquare, 0.01); + } +} diff --git a/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java b/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java new file mode 100644 index 0000000..a41923e --- /dev/null +++ b/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java @@ -0,0 +1,30 @@ +package test.module4.ex2_temperature; +import module4.ex2_temperature.*; + +import org.junit.Assert; +import org.junit.Test; + +public class ConvertsTemperatureTest { + + @Test(timeout = 3000) + public void testCelsiusToFahrenheit() throws Exception { + final double fahrenheitDegree = 709.8; + + ConvertsTemperature convertsTemperature = new ConvertsTemperature(); + convertsTemperature.setCelsiusDegree(21); + final double value = convertsTemperature.celsiusToFahrenheit(); + + Assert.assertEquals(fahrenheitDegree, value, 0.1); + } + + @Test(timeout = 3000) + public void testFahrenheitToCelsius() throws Exception { + final double celsiusDegree = 21; + + ConvertsTemperature convertsTemperature = new ConvertsTemperature(); + convertsTemperature.setFahrenheitDegree(709); + final double value = convertsTemperature.fahrenheitToCelsius(); + + Assert.assertEquals(celsiusDegree, value, 0.1); + } +} diff --git a/src/test/module4/ex3_distance/CalculateDistanceTest.java b/src/test/module4/ex3_distance/CalculateDistanceTest.java new file mode 100644 index 0000000..d9096fe --- /dev/null +++ b/src/test/module4/ex3_distance/CalculateDistanceTest.java @@ -0,0 +1,23 @@ +package test.module4.ex3_distance; +import module4.ex3_distance.*; +import org.junit.Assert; +import org.junit.Test; + +public class CalculateDistanceTest { + + @Test(timeout = 3000) + + public void testDistanceBetweenTwoPoints() { + int distanceForCheck = 4; + + CalculateDistance calculateDistance = new CalculateDistance(); + calculateDistance.setX1(5); + calculateDistance.setX2(9); + calculateDistance.setY1(8); + calculateDistance.setY2(7); + final int distance = calculateDistance.distanceBetweenTwoPoints(); + + Assert.assertEquals(distanceForCheck, distance); + } +} + diff --git a/src/test/module5/ArrMinMaxSortTest.java b/src/test/module5/ArrMinMaxSortTest.java new file mode 100644 index 0000000..5fe253e --- /dev/null +++ b/src/test/module5/ArrMinMaxSortTest.java @@ -0,0 +1,41 @@ +package test.module5; +import module5.*; + +import org.junit.Assert; +import org.junit.Test; + +public class ArrMinMaxSortTest { + + @Test(timeout = 3000) + public void testDoBubbleSort() throws Exception { + final int[] arr = {1, 2, 3, 4}; + final int[] arrToDoBubbleSort = {2, 1, 4, 3}; + + ArrMinMaxSortTestDrive arrMinMaxSortTestDrive = new ArrMinMaxSortTestDrive(); + final int[] resultDoBubbleSort = arrMinMaxSortTestDrive.doBubbleSort(arrToDoBubbleSort); + + Assert.assertArrayEquals(arr, resultDoBubbleSort); + } + @Test(timeout = 3000) + public void testGetMaxValue() throws Exception { + final int[] arr = {1, 2, 3, 4}; + final int max = 4; + + ArrMinMaxSortTestDrive arrMinMaxSortTestDrive = new ArrMinMaxSortTestDrive(); + final int resultMax = arrMinMaxSortTestDrive.getMaxValue(arr); + + Assert.assertEquals(max, resultMax); + } + + @Test(timeout = 3000) + public void testGetMinValue() throws Exception { + final int[] arr = {1, 2, 3, 4}; + final int min = 1; + + ArrMinMaxSortTestDrive arrMinMaxSortTestDrive = new ArrMinMaxSortTestDrive(); + final int resultMin = arrMinMaxSortTestDrive.getMinValue(arr); + + Assert.assertEquals(min, resultMin); + } +} + diff --git a/src/test/module9/CezarTest.java b/src/test/module9/CezarTest.java new file mode 100644 index 0000000..52d6cd1 --- /dev/null +++ b/src/test/module9/CezarTest.java @@ -0,0 +1,31 @@ +package test.module9; +import module9.*; +import org.junit.Assert; +import org.junit.Test; + +public class CezarTest { + + @Test(timeout = 3000) + public void testEncrypt() throws Exception { + + final String string = "Audio file"; + final int key = 2; + + CezarTestDrive cezarTestDrive = new CezarTestDrive(); + final String encryptString = cezarTestDrive.encrypt(string, key); + + Assert.assertEquals("Cwfkq hkng", encryptString); + } + + @Test(timeout = 3000) + public void testDeEncrypt() throws Exception { + + final String string = "Cwfkq hkng"; + final int key = 2; + + CezarTestDrive cezarTestDrive = new CezarTestDrive(); + final String decryptString = cezarTestDrive.decrypt(string, key); + + Assert.assertEquals("Audio file", decryptString); + } +} diff --git a/src/test/practice_five/BSTSearchTest.java b/src/test/practice_five/BSTSearchTest.java new file mode 100644 index 0000000..253b171 --- /dev/null +++ b/src/test/practice_five/BSTSearchTest.java @@ -0,0 +1,16 @@ +package test.practice_five; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Знайти число в бінарному дереві пошуку і повернути true якщо воно присутнє, інакше повернути false. + */ +public class BSTSearchTest { + + @Test + public void testExist() throws Exception { + + } +} \ No newline at end of file diff --git a/src/test/practice_one/FindMaxNumberTest.java b/src/test/practice_one/FindMaxNumberTest.java new file mode 100644 index 0000000..609dded --- /dev/null +++ b/src/test/practice_one/FindMaxNumberTest.java @@ -0,0 +1,18 @@ +package test.practice_one; + +import practice_one.FindMaxNumber; +import org.junit.Assert; +import org.junit.Test; + +public class FindMaxNumberTest { + + @Test + public void testMax() throws Exception { + int[] input = {-6, -2, -3}; + int expected = -2; + FindMaxNumber findMaxNumber = new FindMaxNumber(); + int extualResult = findMaxNumber.max(input); + Assert.assertEquals(expected, extualResult); + System.out.println(extualResult); + } +} \ No newline at end of file diff --git a/src/test/practice_one/FirstOddNumberTest.java b/src/test/practice_one/FirstOddNumberTest.java new file mode 100644 index 0000000..de73d39 --- /dev/null +++ b/src/test/practice_one/FirstOddNumberTest.java @@ -0,0 +1,17 @@ +package test.practice_one; + +import practice_one.FirstOddNumber; +import org.junit.Assert; +import org.junit.Test; + +public class FirstOddNumberTest { + @Test + public void testFind() throws Exception { + int[] input = {}; + int expected = -1; + FirstOddNumber firstOddNumber = new FirstOddNumber(); + int extualResult = firstOddNumber.find(input); + Assert.assertEquals(expected, extualResult); + System.out.println(extualResult); + } +} \ No newline at end of file diff --git a/src/test/practice_one/JoinCharactersTest.java b/src/test/practice_one/JoinCharactersTest.java new file mode 100644 index 0000000..12d75c0 --- /dev/null +++ b/src/test/practice_one/JoinCharactersTest.java @@ -0,0 +1,29 @@ +package test.practice_one; + +import practice_one.JoinCharacters; +import org.junit.Assert; +import org.junit.Test; + + +public class JoinCharactersTest { + JoinCharacters joinCharacters = new JoinCharacters(); + + @Test + public void testSingleElementArray() throws Exception { + char[] input = {'1'}; + int expected = 1; + + int extualResult = joinCharacters.join(input); + + Assert.assertEquals("Characters should be joind correctly for single element array.", expected, extualResult); + } + + @Test + public void testThreeElementsArray() throws Exception { + char[] input = {'1', '2', '3'}; + int expected = 123; + + int extualResult = joinCharacters.join(input); + Assert.assertEquals("Characters should be joind correctly for three elements array.", expected, extualResult); + } +} \ No newline at end of file diff --git a/src/test/practice_one/MatrixSnakeTraversalTest.java b/src/test/practice_one/MatrixSnakeTraversalTest.java new file mode 100644 index 0000000..e8fc501 --- /dev/null +++ b/src/test/practice_one/MatrixSnakeTraversalTest.java @@ -0,0 +1,26 @@ +package test.practice_one; + +import practice_one.MatrixSnakeTraversal; +import org.junit.Assert; +import org.junit.Test; + + +public class MatrixSnakeTraversalTest { + + MatrixSnakeTraversal matrixSnakeTraversal = new MatrixSnakeTraversal(); + + + @Test + public void testPrintForSquareMatrix() throws Exception { + int[][] input = {{1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}}; + + int[] expected = {1, 4, 7, 8, 5, 2, 3, 6, 9}; + int[] extualResult = matrixSnakeTraversal.print(input); + Assert.assertArrayEquals(expected, extualResult); + + } + + +} diff --git a/src/test/practice_one/MatrixTraversalTest.java b/src/test/practice_one/MatrixTraversalTest.java new file mode 100644 index 0000000..e94950f --- /dev/null +++ b/src/test/practice_one/MatrixTraversalTest.java @@ -0,0 +1,31 @@ +package test.practice_one; +/*Обійти матрицю по спіралі і записати всі числа в одмірний масив. + Для матриці + [[1, 2, 3, 4], + [5, 6, 7, 8] + [9, 10, 11, 12] + [13, 14, 15, 16]] + вивести [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10] +*/ + +import org.junit.Assert; +import org.junit.Test; +import practice_one.MatrixTraversal; + +public class MatrixTraversalTest { + + MatrixTraversal matrixTraversal = new MatrixTraversal(); + + @Test + public void testPrint() throws Exception { + int[][] input = {{1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16}}; + + int[] expected = {1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10}; + int[] extualResult = matrixTraversal.print(input); + Assert.assertArrayEquals(expected, extualResult); + } +} + diff --git a/src/test/practice_one/SumDigitsTest.java b/src/test/practice_one/SumDigitsTest.java new file mode 100644 index 0000000..d0fe01c --- /dev/null +++ b/src/test/practice_one/SumDigitsTest.java @@ -0,0 +1,17 @@ +package test.practice_one; + +import practice_one.SumDigits; +import org.junit.Assert; +import org.junit.Test; + +public class SumDigitsTest { + @Test + public void testSum() throws Exception { + int input = -256; + int expected = 13; + SumDigits sumDigits = new SumDigits(); + int extualResult = sumDigits.sum(input); + Assert.assertEquals(expected, extualResult); + System.out.println("Sum numbers in number " + input + " is " + extualResult + "."); + } +} diff --git a/src/test/practice_three/BinaryHeap.java b/src/test/practice_three/BinaryHeap.java new file mode 100644 index 0000000..a088074 --- /dev/null +++ b/src/test/practice_three/BinaryHeap.java @@ -0,0 +1,145 @@ +package test.practice_three; +import java.util.Arrays; +/** + Реалізуйте структуру даних - Бінарна Купа (Binary Heap). + Конструктор проймає один параметр size. + Методи insert(int) що працює за O(logN) і poll(), + який видаляє і повертає максимальне число з купи і також працює за O(logN). + */ +public class BinaryHeap { + private int[] heap; + private int heapSize; + + public BinaryHeap(int size){ + heap = new int[size]; + heapSize = 0; + Arrays.fill(heap, -1); + } + + public int insert(int val){ + int tmp; + int insertPoint = heapSize; + + if(this.isFull() || val < 0){ + throw new HeapException(); + } + + heap[heapSize] = val; + + for(int i = getHeapSize(); getParent(i) >= 0; i = insertPoint) { + if (val < heap[getParent(i)]) { + tmp = heap[getParent(i)]; + heap[getParent(i)] = heap[i]; + heap[i] = tmp; + insertPoint = getParent(i); + }else if(val == heap[getParent(i)]){ + throw new HeapException(); + } + else{ + insertPoint = i; + break; + } + } + heapSize++; + return insertPoint; + } + + public int poll(){ + if(this.isEmpty()){ + throw new HeapException(); + } + int result = heap[0]; + int key = heap[heapSize - 1]; + int tmp; + int insertPoint; + + heap[0] = key; + heap[heapSize - 1] = -1; + heapSize--; + + for(int i = 0; i < this.getHeapSize() - 1; i = insertPoint){ + if(key > getLeftChild(key)){ + tmp = getLeftChild(key); + heap[i] = tmp; + heap[2 * i + 1] = key; + insertPoint = 2 * i + 1; + }else if(key > getRightChild(key)){ + tmp = getRightChild(key); + heap[i] = tmp; + heap[2 * i + 2] = key; + insertPoint = 2 * i + 2; + }else{ + break; + } + } + + return result; + } + + public int peek(){ + if(this.isEmpty()){ + throw new HeapException(); + } + return heap[0]; + } + + public boolean contains(int key){ + for(int i = 0; i < this.heapSize; i++){ + if(heap[i] == key){ + return true; + } + } + return false; + } + + public boolean isEmpty(){ + if(this.heapSize == 0){ + return true; + } + return false; + } + + public boolean isFull(){ + if(this.heapSize == heap.length){ + return true; + } + return false; + } + + public int getParent(int key){ + int parent = -1; + if(key > 0){ + parent = (key - 1) / 2; + } + return parent; + } + + public int getLeftChild(int key){ + for(int i = 0; (2 * i + 1) < this.heapSize; i++){ + if(heap[i] == key){ + return heap[2 * i + 1]; + } + } + return -1; + } + + public int getRightChild(int key){ + for(int i = 0; (2 * i + 2) < this.heapSize; i++){ + if(heap[i] == key){ + return heap[2 * i + 2]; + } + } + return -1; + } + + public int getHeapSize(){ + return this.heapSize; + } + + public int[] getHeap(){ + return this.heap; + } +} + +class HeapException extends RuntimeException{ +} \ No newline at end of file diff --git a/src/test/practice_three/LongestStabilityPeriodTest.java b/src/test/practice_three/LongestStabilityPeriodTest.java new file mode 100644 index 0000000..631d1df --- /dev/null +++ b/src/test/practice_three/LongestStabilityPeriodTest.java @@ -0,0 +1,21 @@ +package test.practice_three; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** +Найдовший Період Стабільності + + Дано масив чисел в якому знаходяться значення ВВП за кожен місяць в мільярдах доларів США. + Необхідно знайти найдовший період стабільності. + Період стабільності - період часу де всі значення ВВП попарно відрізняються один від одного максимум на 1. + Повернути кількість місяців. + */ +public class LongestStabilityPeriodTest { + + @Test + public void testCount() throws Exception { + + } +} \ No newline at end of file diff --git a/src/test/practice_three/ReversePolishNotationTest.java b/src/test/practice_three/ReversePolishNotationTest.java new file mode 100644 index 0000000..8080a2f --- /dev/null +++ b/src/test/practice_three/ReversePolishNotationTest.java @@ -0,0 +1,18 @@ +package test.practice_three; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + *Дано арифметичний вираз у вигляді Польського Інверсного запису. + Необхідно обчислити значення виразу і повернути його. + Вираз складається лише з цілих чисел і операцій +, -, *, /. Гарантується, що результат також ціне число. + */ +public class ReversePolishNotationTest { + + @Test + public void testEvaluate() throws Exception { + + } +} \ No newline at end of file diff --git a/src/test/practice_two/AbcNumberTest.java b/src/test/practice_two/AbcNumberTest.java new file mode 100644 index 0000000..ca0ff18 --- /dev/null +++ b/src/test/practice_two/AbcNumberTest.java @@ -0,0 +1,23 @@ +package test.practice_two; + +import org.junit.Assert; +import org.junit.Test; +import practice_two.AbcNumber; + +/** + Дано рядок отриманий шляхом заміни цифр 0,1,2,...,9 певного числа на букви a,b,c,..,j. + Необхідно повернути початкове число маючи конвертований рядок. + Наприклад: + Для "bcd" повернути 123 + */ +public class AbcNumberTest { + + @Test + public void testConvert() throws Exception { + String input = "d"; + int expected = 123; + AbcNumber change = new AbcNumber(); + int extualResult = change.convert(input); + Assert.assertEquals(expected, extualResult); + } +} \ No newline at end of file diff --git a/src/test/practice_two/AddBinaryTest.java b/src/test/practice_two/AddBinaryTest.java new file mode 100644 index 0000000..7fa119b --- /dev/null +++ b/src/test/practice_two/AddBinaryTest.java @@ -0,0 +1,32 @@ +package test.practice_two; + +import org.junit.Assert; +import org.junit.Test; +import practice_two.AddBinary; + +/** + * Додайте два беззнакових числа, що передаються як рядки. + * "101" + "100" = "1001" + */ +public class AddBinaryTest { + @Test + public void AddBinary() throws Exception { + String inputA = "101"; + String inputB = "100"; + String expected = "1001"; + AddBinary addBinary = new AddBinary(); + String extualResult = addBinary.add(inputA, inputB); + Assert.assertEquals(expected, extualResult); + } + + @Test + public void AddBinaryLong() throws Exception { + String inputA = "10000000000000000000000000000000"; + String inputB = "10000000000000000000000000000000"; + String expected = "100000000000000000000000000000000"; + AddBinary addBinary = new AddBinary(); + String extualResult = addBinary.add(inputA, inputB); + Assert.assertEquals(expected, extualResult); + } + +} \ No newline at end of file diff --git a/src/test/practice_two/AddNumberBase36Test.java b/src/test/practice_two/AddNumberBase36Test.java new file mode 100644 index 0000000..5290113 --- /dev/null +++ b/src/test/practice_two/AddNumberBase36Test.java @@ -0,0 +1,19 @@ +package test.practice_two; + +import org.junit.Test; + +/** + * Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. + * Повернути суму чисел, також в системі 36. + * Наприклад: + * "9" + "1" = "a" + * "z" + "1" = "10" + */ +public class AddNumberBase36Test { + + @Test + public void testAdd() throws Exception { + + + } +} \ No newline at end of file diff --git a/src/test/practice_two/AverageNumberTest.java b/src/test/practice_two/AverageNumberTest.java new file mode 100644 index 0000000..aa3ac57 --- /dev/null +++ b/src/test/practice_two/AverageNumberTest.java @@ -0,0 +1,24 @@ +package test.practice_two; + +import org.junit.Assert; +import org.junit.Test; +import practice_two.AverageNumber; + +/** + Знайти середнє значення двох цілих чисел. + Приклади: + average( 4, 6 ) = 5 + average( -4, -7 ) = -5 + average( -4, 7 ) = 1 + */ +public class AverageNumberTest { + @Test + public void testAverage() throws Exception { + int inputA = 1073741824; + int inputB = 1073741824; + int expected = 1073741824; + AverageNumber averageNumber = new AverageNumber(); + int extualResult = averageNumber.average(inputA,inputB); + Assert.assertEquals(expected, extualResult); + } +} \ No newline at end of file diff --git a/src/test/practice_two/PositiveAverageNumberTest.java b/src/test/practice_two/PositiveAverageNumberTest.java new file mode 100644 index 0000000..f2cc05f --- /dev/null +++ b/src/test/practice_two/PositiveAverageNumberTest.java @@ -0,0 +1,23 @@ +package test.practice_two; + +import org.junit.Assert; +import org.junit.Test; +import practice_two.PositiveAverageNumber; + +/** + Знайти середнє арифметике двух додатніх чисел. + Наприклад: + average( 2, 4 ) = 3 + average( 4, 7 ) = 5 + */ +public class PositiveAverageNumberTest { + @Test + public void testAverage() throws Exception { + int inputA = 1073741824; + int inputB = 1073741824; + int expected = 1073741824; + PositiveAverageNumber averageNumber = new PositiveAverageNumber(); + int extualResult = averageNumber.average(inputA,inputB); + Assert.assertEquals(expected, extualResult); + } +} \ No newline at end of file diff --git a/src/test/practice_two/SetZeroTest.java b/src/test/practice_two/SetZeroTest.java new file mode 100644 index 0000000..de08118 --- /dev/null +++ b/src/test/practice_two/SetZeroTest.java @@ -0,0 +1,24 @@ +package test.practice_two; + +import org.junit.Assert; +import org.junit.Test; +import practice_two.SetZero; + +/** + Дано число. Треба замінити i-й біт замінити на нуль. + Наприклад: + для числа 6 в бінарному вигляді 110, + замінивши 2-й біт на нуль отримаємо 100 тобто 4. + 1<= i <= 32 + */ +public class SetZeroTest { + @Test + public void set() throws Exception { + int inputA = 6; + int inputB = 2; + int expected = 4; + SetZero change = new SetZero(); + int extualResult = change.set(inputA, inputB); + Assert.assertEquals(expected, extualResult); + } +} \ No newline at end of file