├── Defining Classes - Lab ├── Demo │ └── definingClasses_Demo │ │ ├── Demo.java │ │ └── Person.java └── Solutions │ ├── definingClasses_01_Intro │ ├── Car.java │ └── Main.java │ ├── definingClasses_02_Constructors │ ├── Car.java │ └── Main.java │ └── definingClasses_03_Static │ ├── BankAccount.java │ └── Main.java ├── Exam Preparation ├── BookWorm_02.java ├── SantasPresents_01.java └── cafe │ ├── Cafe.java │ ├── Employee.java │ └── Main.java ├── Functional Programming - Lab ├── Demos │ ├── DemoBiFunctions.java │ ├── DemoConsumer.java │ ├── DemoFunction.java │ ├── DemoNestedMaps.java │ ├── DemoPredicate.java │ └── DemoSupplier.java ├── Solutions │ ├── AddVAT_04.java │ ├── CountUppercaseWords_03.java │ ├── FilterByAge_05.java │ ├── FindEvensOdds_06.java │ ├── SortEvenNumbers_Functional_01.java │ ├── SortEvenNumbers_NoFunctional_01.java │ └── SumNumbers_02.java └── Theory │ └── Functional Programming - Notes.txt ├── Generics - Lab ├── arrayCreator │ ├── ArrayCreator.java │ └── Main.java ├── generics │ ├── Car.java │ ├── Demo.java │ ├── ListCar.java │ ├── RenaultCar.java │ └── SkodaCar.java ├── jar │ ├── Jar.java │ └── Main.java ├── listUtils │ ├── ListUtils.java │ └── Main.java └── scale │ ├── Main.java │ └── Scale.java ├── Iterators and Comparators - Lab ├── Demo │ ├── Demo.java │ ├── supermarket │ │ ├── Main.java │ │ └── Stand.java │ └── zoo │ │ ├── Cat.java │ │ └── Main.java └── Solutions │ ├── bookComparator_04 │ ├── Book.java │ ├── BookComparator.java │ └── Main.java │ ├── book_01 │ ├── Book.java │ └── Main.java │ ├── comparableBook_03 │ ├── Book.java │ └── Main.java │ └── library_02 │ ├── Book.java │ ├── Library.java │ └── Main.java ├── Streams, Files and Directories - Lab ├── Demos │ ├── Cube.java │ ├── DemoSerialization.java │ ├── FileDemo.java │ ├── FileInputOutputStreamDemo.java │ ├── FilesDemo.java │ └── ScannerPrintWriterDemo.java └── Solutions │ ├── CopyBytes_03.java │ ├── Cube.java │ ├── ExtractIntegers_04.java │ ├── ListFiles_07.java │ ├── ReadFile_01.java │ ├── SerializeCustomObject_09.java │ ├── SortLines_06.java │ ├── WriteEveryThirdLine_05.java │ └── WriteToFile_02.java ├── Workshop - Algorithms Introduction ├── Demo │ ├── BruteForceDemo.java │ ├── BubbleSortDemo.java │ ├── Coins.java │ ├── Demo.java │ └── FibonacciDemo.java └── Solutions │ ├── BinarySearch_07.java │ ├── MergeSort_05.java │ ├── Quicksort_06.java │ ├── RecursiveArraySum_01.java │ ├── RecursiveFactorial_02.java │ └── SumOfCoins_03.java ├── Видеа на задачи от курса.txt └── Видеа на изпитни задачи.txt /Defining Classes - Lab/Demo/definingClasses_Demo/Demo.java: -------------------------------------------------------------------------------- 1 | package definingClasses_Demo; 2 | 3 | public class Demo { 4 | public static void main(String[] args) { 5 | /*Car car = new Car(); //празен обект от клас Car 6 | 7 | //setters -> задаваме стойност на полетата 8 | car.setBrand("Skoda"); 9 | car.setModel("Karoq"); 10 | car.setHorsePower(150); 11 | 12 | //getters -> взимаме стойностите в полета 13 | System.out.println(car.getBrand()); 14 | System.out.println(car.getModel()); 15 | System.out.println(car.getHorsePower()); 16 | 17 | //default toString -> "package.class@address" 18 | System.out.println(car.toString()); 19 | 20 | 21 | //constructor use 22 | Car secondCar = new Car("Audi", "A1", 110); 23 | System.out.println(secondCar); 24 | 25 | 26 | System.out.println();*/ 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Defining Classes - Lab/Demo/definingClasses_Demo/Person.java: -------------------------------------------------------------------------------- 1 | package definingClasses_Demo; 2 | 3 | public class Person { 4 | //полета 5 | private String name; 6 | private int age; 7 | private String birthday; 8 | 9 | 10 | //методи 11 | //1. конструктор 12 | public Person(String name, int age, String birthday) { 13 | this.name = name; 14 | this.age = age; 15 | this.birthday = birthday; 16 | } 17 | 18 | //2. getters 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public int getAge() { 24 | return age; 25 | } 26 | 27 | public String getBirthday() { 28 | return birthday; 29 | } 30 | 31 | //3. setters 32 | public void setName(String name) { 33 | this.name = name; 34 | } 35 | 36 | public void setAge(int age) { 37 | this.age = age; 38 | } 39 | 40 | public void setBirthday(String birthday) { 41 | this.birthday = birthday; 42 | } 43 | 44 | @Override 45 | public int hashCode() { 46 | return 1234; 47 | } 48 | 49 | @Override 50 | public boolean equals(Object obj) { 51 | return false; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return "test"; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Defining Classes - Lab/Solutions/definingClasses_01_Intro/Car.java: -------------------------------------------------------------------------------- 1 | package definingClasses_01_Intro; 2 | 3 | class Car { 4 | //полета -> характеристики 5 | private String brand; 6 | private String model; 7 | private int horsePower; 8 | 9 | 10 | //методи -> действия 11 | 12 | //getters / accessors -> методи, които осигуряват достъп до полетата и взимат стойността в тях 13 | //1. getter на полето brand -> върна стойността, която имам срещу полето brand 14 | public String getBrand() { 15 | return this.brand; 16 | } 17 | 18 | //2. getter на полето model -> върна стойността, която имам срещу полето model 19 | public String getModel() { 20 | return this.model; 21 | } 22 | 23 | //3. getter на полето horsePower -> върна стойността, която имаме срещу полето horsePower 24 | public int getHorsePower() { 25 | return this.horsePower; 26 | } 27 | 28 | //setters / mutators -> методи, чрез които да задаваме стойност на полетата 29 | //1. setter на полето brand 30 | public void setBrand(String brand) { 31 | this.brand = brand; 32 | } 33 | 34 | //2. setter на полето model 35 | public void setModel(String model) { 36 | this.model = model; 37 | } 38 | 39 | //3. setter на полето horsePower 40 | public void setHorsePower(int horsePower) { 41 | this.horsePower = horsePower; 42 | } 43 | 44 | //вградени методи -> toString, equals, hashCode 45 | 46 | //1. toString -> представя обекта под формата на текст -> "package.class@address" 47 | @Override 48 | public String toString() { 49 | //"The car is: Chevrolet Impala - 390 HP." 50 | return String.format("The car is: %s %s - %d HP.", 51 | this.getBrand(), this.getModel(), this.getHorsePower()); 52 | } 53 | 54 | //2. equals -> метод, който сравняваме обекти 55 | 56 | //3. hashCode -> метод, който ни дава цифровата репрезентация на един обект 57 | 58 | } 59 | -------------------------------------------------------------------------------- /Defining Classes - Lab/Solutions/definingClasses_01_Intro/Main.java: -------------------------------------------------------------------------------- 1 | package definingClasses_01_Intro; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | int countCars = Integer.parseInt(scanner.nextLine()); 10 | 11 | for (int count = 1; count <= countCars; count++) { 12 | String data = scanner.nextLine(); //"{brand} {model} {hp}" 13 | String brand = data.split(" ")[0]; 14 | String model = data.split(" ")[1]; 15 | int hp = Integer.parseInt(data.split(" ")[2]); 16 | 17 | Car car = new Car(); //нов празен обект 18 | car.setBrand(brand); 19 | car.setModel(model); 20 | car.setHorsePower(hp); 21 | 22 | System.out.println(car); 23 | 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Defining Classes - Lab/Solutions/definingClasses_02_Constructors/Car.java: -------------------------------------------------------------------------------- 1 | package definingClasses_02_Constructors; 2 | 3 | class Car { 4 | //полета -> характеристики 5 | private String brand; 6 | private String model; 7 | private int horsePower; 8 | 9 | //методи -> действия 10 | //constructor -> метод, чрез който създаваме обекти 11 | 12 | //конструктор по поздразбиране / default конструктор - вграден 13 | public Car () { 14 | //празен обект 15 | //brand = null 16 | //model = null 17 | //horsePower = 0 18 | } 19 | 20 | //конструктори с параметри 21 | public Car (String brand, String model, int hp) { 22 | //нов празен обект 23 | //brand = null 24 | //model = null 25 | //horsePower = 0 26 | this(brand); 27 | this.setModel(model); 28 | this.setHorsePower(hp); 29 | } 30 | 31 | public Car (String brand) { 32 | //празен обект 33 | //brand = null 34 | //model = null 35 | //horsePower = 0 36 | this.setBrand(brand); 37 | this.setModel("unknown"); 38 | this.setHorsePower(-1); 39 | } 40 | 41 | 42 | //getters / accessors -> методи, които осигуряват достъп до полетата и взимат стойността в тях 43 | //1. getter на полето brand -> върна стойността, която имам срещу полето brand 44 | public String getBrand() { 45 | return this.brand; 46 | } 47 | 48 | //2. getter на полето model -> върна стойността, която имам срещу полето model 49 | public String getModel() { 50 | return this.model; 51 | } 52 | 53 | //3. getter на полето horsePower -> върна стойността, която имаме срещу полето horsePower 54 | public int getHorsePower() { 55 | return this.horsePower; 56 | } 57 | 58 | //setters / mutators -> методи, чрез които да задаваме стойност на полетата 59 | //1. setter на полето brand 60 | public void setBrand(String brand) { 61 | this.brand = brand; 62 | } 63 | 64 | //2. setter на полето model 65 | public void setModel(String model) { 66 | this.model = model; 67 | } 68 | 69 | //3. setter на полето horsePower 70 | public void setHorsePower(int horsePower) { 71 | this.horsePower = horsePower; 72 | } 73 | 74 | //вградени методи -> toString, equals, hashCode 75 | 76 | //1. toString -> представя обекта под формата на текст -> "package.class@address" 77 | @Override 78 | public String toString() { 79 | //"The car is: Chevrolet Impala - 390 HP." 80 | return String.format("The car is: %s %s - %d HP.", 81 | this.getBrand(), this.getModel(), this.getHorsePower()); 82 | } 83 | 84 | //2. equals -> метод, който сравняваме обекти 85 | 86 | //3. hashCode -> метод, който ни дава цифровата репрезентация на един обект 87 | 88 | } 89 | -------------------------------------------------------------------------------- /Defining Classes - Lab/Solutions/definingClasses_02_Constructors/Main.java: -------------------------------------------------------------------------------- 1 | package definingClasses_02_Constructors; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int carCount = Integer.parseInt(scanner.nextLine()); 9 | 10 | for (int i = 1; i <= carCount; i++) { 11 | String[] carParts = scanner.nextLine().split(" "); 12 | Car currentCar = new Car(); 13 | 14 | if (carParts.length == 3) { 15 | currentCar = new Car( 16 | carParts[0], carParts[1], Integer.parseInt(carParts[2])); 17 | } else { 18 | currentCar = new Car(carParts[0]); 19 | } 20 | 21 | System.out.println(currentCar.toString()); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Defining Classes - Lab/Solutions/definingClasses_03_Static/BankAccount.java: -------------------------------------------------------------------------------- 1 | package definingClasses_03_Static; 2 | 3 | class BankAccount { 4 | private static double interestRate = 0.02; 5 | private static int counter = 1; 6 | 7 | private int id; 8 | private double balance; 9 | 10 | BankAccount() { 11 | this.id = counter++; 12 | } 13 | 14 | int getId() { 15 | return this.id; 16 | } 17 | 18 | static void setInterestRate(double interestRate) { 19 | BankAccount.interestRate = interestRate; 20 | } 21 | 22 | double getInterestRate(int years) { 23 | return BankAccount.interestRate * years * this.balance; 24 | } 25 | 26 | void deposit(double amount) { 27 | this.balance += amount; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return String.format("Account ID%d, balance %.2f", this.id, this.balance); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Defining Classes - Lab/Solutions/definingClasses_03_Static/Main.java: -------------------------------------------------------------------------------- 1 | package definingClasses_03_Static; 2 | 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Scanner; 7 | 8 | public class Main { 9 | 10 | 11 | public static void main(String[] args) throws IOException { 12 | Scanner scanner = new Scanner(System.in); 13 | 14 | Map bankAccounts = new HashMap<>(); 15 | while (true) { 16 | String[] line = scanner.nextLine().split(" "); 17 | if ("end".equalsIgnoreCase(line[0])) { 18 | break; 19 | } 20 | 21 | switch (line[0]) { 22 | case "Create": 23 | createBankAccount(bankAccounts); 24 | break; 25 | case "Deposit": 26 | depositSum(Integer.parseInt(line[1]), Double.parseDouble(line[2]), bankAccounts); 27 | break; 28 | case "SetInterest": 29 | setInterest(Double.parseDouble(line[1])); 30 | break; 31 | case "GetInterest": 32 | getInterest(Integer.parseInt(line[1]), Integer.parseInt(line[2]), bankAccounts); 33 | break; 34 | } 35 | } 36 | } 37 | 38 | private static void getInterest(int id, int years, Map bankAccounts) { 39 | if (bankAccounts.containsKey(id)) { 40 | System.out.printf("%.2f%n", bankAccounts.get(id).getInterestRate(years)); 41 | } else { 42 | System.out.println("Account does not exist"); 43 | } 44 | } 45 | 46 | private static void depositSum(int id, double amount, Map bankAccounts) { 47 | if (bankAccounts.containsKey(id)) { 48 | bankAccounts.get(id).deposit(amount); 49 | System.out.printf("Deposited %.0f to ID%d%n", amount, id); 50 | } else { 51 | System.out.println("Account does not exist"); 52 | } 53 | } 54 | 55 | private static void createBankAccount(Map bankAccounts) { 56 | BankAccount ba = new BankAccount(); 57 | bankAccounts.put(ba.getId(), ba); 58 | System.out.println("Account ID" + ba.getId() + " created"); 59 | } 60 | 61 | private static void setInterest(double interest) { 62 | BankAccount.setInterestRate(interest); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Exam Preparation/BookWorm_02.java: -------------------------------------------------------------------------------- 1 | package examPreparation; 2 | 3 | import java.util.Scanner; 4 | 5 | public class BookWorm_02 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | String startText = scanner.nextLine(); //първоначалния текст 10 | StringBuilder textBuilder = new StringBuilder(startText); 11 | int size = Integer.parseInt(scanner.nextLine()); //размер на матрицата: бр. редове = бр. колоните = size 12 | 13 | String [][] matrix = new String[size][size]; 14 | fillMatrix(matrix, scanner); 15 | 16 | //намираме местоположението на играча 17 | int playerRow = -1; //на кой ред се намира играча 18 | int playerCol = -1; //на коя колона се намира играча 19 | 20 | for (int row = 0; row < size; row++) { 21 | for (int col = 0; col < size; col++) { 22 | if (matrix[row][col].equals("P")) { 23 | playerRow = row; 24 | playerCol = col; 25 | } 26 | } 27 | } 28 | 29 | 30 | String command = scanner.nextLine(); 31 | while (!command.equals("end")) { 32 | //запазвам от къде тръгвам 33 | int startRow = playerRow; //ред, от който тръгва 34 | int startCol = playerCol; //колона, от която тръгва 35 | //command = "up", "down", "left", "right" 36 | //преместване 37 | boolean isOutside = false; 38 | switch (command) { 39 | case "up": 40 | //нагоре 41 | playerRow--; 42 | //проверка дали сме отвън 43 | if (playerRow < 0) { 44 | playerRow++; 45 | isOutside = true; 46 | } 47 | break; 48 | case "down": 49 | //надолу 50 | playerRow++; 51 | //проверка дали сме отвън 52 | if (playerRow >= size) { 53 | playerRow--; 54 | isOutside = true; 55 | } 56 | break; 57 | case "left": 58 | //ляво 59 | playerCol--; 60 | //проверка дали сме отвън 61 | if (playerCol < 0) { 62 | playerCol++; 63 | isOutside = true; 64 | } 65 | break; 66 | case "right": 67 | //дясно 68 | playerCol++; 69 | //проверка дали сме отвън 70 | if (playerCol >= size) { 71 | playerCol--; 72 | isOutside = true; 73 | } 74 | break; 75 | } 76 | 77 | //извършено движение -> вътре или отвън 78 | //проверка какво има на мястото където е отишъл, само ако не е извън 79 | if (!isOutside) { 80 | String currentText = matrix[playerRow][playerCol]; //текстът, който е на мястото, на което отива 81 | if (!currentText.equals("-")) { 82 | //буква 83 | textBuilder.append(currentText); 84 | } 85 | matrix[playerRow][playerCol] = "P"; //мястото, на което се е преместил 86 | matrix[startRow][startCol] = "-"; //мястото, от което си тръгнал 87 | } else { 88 | if (textBuilder.length() > 0) { 89 | //премахвам неговата последна буква 90 | textBuilder.deleteCharAt(textBuilder.length() - 1); 91 | } 92 | } 93 | 94 | command = scanner.nextLine(); 95 | } 96 | 97 | System.out.println(textBuilder); 98 | printMatrix(matrix); 99 | } 100 | 101 | private static void printMatrix(String[][] matrix) { 102 | for (int row = 0; row < matrix.length; row++) { 103 | for (int col = 0; col < matrix.length; col++) { 104 | System.out.print(matrix[row][col]); 105 | } 106 | System.out.println(); //преминаваме на нов ред 107 | } 108 | } 109 | 110 | private static void fillMatrix(String[][] matrix, Scanner scanner) { 111 | //бр. редове = matrix.length 112 | //бр. колони = matrix.length 113 | for (int row = 0; row <= matrix.length - 1; row++) { 114 | matrix[row] = scanner.nextLine().split(""); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Exam Preparation/SantasPresents_01.java: -------------------------------------------------------------------------------- 1 | package examPreparation; 2 | 3 | import java.util.*; 4 | import java.util.stream.Collectors; 5 | 6 | public class SantasPresents_01 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | String materialsInput = scanner.nextLine(); //"10 -5 20 15 -30 10".split(" ") -> ["10", "-5", "20"...] 11 | String magicsInput = scanner.nextLine(); //"40 60 10 4 10 0" 12 | 13 | Stack materials = new Stack<>(); 14 | Arrays.stream(materialsInput.split("\\s+")) 15 | .map(Integer::parseInt).forEach(materials::push); 16 | 17 | Queue magics = Arrays.stream(magicsInput.split("\\s+")) 18 | .map(Integer::parseInt) 19 | .collect(Collectors.toCollection(ArrayDeque::new)); 20 | 21 | //играчка -> бр. произведени 22 | Map presentsMap = new TreeMap<>(); 23 | presentsMap.put("Doll", 0); 24 | presentsMap.put("Wooden train", 0); 25 | presentsMap.put("Teddy bear", 0); 26 | presentsMap.put("Bicycle", 0); 27 | 28 | while (!materials.isEmpty() && !magics.isEmpty()) { 29 | //първия материал 30 | int material = materials.peek(); 31 | int magic = magics.peek(); 32 | 33 | int totalMagic = magic * material; //получената магия 34 | 35 | //проверка за получената магия 36 | if (totalMagic == 150) { 37 | //кукла 38 | materials.pop(); 39 | magics.poll(); 40 | presentsMap.put("Doll", presentsMap.get("Doll") + 1); 41 | } else if (totalMagic == 250) { 42 | //влакче 43 | materials.pop(); 44 | magics.poll(); 45 | presentsMap.put("Wooden train", presentsMap.get("Wooden train") + 1); 46 | } else if (totalMagic == 300) { 47 | //мече 48 | materials.pop(); 49 | magics.poll(); 50 | presentsMap.put("Teddy bear", presentsMap.get("Teddy bear") + 1); 51 | } else if (totalMagic == 400) { 52 | //колело 53 | materials.pop(); 54 | magics.poll(); 55 | presentsMap.put("Bicycle", presentsMap.get("Bicycle") + 1); 56 | } else if (totalMagic < 0) { 57 | int sum = material + magic; 58 | materials.pop(); 59 | magics.poll(); 60 | materials.push(sum); 61 | } else if (totalMagic > 0) { 62 | magics.poll(); 63 | materials.push(materials.pop() + 15); 64 | } else { 65 | if (magic == 0) { 66 | magics.poll(); 67 | } 68 | if(material == 0) { 69 | materials.pop(); 70 | } 71 | } 72 | } 73 | 74 | //проверка дали сме произвели нужните подаръци 75 | //1. кукла и влакче 76 | //2. мече и колело 77 | boolean isDollAndTrain = presentsMap.get("Doll") > 0 && presentsMap.get("Wooden train") > 0; 78 | boolean isBearAndBicycle = presentsMap.get("Teddy bear") > 0 && presentsMap.get("Bicycle") > 0; 79 | if (isDollAndTrain || isBearAndBicycle) { 80 | //справили сме се с изработката 81 | System.out.println("The presents are crafted! Merry Christmas!"); 82 | } else { 83 | //не сме се справили с изработката 84 | System.out.println("No presents this Christmas!"); 85 | } 86 | 87 | //останалите материали 88 | if (!materials.isEmpty()) { 89 | System.out.print("Materials left: "); 90 | //[3, 4, 5] 91 | Collections.reverse(materials); 92 | System.out.println(materials.toString().replace("[", "").replace("]", "")); 93 | } 94 | 95 | //останалите магии 96 | if (!magics.isEmpty()) { 97 | System.out.print("Magic left: "); 98 | System.out.println(magics.toString().replace("[", "").replace("]", "")); 99 | } 100 | 101 | //отпечатваме: играчка: брой > 0 102 | for (Map.Entry entry : presentsMap.entrySet()) { 103 | //entry 104 | //key: играчка 105 | //value: бройка 106 | if (entry.getValue() > 0) { 107 | System.out.println(entry.getKey() + ": " + entry.getValue()); 108 | } 109 | } 110 | 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Exam Preparation/cafe/Cafe.java: -------------------------------------------------------------------------------- 1 | package cafe; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | 7 | public class Cafe { 8 | //полета -> характеристики 9 | private String name; 10 | private int capacity; 11 | private List employees; 12 | 13 | //методи -> поведение 14 | //конструктор 15 | 16 | public Cafe(String name, int capacity) { 17 | //нов празен обект 18 | this.name = name; 19 | this.capacity = capacity; 20 | this.employees = new ArrayList<>(); 21 | } 22 | 23 | public void addEmployee(Employee employee) { 24 | //мога да добавям ако текущия брой < капацитета 25 | //не мога да добавям текущия брой >= капацитета 26 | if (this.employees.size() < this.capacity) { 27 | this.employees.add(employee); 28 | } 29 | } 30 | 31 | public boolean removeEmployee(String name) { 32 | for (Employee employee : this.employees) { 33 | if (employee.getName().equals(name)) { 34 | this.employees.remove(employee); 35 | return true; 36 | } 37 | } 38 | //преминали сме през всички служители и не сме намерили служител с даденото име 39 | return false; 40 | } 41 | 42 | public Employee getOldestEmployee() { 43 | //1 начин 44 | return this.employees.stream().max(Comparator.comparingInt(Employee::getAge)).get(); 45 | 46 | //2 начин 47 | /*Employee oldestEmployee = new Employee("", 0, ""); //най-възрастния служител 48 | for (Employee employee : this.employees) { 49 | if (employee.getAge() > oldestEmployee.getAge()) { 50 | oldestEmployee = employee; 51 | } 52 | } 53 | return oldestEmployee;*/ 54 | } 55 | 56 | public Employee getEmployee(String name) { 57 | for (Employee employee : this.employees) { 58 | if (employee.getName().equals(name)) { 59 | return employee; 60 | } 61 | } 62 | 63 | //преминали през всички служители и не сме намерили служител с даденото име 64 | return null; 65 | } 66 | 67 | public int getCount() { 68 | return this.employees.size(); 69 | } 70 | 71 | public String report() { 72 | StringBuilder stringBuilder = new StringBuilder(); 73 | stringBuilder.append("Employees working at Cafe " + this.name + ":").append(System.lineSeparator()); 74 | this.employees.forEach(e -> stringBuilder.append(e.toString()).append(System.lineSeparator())); 75 | return stringBuilder.toString(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Exam Preparation/cafe/Employee.java: -------------------------------------------------------------------------------- 1 | package cafe; 2 | 3 | public class Employee { 4 | //полета -> характеристики 5 | private String name; 6 | private int age; 7 | private String country; 8 | 9 | //методи 10 | //конструктор -> метод, чрез който създаваме обекти от класа 11 | //ALT + INSERT 12 | public Employee(String name, int age, String country) { 13 | //нов празен обект 14 | this.name = name; 15 | this.age = age; 16 | this.country = country; 17 | } 18 | 19 | //Getters & Setters 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public void setName(String name) { 25 | this.name = name; 26 | } 27 | 28 | public int getAge() { 29 | return age; 30 | } 31 | 32 | public void setAge(int age) { 33 | this.age = age; 34 | } 35 | 36 | public String getCountry() { 37 | return country; 38 | } 39 | 40 | public void setCountry(String country) { 41 | this.country = country; 42 | } 43 | 44 | //toString -> представя всеки обект от класа под формата на текст 45 | @Override 46 | public String toString() { 47 | //"Employee: {name}, {age} from {country}" 48 | return String.format("Employee: %s, %d from %s", this.name, this.age, this.country); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Exam Preparation/cafe/Main.java: -------------------------------------------------------------------------------- 1 | package cafe; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | //Initialize the repository 7 | Cafe cafe = new Cafe("Costa", 15); 8 | //Initialize entity 9 | Employee employee = new Employee("Alexander", 30, "Bulgaria"); 10 | //Print Employee 11 | System.out.println(employee); // Employee: Alexander, 30 from Bulgaria 12 | 13 | //Add Employee 14 | cafe.addEmployee(employee); 15 | 16 | //Remove Employee 17 | System.out.println(cafe.removeEmployee("Employee")); //false 18 | 19 | Employee secondEmployee = new Employee("Sara", 24, "UK"); 20 | Employee thirdEmployee = new Employee("Anna", 22, "Germany"); 21 | 22 | //Add Employee 23 | cafe.addEmployee(secondEmployee); 24 | cafe.addEmployee(thirdEmployee); 25 | 26 | Employee oldestEmployee = cafe.getOldestEmployee(); 27 | Employee employeeStephen = cafe.getEmployee("Sara"); 28 | System.out.println(oldestEmployee); // Employee: Alexander, 30 from Bulgaria System.out.println(employeeStephen); //Employee: Sara, 24 from UK 29 | 30 | System.out.println(cafe.getCount()); // 3 31 | System.out.println(cafe.removeEmployee("Anna")); // true 32 | 33 | System.out.println(cafe.report()); 34 | //Employees working at Cafe Costa: 35 | //Employee: Alexander, 30 from Bulgaria 36 | //Employee: Sara, 24 from UK 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Demos/DemoBiFunctions.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.function.BiConsumer; 4 | import java.util.function.BiFunction; 5 | import java.util.function.BiPredicate; 6 | 7 | public class DemoBiFunctions { 8 | public static void main(String[] args) { 9 | //BiFunction<приема1, приема2, връща> apply 10 | BiFunction sumTwoNumbers = (firstNumber, secondNumber) -> firstNumber + secondNumber; 11 | int sum = sumTwoNumbers.apply(5, 6); 12 | System.out.println(sum); 13 | 14 | //BiConsumer <приема1, приема2> void accept 15 | BiConsumer printData = (name, age) -> System.out.println("I am " + name + ". I am " + age + " years old."); 16 | printData.accept("Desislava", 25); 17 | 18 | //BiPredicate <приема1, приема2> връща true/false test 19 | BiPredicate divisible = (firstNumber, secondNumber) -> firstNumber % secondNumber == 0; 20 | System.out.println(divisible.test(45, 5)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Demos/DemoConsumer.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.function.Consumer; 4 | 5 | public class DemoConsumer { 6 | public static void main(String[] args) { 7 | //Consumer<приема> -> void -> accept 8 | Consumer print = text -> { 9 | text += "Test"; 10 | System.out.println(text + "!"); 11 | System.out.println(text + "?"); 12 | System.out.println(text + "."); 13 | }; 14 | 15 | print.accept("Today is Tuesday"); 16 | } 17 | 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Demos/DemoFunction.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.function.Function; 7 | 8 | public class DemoFunction { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | //Function <приема, връщаме> -> apply 13 | 14 | Function, Integer> sum = list -> { 15 | int sumNumbers = 0; 16 | for (int number : list) { 17 | sumNumbers += number; 18 | } 19 | 20 | return sumNumbers; 21 | }; 22 | 23 | List numbers = Arrays.asList(4, 5, 6, 7, 8); 24 | System.out.println(sum.apply(numbers)); 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Demos/DemoNestedMaps.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.*; 4 | 5 | public class DemoNestedMaps { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //име ученик -> учебен предмет -> лист с оценките 10 | Map>> map = new HashMap<>(); 11 | 12 | Map> aleksGradesMap = new HashMap<>(); //учебен предмет -> списък с оценките 13 | aleksGradesMap.put("BG", Arrays.asList(6, 5, 3, 2)); 14 | aleksGradesMap.put("Math", Arrays.asList(4, 3, 4, 6)); 15 | aleksGradesMap.put("Physics", Arrays.asList(6, 2, 6, 2)); 16 | aleksGradesMap.put("History", Arrays.asList(4, 5,4, 5)); 17 | map.put("Aleksandar", aleksGradesMap); 18 | 19 | map.get("Aleksandar").put("Geography", Arrays.asList(6, 6, 6, 6)); 20 | map.get("Aleksandar").remove("BG"); 21 | 22 | for (Map.Entry>> entry : map.entrySet()) { 23 | //entry 24 | //key -> име на ученика 25 | //value -> мап с предмет : списък с оценки 26 | String studentName = entry.getKey(); 27 | Map> gradesMap = entry.getValue(); 28 | 29 | System.out.println(studentName + " has the following grades:"); 30 | //предмет : ср. аритметично 31 | for (Map.Entry> entrySubject : gradesMap.entrySet()) { 32 | //entrySubject 33 | //key -> име на предмета 34 | //value -> list с оценки 35 | String subjectName = entrySubject.getKey(); 36 | double average = entrySubject.getValue().stream().mapToDouble(d -> d).average().orElse(0.0); 37 | System.out.println(subjectName + ": " + average); 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Demos/DemoPredicate.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.function.Predicate; 6 | 7 | public class DemoPredicate { 8 | public static void main(String[] args) { 9 | //Predicate връща true / false test 10 | Predicate isEven = number -> number % 2 == 0; 11 | 12 | List numbers = Arrays.asList(3, 4, 5, 6, 7, 8, 9); 13 | numbers.stream().filter(isEven); 14 | //true -> елементът остава в списъка 15 | //false -> елементът се премахва от списъка 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Demos/DemoSupplier.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.Random; 4 | import java.util.Scanner; 5 | import java.util.function.Supplier; 6 | 7 | public class DemoSupplier { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | //Supplier<връща> не приема нищо 11 | Supplier random = () -> new Random().nextInt(51); 12 | System.out.println(random.get()); 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Solutions/AddVAT_04.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.function.Consumer; 7 | import java.util.function.Function; 8 | import java.util.stream.Collectors; 9 | 10 | public class AddVAT_04 { 11 | public static void main(String[] args) { 12 | Scanner scanner = new Scanner(System.in); 13 | 14 | //1. входни данни: списък с дробни числа 15 | List prices = Arrays.stream(scanner.nextLine() 16 | .split(", ")) 17 | .map(Double::parseDouble) 18 | .collect(Collectors.toList()); 19 | 20 | //цена -> върна цена + 20% 21 | Function addVAT = price -> price * 1.2; 22 | //цена с ДДС -> отпечатвам 23 | Consumer printFormatPrice = price -> System.out.printf("%.2f%n", price); 24 | 25 | System.out.println("Prices with VAT:"); 26 | for (double price : prices) { 27 | double priceWithVAT = addVAT.apply(price); //цена след добавено ДДС 28 | printFormatPrice.accept(priceWithVAT); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Solutions/CountUppercaseWords_03.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | import java.util.function.Consumer; 8 | import java.util.function.Predicate; 9 | import java.util.stream.Collectors; 10 | 11 | public class CountUppercaseWords_03 { 12 | public static void main(String[] args) { 13 | Scanner scanner = new Scanner(System.in); 14 | 15 | //1. входни данни 16 | String input = scanner.nextLine(); 17 | List words = Arrays.stream(input.split("\\s+")).collect(Collectors.toList()); //лист със всички думи в текста 18 | 19 | //дума -> true (ако започва с главна буква) / false (ако не започва с главна буква) 20 | Predicate isUppercase = word -> Character.isUpperCase(word.charAt(0)); 21 | words = words.stream().filter(isUppercase).collect(Collectors.toList()); 22 | 23 | //words -> имаме само думи, които започват с главна буква 24 | System.out.println(words.size()); 25 | System.out.println(String.join("\n", words)); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Solutions/FilterByAge_05.java: -------------------------------------------------------------------------------- 1 | package com.softuni; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | import java.util.function.BiPredicate; 7 | import java.util.function.Consumer; 8 | 9 | public class FilterByAge_05 { 10 | public static void main(String[] args) { 11 | 12 | Scanner scanner = new Scanner(System.in); 13 | Map people = new LinkedHashMap<>(); 14 | 15 | int peopleCount = Integer.parseInt(scanner.nextLine()); 16 | for (int i = 0; i < peopleCount; i++) { 17 | String[] personData = scanner.nextLine().split(", "); 18 | String personName = personData[0]; 19 | int personAge = Integer.parseInt(personData[1]); 20 | people.put(personName, personAge); 21 | } 22 | 23 | String comparison = scanner.nextLine(); 24 | int ageLimit = Integer.parseInt(scanner.nextLine()); 25 | String printType = scanner.nextLine(); 26 | 27 | //филтрира според възрастов лимит 28 | //Predicate 29 | //BiPredicate 30 | BiPredicate filterPredicate; 31 | if (comparison.equals("younger")) { 32 | filterPredicate = (personAge, age) -> personAge <= age; 33 | } else { 34 | filterPredicate = (personAge, age) -> personAge >= age; 35 | } 36 | 37 | //принтира според шаблона 38 | //Consumer 39 | Consumer> printConsumer; 40 | if(printType.equals("age")){ 41 | printConsumer = person -> System.out.println(person.getValue()); 42 | } else if(printType.equals("name")){ 43 | printConsumer = person -> System.out.println(person.getKey()); 44 | } else { 45 | printConsumer = person -> System.out.printf("%s - %d%n", person.getKey(), person.getValue()); 46 | } 47 | 48 | people.entrySet() 49 | .stream() 50 | .filter(person -> filterPredicate.test(person.getValue(), ageLimit)) 51 | .forEach(printConsumer); 52 | 53 | 54 | } 55 | } -------------------------------------------------------------------------------- /Functional Programming - Lab/Solutions/FindEvensOdds_06.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | import java.util.Arrays; 3 | import java.util.Scanner; 4 | import java.util.function.Consumer; 5 | import java.util.function.Predicate; 6 | public class FindEvensOdds_06 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | int[] bounds = Arrays.stream(scanner.nextLine().split("\\s+")).mapToInt(Integer::parseInt).toArray(); 11 | String condition = scanner.nextLine(); 12 | 13 | Predicate isEven = n -> n % 2 == 0; 14 | printNumbers(bounds, isEven, condition); 15 | 16 | } 17 | 18 | private static void printNumbers(int[] bounds, Predicate isEven, String condition) { 19 | int lowerBound = bounds[0]; 20 | int upperBound = bounds[1]; 21 | 22 | if (condition.equals("odd")) { 23 | for (int i = lowerBound; i <= upperBound; i++) { 24 | if (!isEven.test(i)) { 25 | System.out.print(i + " "); 26 | } 27 | } 28 | } else { 29 | for (int i = lowerBound; i <= upperBound; i++) { 30 | if (isEven.test(i)) { 31 | System.out.print(i + " "); 32 | } 33 | } 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Solutions/SortEvenNumbers_Functional_01.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.*; 4 | import java.util.stream.Collectors; 5 | 6 | public class SortEvenNumbers_Functional_01 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | //1. входни данни само четните числа -> "4, 2, 1, 3, 5, 7, 1, 4, 2, 12" 10 | List numbers = Arrays.stream(scanner.nextLine() //"4, 2, 1, 3, 5, 7, 1, 4, 2, 12" 11 | .split(", ")) //["4", "2", "1", "3", "5", "7", "2", "4", "2", "12"] 12 | .map(Integer::parseInt) //[4, 2, 1, 3, 5, 7, 2, 4, 2, 12] 13 | .filter(n -> n % 2 == 0) //[4, 2, 2, 4, 2, 12] 14 | .collect(Collectors.toList()); //{4, 2, 2, 4, 2, 12} 15 | 16 | //2. принтирам само четните числа 17 | //System.out.println(String.join(", ", numbers.toString() .replace("[","") .replace("]",""))); 18 | printListWithComa(numbers); 19 | //3. сортираме в нарастващ ред 20 | Collections.sort(numbers); 21 | //4. принтираме отново само четните числа 22 | //System.out.println(String.join(", ", numbers.toString().replace("[","").replace("]",""))); 23 | printListWithComa(numbers); 24 | } 25 | 26 | private static void printListWithComa(List numbers) { 27 | //{4, 2, 2, 4, 2, 12} 28 | List numbersAsText = new ArrayList<>(); 29 | for (int number : numbers) { 30 | //4 -> "4" 31 | numbersAsText.add(String.valueOf(number)); 32 | } 33 | //{"4", "2", "2", "4", "2", "12"} 34 | System.out.println(String.join(", ", numbersAsText)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Solutions/SortEvenNumbers_NoFunctional_01.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | 8 | public class SortEvenNumbers_NoFunctional_01 { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | //1. входни данни -> "4, 2, 1, 3, 5, 7, 1, 4, 2, 12" 12 | String input = scanner.nextLine(); //"4, 2, 1, 3, 5, 7, 1, 4, 2, 12" 13 | String[] splittedInput = input.split(", "); //["4", "2", "1", "3", "5", "7", "2", "4", "2", "12"] 14 | 15 | List numbers = new ArrayList<>(); 16 | for (String text : splittedInput) { 17 | numbers.add(Integer.parseInt(text)); 18 | } 19 | 20 | //2. принтирам само четните числа 21 | printOnlyEvenNumbers(numbers); 22 | 23 | //3. сортираме в нарастващ ред 24 | Collections.sort(numbers); 25 | 26 | 27 | //4. принтираме отново само четните числа 28 | System.out.println(); 29 | printOnlyEvenNumbers(numbers); 30 | } 31 | 32 | private static void printOnlyEvenNumbers(List numbers) { 33 | for (int number : numbers) { 34 | if (number % 2 == 0) { 35 | System.out.print(number + " "); 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Solutions/SumNumbers_02.java: -------------------------------------------------------------------------------- 1 | package FunctionalProgramming; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.function.Function; 7 | import java.util.stream.Collectors; 8 | 9 | public class SumNumbers_02 { 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | //1. входни данни: "4, 2, 1, 3, 5, 7, 1, 4, 2, 12" 13 | List numbers = Arrays.stream(scanner.nextLine().split(", ")) 14 | .map(Integer::parseInt) 15 | .collect(Collectors.toList()); 16 | 17 | //2. брой на числата във въведения списък 18 | int countNumbers = numbers.size(); //брой на елементите в списъка 19 | 20 | //3. сума на числата в списъка 21 | //лист -> сума от числата 22 | Function, Integer> sumElementsInList = list -> { 23 | int sum = 0; //сумата на числата в списъка 24 | for (int number : list) { 25 | sum += number; 26 | } 27 | 28 | return sum; 29 | }; 30 | int sumNumbers = sumElementsInList.apply(numbers); //сума на числата в списъка 31 | 32 | //4. принтираме резултатите 33 | System.out.println("Count = " + countNumbers); 34 | System.out.println("Sum = " + sumNumbers); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Functional Programming - Lab/Theory/Functional Programming - Notes.txt: -------------------------------------------------------------------------------- 1 | Function<приема, връща> -> apply 2 | Consumer<приема> -> void -> accept 3 | Supplier<връща> -> get 4 | Predicate<приема> -> връща true / false -> test 5 | BiFunction<приема1, приема2, връща> -> apply 6 | BiConsumer<приема1, приема2> -> void -> accept 7 | BiPredicate<приема1, приема2> -> връща true / false -> test -------------------------------------------------------------------------------- /Generics - Lab/arrayCreator/ArrayCreator.java: -------------------------------------------------------------------------------- 1 | package arrayCreator; 2 | import java.lang.reflect.Array; 3 | public class ArrayCreator { 4 | 5 | public static T[] create(int length, T item) { 6 | T[] array = (T[]) new Object[length]; 7 | for (int i = 0; i < length; i++) { 8 | array[i] = item; 9 | } 10 | return array; 11 | } 12 | public static T[] create(Class tClass, int length, T item) { 13 | T[] array = (T[]) Array.newInstance(tClass, length); 14 | for (int i = 0; i < array.length; i++) { 15 | array[i] = item; 16 | } 17 | return array; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Generics - Lab/arrayCreator/Main.java: -------------------------------------------------------------------------------- 1 | package arrayCreator; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | Integer[] integers = ArrayCreator.create(Integer.class, 10, 0); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Generics - Lab/generics/Car.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class Car { 4 | private String brand; 5 | private String owner; 6 | private int hp; 7 | 8 | 9 | public void drive () { 10 | System.out.println("Drive"); 11 | } 12 | 13 | public void refuel () { 14 | System.out.println("Refuel"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Generics - Lab/generics/Demo.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | public class Demo { 9 | public static void main(String[] args) { 10 | SkodaCar skoda = new SkodaCar(); 11 | 12 | 13 | skoda.driveSkoda(); //собствен метод 14 | skoda.drive(); //наследен метод 15 | 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Generics - Lab/generics/ListCar.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class ListCar { 4 | private T[] parents; 5 | 6 | public ListCar(T parent) { 7 | this.parents = (T[]) new Object[4]; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Generics - Lab/generics/RenaultCar.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class RenaultCar extends Car { 4 | } 5 | -------------------------------------------------------------------------------- /Generics - Lab/generics/SkodaCar.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class SkodaCar extends Car { 4 | //наследени полета 5 | //brand 6 | //owner 7 | //hp 8 | 9 | 10 | //наследени методи 11 | //drive 12 | //refuel 13 | 14 | public void driveSkoda () { 15 | System.out.println("Drive Skoda"); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Generics - Lab/jar/Jar.java: -------------------------------------------------------------------------------- 1 | package jar; 2 | 3 | import java.util.ArrayDeque; 4 | 5 | public class Jar { 6 | private ArrayDeque stack; 7 | //мястото, в което съхраняваме данните 8 | 9 | public Jar() { 10 | //нов буркан 11 | this.stack = new ArrayDeque<>(); 12 | } 13 | public void add (T element) { 14 | this.stack.push(element); 15 | } 16 | 17 | public T remove() { 18 | return this.stack.pop(); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Generics - Lab/jar/Main.java: -------------------------------------------------------------------------------- 1 | package jar; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | 6 | 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Generics - Lab/listUtils/ListUtils.java: -------------------------------------------------------------------------------- 1 | package listUtils; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | 6 | public class ListUtils { 7 | public static > T getMin(List list) { 8 | if (list.isEmpty()) { 9 | throw new IllegalArgumentException(); 10 | } 11 | return Collections.min(list); 12 | } 13 | 14 | public static > T getMax(List list) { 15 | if (list.isEmpty()) { 16 | throw new IllegalArgumentException("List is empty!"); 17 | } 18 | return Collections.max(list); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Generics - Lab/listUtils/Main.java: -------------------------------------------------------------------------------- 1 | package listUtils; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Main { 7 | public static void main(String[] args) { 8 | List numbers = Arrays.asList(); 9 | System.out.println(ListUtils.getMax(numbers)); 10 | System.out.println(ListUtils.getMin(numbers)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Generics - Lab/scale/Main.java: -------------------------------------------------------------------------------- 1 | package scale; 2 | 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | Scale scale = new Scale<>(5, 9); 7 | System.out.println(scale.getHeavier()); 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Generics - Lab/scale/Scale.java: -------------------------------------------------------------------------------- 1 | package scale; 2 | 3 | public class Scale> { 4 | private T left; 5 | private T right; 6 | 7 | public Scale(T left, T right) { 8 | //нова везна 9 | this.left = left; 10 | this.right = right; 11 | } 12 | 13 | public T getHeavier() { 14 | //el1.compareTo(el2) 15 | //result: 1, 0, -1 16 | //result = 0 -> el1 == el2 17 | //result = 1 -> el1 > el2 18 | //result = -1 -> el1 < el2 19 | if (this.left.compareTo(this.right) > 0){ 20 | return this.left; 21 | } 22 | 23 | if (this.left.compareTo(this.right) < 0) { 24 | return this.right; 25 | } 26 | 27 | return null; //равни стойности 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Demo/Demo.java: -------------------------------------------------------------------------------- 1 | import java.sql.SQLOutput; 2 | import java.util.*; 3 | 4 | public class Main { 5 | public static void main(String... args) { 6 | 7 | //интерфейс: 8 | //1. дефинира поведение 9 | //2. подобно на клас, в който имаме методи без имплементация 10 | //3. не се инстанцира 11 | 12 | 13 | //Iterable -> може да се обхожда 14 | //Iterator -> инструмента, който обхожда 15 | //Comparable -> то може да се сравнява чрез метода compareTo 16 | //Comparator -> инструмент, чрез който можем да сравняваме 17 | 18 | List numbers = new ArrayList<>(Arrays.asList(2, 5, 4, 7, 1)); 19 | 20 | Collections.sort(numbers); //числата да са подредени в нарастващ ред 21 | //sort 22 | //5 и 4 23 | //1. сравнява -> comparator -> < 0; == 0; > 0 24 | //2. проверка резултат от сравнение 25 | //< 0 -> второто > първото -> не променя местата 26 | // == 0 -> първото == второто -> не променя местата 27 | // > 0 -> първото > второто -> сменя местата на двата елемента 28 | 29 | } 30 | 31 | public static void printNames (String company, String... numbers) { 32 | //1. само един var args в метод 33 | //2. var args последни като параметър 34 | 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Demo/supermarket/Main.java: -------------------------------------------------------------------------------- 1 | package supermarket; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | public class Main { 8 | public static void main(String[] args) { 9 | List fruits = new ArrayList<>(); 10 | fruits.add("Apple"); 11 | fruits.add("Banana"); 12 | fruits.add("Orange"); 13 | fruits.add("Cherry"); 14 | 15 | Stand stand = new Stand(); 16 | stand.setFruits(fruits); 17 | //{"Apple", "Banana", "Orange", "Cherry"} 18 | 19 | Iterator shopAssistant = stand.iterator(); 20 | 21 | while (shopAssistant.hasNext()) { 22 | System.out.println(shopAssistant.next()); 23 | } 24 | 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Demo/supermarket/Stand.java: -------------------------------------------------------------------------------- 1 | package supermarket; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | public class Stand implements Iterable { 8 | private List fruits; 9 | 10 | public Stand() { 11 | //нов празен щанд 12 | this.fruits = new ArrayList<>(); 13 | } 14 | 15 | public void setFruits(List fruits) { 16 | this.fruits = fruits; 17 | } 18 | 19 | @Override 20 | public Iterator iterator() { 21 | return new ShopAssistant(); 22 | } 23 | 24 | //ITERATOR -> инструментът, който обхожда чрез методите hasNext, next 25 | private class ShopAssistant implements Iterator { 26 | //iterator -> инструментът, който ще обхожда 27 | private int index = 0; 28 | 29 | @Override 30 | public boolean hasNext() { 31 | return index < fruits.size(); 32 | } 33 | 34 | @Override 35 | public String next() { 36 | return fruits.get(index++); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Demo/zoo/Cat.java: -------------------------------------------------------------------------------- 1 | package zoo; 2 | 3 | import java.util.Iterator; 4 | 5 | public class Cat implements Comparable { 6 | private String name; 7 | private int age; 8 | private int weight; 9 | 10 | public Cat(String name, int age, int weight) { 11 | this.name = name; 12 | this.age = age; 13 | this.weight = weight; 14 | } 15 | 16 | @Override 17 | //cat1.compareTo(cat2) 18 | public int compareTo(Cat cat2) { 19 | //0 -> ако двете котки са с еднаква възраст 20 | //> 0 -> първата е по-възрастна от втората 21 | // < 0 -> втората е по- възрастна от първата 22 | if (this.age == cat2.age) { 23 | return 0; 24 | } else if (this.age > cat2.age) { 25 | return 1; 26 | } else { 27 | return 0; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Demo/zoo/Main.java: -------------------------------------------------------------------------------- 1 | package zoo; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | Cat cat1 = new Cat("Nikolay", 12, 7500); 6 | Cat cat2 = new Cat("Sami", 3, 3400); 7 | 8 | System.out.println(cat1.compareTo(cat2)); 9 | //0 -> котките са с еднаква възраст 10 | //1 -> Николай е по-стар 11 | //-1 -> Сами е по-стар 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/bookComparator_04/Book.java: -------------------------------------------------------------------------------- 1 | package bookComparison; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class Book { 8 | //полета 9 | private String title; //заглавие 10 | private int year; //година на издаване 11 | private List authors; //списък с авторите 12 | 13 | //методи 14 | //конструктор 15 | public Book (String title, int year, String... authors) { 16 | //нова празна книга 17 | this.title = title; 18 | this.year = year; 19 | //[автори] -> {автори} 20 | this.authors = new ArrayList<>(Arrays.asList(authors)); 21 | } 22 | 23 | //getters and setters 24 | 25 | public String getTitle() { 26 | return title; 27 | } 28 | 29 | public void setTitle(String title) { 30 | this.title = title; 31 | } 32 | 33 | public int getYear() { 34 | return year; 35 | } 36 | 37 | public void setYear(int year) { 38 | this.year = year; 39 | } 40 | 41 | public List getAuthors() { 42 | return authors; 43 | } 44 | 45 | public void setAuthors(List authors) { 46 | this.authors = authors; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/bookComparator_04/BookComparator.java: -------------------------------------------------------------------------------- 1 | package bookComparison; 2 | 3 | import java.util.Comparator; 4 | 5 | public class BookComparator implements Comparator { 6 | //comparator -> инструмент за сравнение 7 | @Override 8 | public int compare(Book firstBook, Book secondBook) { 9 | int result = firstBook.getTitle().compareTo(secondBook.getTitle()); 10 | //< 0 11 | // == 0 12 | // > 0 13 | if (result == 0) { 14 | //двете книги имат еднакво заглавие 15 | return Integer.compare(firstBook.getYear(), secondBook.getYear()); 16 | //< 0 -> first < second 17 | //== 0 -> first == second 18 | // > 0 -> first > second 19 | } 20 | return result; 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/bookComparator_04/Main.java: -------------------------------------------------------------------------------- 1 | package bookComparison; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Main { 7 | public static void main(String[] args) { 8 | Book bookOne = new Book("Animal Farm", 2003, "George Orwell"); 9 | Book bookThree = new Book("The Documents in the Case", 2002); 10 | Book bookTwo = new Book("The Documents in the Case", 1930, "Dorothy Sayers", "Robert"); 11 | 12 | List books = new ArrayList<>(); 13 | books.add(bookOne); 14 | books.add(bookTwo); 15 | books.add(bookThree); 16 | 17 | books.sort(new BookComparator()); 18 | 19 | for (Book book: books) { 20 | System.out.println(book.getTitle() + book.getYear()); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/book_01/Book.java: -------------------------------------------------------------------------------- 1 | package book; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class Book { 8 | //полета 9 | private String title; //заглавие 10 | private int year; //година на издаване 11 | private List authors; //списък с авторите 12 | 13 | //методи 14 | //конструктор 15 | public Book (String title, int year, String... authors) { 16 | //нова празна книга 17 | this.title = title; 18 | this.year = year; 19 | //[автори] -> {автори} 20 | this.authors = new ArrayList<>(Arrays.asList(authors)); 21 | } 22 | 23 | 24 | //getters and setters 25 | 26 | public String getTitle() { 27 | return title; 28 | } 29 | 30 | public void setTitle(String title) { 31 | this.title = title; 32 | } 33 | 34 | public int getYear() { 35 | return year; 36 | } 37 | 38 | public void setYear(int year) { 39 | this.year = year; 40 | } 41 | 42 | public List getAuthors() { 43 | return authors; 44 | } 45 | 46 | public void setAuthors(List authors) { 47 | this.authors = authors; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/book_01/Main.java: -------------------------------------------------------------------------------- 1 | package book; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Main { 7 | public static void main(String[] args) { 8 | //конструктор: заглавие, година, автори.... (0 или повече) 9 | Book bookOne = new Book("Animal Farm", 2003, "George Orwell"); 10 | Book bookThree = new Book("The Documents in the Case", 2002); 11 | Book bookTwo = new Book("The Documents in the Case", 1930, "Dorothy Sayers", "Robert Eustace"); 12 | List books = new ArrayList<>(); 13 | books.add(bookOne); 14 | books.add(bookTwo); 15 | books.add(bookThree); 16 | 17 | //1. двата класа се зипват -> трябва да се изтрият първите редове и в двата класа: package {packageName}; 18 | //2. зипваме самия package 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/comparableBook_03/Book.java: -------------------------------------------------------------------------------- 1 | package comparableBook; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class Book implements Comparable{ 8 | //полета 9 | private String title; //заглавие 10 | private int year; //година на издаване 11 | private List authors; //списък с авторите 12 | 13 | //методи 14 | //конструктор 15 | public Book (String title, int year, String... authors) { 16 | //нова празна книга 17 | this.title = title; 18 | this.year = year; 19 | //[автори] -> {автори} 20 | this.authors = new ArrayList<>(Arrays.asList(authors)); 21 | } 22 | 23 | 24 | //getters and setters 25 | 26 | public String getTitle() { 27 | return title; 28 | } 29 | 30 | public void setTitle(String title) { 31 | this.title = title; 32 | } 33 | 34 | public int getYear() { 35 | return year; 36 | } 37 | 38 | public void setYear(int year) { 39 | this.year = year; 40 | } 41 | 42 | public List getAuthors() { 43 | return authors; 44 | } 45 | 46 | public void setAuthors(List authors) { 47 | this.authors = authors; 48 | } 49 | 50 | @Override 51 | public int compareTo(Book otherBook) { 52 | //1. Title 53 | //2. Year 54 | int resultTitle = this.title.compareTo(otherBook.title); 55 | //compareTo от String 56 | //0 -> ако двата текста са напълно еднакви 57 | //> 0 -> ако първия е по-рано по азбучен ред 58 | //< 0 -> ако втория е по-рано по азбучен ред 59 | if (resultTitle == 0) { 60 | //двете книги са с еднакви заглавия 61 | resultTitle = Integer.compare(this.year, otherBook.year); 62 | //Integer.compare 63 | //0 -> ако годините са еднакви 64 | //1 -> първата > втората 65 | //-1 -> втората > първата 66 | } 67 | return resultTitle; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/comparableBook_03/Main.java: -------------------------------------------------------------------------------- 1 | package comparableBook; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | Book bookOne = new Book("Animal Farm", 2003, "George Orwell"); 6 | Book bookThree = new Book("The Documents in the Case", 2002); 7 | Book bookTwo = new Book("The Documents in the Case", 1930, "Dorothy Sayers", "Robert Eustace"); 8 | if (bookOne.compareTo(bookTwo) > 0) { 9 | System.out.println(String.format("%s is before %s", bookOne.getTitle(), bookTwo.getTitle())); 10 | } else if (bookOne.compareTo(bookTwo) < 0) { 11 | System.out.println(String.format("%s is before %s", bookTwo.getTitle(), bookOne.getTitle())); 12 | } else { 13 | System.out.println("Book are equal"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/library_02/Book.java: -------------------------------------------------------------------------------- 1 | package library; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class Book { 8 | //полета 9 | private String title; //заглавие 10 | private int year; //година на издаване 11 | private List authors; //списък с авторите 12 | 13 | //методи 14 | //конструктор 15 | public Book (String title, int year, String... authors) { 16 | //нова празна книга 17 | this.title = title; 18 | this.year = year; 19 | //[автори] -> {автори} 20 | this.authors = new ArrayList<>(Arrays.asList(authors)); 21 | } 22 | 23 | 24 | //getters and setters 25 | 26 | public String getTitle() { 27 | return title; 28 | } 29 | 30 | public void setTitle(String title) { 31 | this.title = title; 32 | } 33 | 34 | public int getYear() { 35 | return year; 36 | } 37 | 38 | public void setYear(int year) { 39 | this.year = year; 40 | } 41 | 42 | public List getAuthors() { 43 | return authors; 44 | } 45 | 46 | public void setAuthors(List authors) { 47 | this.authors = authors; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/library_02/Library.java: -------------------------------------------------------------------------------- 1 | package library; 2 | 3 | import java.util.Iterator; 4 | 5 | public class Library implements Iterable { 6 | private Book[] books; 7 | 8 | public Library(Book... books) { 9 | //нова библиотека 10 | this.books = books; 11 | } 12 | 13 | @Override 14 | public Iterator iterator() { 15 | return new LibraryIterator(); 16 | } 17 | 18 | //ITERATOR 19 | private class LibraryIterator implements Iterator { 20 | private int count = 0; //на коя книга се намирам 21 | @Override 22 | public boolean hasNext() { 23 | return count < books.length; 24 | } 25 | 26 | @Override 27 | public Book next() { 28 | return books[count++]; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Iterators and Comparators - Lab/Solutions/library_02/Main.java: -------------------------------------------------------------------------------- 1 | package library; 2 | 3 | import java.util.Iterator; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Book bookOne = new Book("Animal Farm", 2003, "George Orwell"); 8 | Book bookThree = new Book("The Documents in the Case", 2002); 9 | Book bookTwo = new Book("The Documents in the Case 2", 1930, "Dorothy Sayers", "Robert Eustace"); 10 | Library library = new Library(bookOne, bookTwo, bookThree); 11 | 12 | Iterator iterator = library.iterator(); 13 | while(iterator.hasNext()) { 14 | System.out.println(iterator.next().getTitle()); 15 | } 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Demos/Cube.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Cube implements Serializable { 6 | private String color; 7 | private int width; 8 | private int length; 9 | private int height; 10 | 11 | public Cube(String color, int width, int length, int height) { 12 | this.color = color; 13 | this.width = width; 14 | this.length = length; 15 | this.height = height; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Demos/DemoSerialization.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.*; 4 | 5 | public class DemoSerialization { 6 | public static void main(String[] args) throws IOException, ClassNotFoundException { 7 | Cube cube = new Cube("blue", 1, 5, 6); 8 | String pathCubeInfo = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\cubeInfo.ser"; 9 | 10 | //записваме обект във файл (serialization - сериализация) 11 | ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(pathCubeInfo)); 12 | oos.writeObject(cube); 13 | oos.close(); 14 | 15 | //прочитаме обект от файл (deserialization - десериализация) 16 | ObjectInputStream ois = new ObjectInputStream(new FileInputStream(pathCubeInfo)); 17 | Cube cube1 = (Cube) ois.readObject(); 18 | System.out.println(); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Demos/FileDemo.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.File; 4 | 5 | public class FileDemo { 6 | public static void main(String[] args) { 7 | File file = new File("C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\Files-and-Streams"); 8 | 9 | //class File - работа с файлове и директории 10 | 11 | System.out.println(file.exists()); 12 | //true -> ако съществува 13 | //false -> ако не съществува 14 | 15 | System.out.println(file.isDirectory()); 16 | //true -> ако е папка 17 | //false -> ако не е папка 18 | 19 | System.out.println(file.getName()); //име на файл 20 | System.out.println(file.length()); //размер на файл 21 | 22 | System.out.println(file.canWrite()); 23 | //true -> ако може да се пише във файла 24 | //false -> ако не може да се пише във файла 25 | 26 | System.out.println(file.canRead()); 27 | //true -> ако може да се чете от файла 28 | //false -> ако не може да се чете от файла 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Demos/FileInputOutputStreamDemo.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | 8 | public class FileInputOutputStreamDemo { 9 | public static void main(String[] args) throws IOException { 10 | //FileInputStream (поток за четене) и FileOutputStream (поток за писане) 11 | //- четем byte по byte 12 | //- по-бавно действие 13 | 14 | String pathRead = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\input.txt"; 15 | String pathWrite = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\outputTask2.txt"; 16 | 17 | FileInputStream inputStream = new FileInputStream(pathRead); 18 | FileOutputStream outputStream = new FileOutputStream(pathWrite); 19 | 20 | int currentByte = inputStream.read(); 21 | char currentSymbol = (char) currentByte; 22 | outputStream.write(currentSymbol); 23 | 24 | 25 | inputStream.close(); 26 | outputStream.close(); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Demos/FilesDemo.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.Collections; 8 | import java.util.List; 9 | 10 | public class FilesDemo { 11 | public static void main(String[] args) throws IOException { 12 | 13 | //Files 14 | //- редица полезни методи за работа с пътища 15 | //- readAllLines -> връща списък с всички редове 16 | //- write -> пише във файла 17 | //- работи пряко Path и Paths - представят пътища на компютър 18 | 19 | Path pathRead = Paths.get("C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\input.txt"); 20 | Path pathWrite = Paths.get("C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\sortedLines.txt"); 21 | List allLines = Files.readAllLines(pathRead); 22 | Files.write(pathWrite, allLines); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Demos/ScannerPrintWriterDemo.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileOutputStream; 6 | import java.io.PrintWriter; 7 | import java.util.Scanner; 8 | 9 | public class ScannerPrintWriterDemo { 10 | public static void main(String[] args) throws FileNotFoundException { 11 | 12 | //Scanner (FileReader) и PrintWriter(FileWriter) 13 | //- можем да използваме познати за нас команди 14 | //- четене символ по символ 15 | 16 | String pathRead = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\input.txt"; 17 | String pathWrite = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\everyThirdLine.txt"; 18 | 19 | FileInputStream inputStream = new FileInputStream(pathRead); 20 | FileOutputStream outputStream = new FileOutputStream(pathWrite); 21 | 22 | Scanner reader = new Scanner(inputStream); 23 | PrintWriter writer = new PrintWriter(outputStream); 24 | 25 | String line = reader.nextLine(); 26 | writer.println(line); 27 | 28 | writer.close(); 29 | reader.close(); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Solutions/CopyBytes_03.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | 8 | public class CopyBytes_03 { 9 | public static void main(String[] args) throws IOException { 10 | 11 | String pathIn = "C:\\Users\\user\\Desktop\\Files\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\input.txt"; 12 | String pathOut = "C:\\Users\\user\\Desktop\\Files\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\03.CopyBytesOutput.txt"; 13 | 14 | FileInputStream in = new FileInputStream(pathIn); 15 | FileOutputStream out = new FileOutputStream(pathOut); 16 | 17 | int oneByte = in.read(); 18 | while (oneByte >= 0) { 19 | if (oneByte == 32 || oneByte == 10) { 20 | out.write(oneByte); 21 | } else { 22 | String digits = String.valueOf(oneByte); 23 | for (int i = 0; i < digits.length(); i++) { 24 | out.write(digits.charAt(i)); 25 | } 26 | } 27 | oneByte = in.read(); 28 | 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Solutions/Cube.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Cube implements Serializable { 6 | private String color; 7 | private int width; 8 | private int length; 9 | private int height; 10 | 11 | public Cube(String color, int width, int length, int height) { 12 | this.color = color; 13 | this.width = width; 14 | this.length = length; 15 | this.height = height; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Solutions/ExtractIntegers_04.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.*; 4 | import java.util.Scanner; 5 | 6 | public class ExtractIntegers_04 { 7 | public static void main(String[] args) throws FileNotFoundException { 8 | String pathRead = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\input.txt"; 9 | FileInputStream inputStream = new FileInputStream(pathRead); 10 | Scanner scanner = new Scanner(inputStream); 11 | 12 | String pathWrite = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\outputNumbers.txt"; 13 | FileOutputStream outputStream = new FileOutputStream(pathWrite); 14 | PrintWriter writer = new PrintWriter(outputStream); 15 | 16 | //hasNext -> true: не сме стигнали до края на файла 17 | //hasNext -> false: сме стигнали до края на файла 18 | while (scanner.hasNext()) { 19 | if (scanner.hasNextInt()) { 20 | int number = scanner.nextInt(); 21 | writer.println(number); 22 | } 23 | scanner.next(); 24 | } 25 | 26 | writer.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Solutions/ListFiles_07.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.File; 4 | 5 | public class ListFiles_07 { 6 | public static void main(String[] args) { 7 | File folder = new File("C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\Files-and-Streams"); 8 | 9 | if (folder.exists()) { 10 | //съществува такъв файл 11 | if (folder.isDirectory()) { 12 | //файлър е папка 13 | File[] allFiles = folder.listFiles(); 14 | for (File file : allFiles) { 15 | if (!file.isDirectory()) { 16 | System.out.printf("%s: [%d]%n", file.getName(), file.length()); 17 | } 18 | } 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Solutions/ReadFile_01.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | 7 | public class ReadFile_01 { 8 | public static void main(String[] args) throws IOException { 9 | String path = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\input.txt"; 10 | FileInputStream inputStream = new FileInputStream(path); 11 | 12 | int currentByte = inputStream.read(); 13 | while (currentByte >= 0) { 14 | //79 -> двоична бройна система ("1001111") 15 | System.out.print(Integer.toBinaryString(currentByte) + " "); 16 | currentByte = inputStream.read(); 17 | } 18 | 19 | inputStream.close(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Solutions/SerializeCustomObject_09.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.IOException; 5 | import java.io.ObjectOutputStream; 6 | 7 | public class SerializeCustomObject_09 { 8 | public static void main(String[] args) throws IOException { 9 | Cube cube = new Cube("blue", 1, 5, 6); 10 | String pathCubeInfo = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\cubeInfo.ser"; 11 | 12 | //записваме обект във файл (serialization - сериализация) 13 | ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(pathCubeInfo)); 14 | oos.writeObject(cube); 15 | oos.close(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Solutions/SortLines_06.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.Collections; 8 | import java.util.List; 9 | 10 | public class SortLines_06 { 11 | public static void main(String[] args) throws IOException { 12 | Path pathRead = Paths.get("C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\input.txt"); 13 | Path pathWrite = Paths.get("C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\sortedLines.txt"); 14 | List allLines = Files.readAllLines(pathRead); 15 | Collections.sort(allLines); 16 | Files.write(pathWrite, allLines); 17 | 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Solutions/WriteEveryThirdLine_05.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileOutputStream; 6 | import java.io.PrintWriter; 7 | import java.util.Scanner; 8 | 9 | public class WriteEveryThirdLine_05 { 10 | public static void main(String[] args) throws FileNotFoundException { 11 | String pathRead = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\input.txt"; 12 | String pathWrite = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\everyThirdLine.txt"; 13 | 14 | FileInputStream inputStream = new FileInputStream(pathRead); 15 | FileOutputStream outputStream = new FileOutputStream(pathWrite); 16 | 17 | Scanner reader = new Scanner(inputStream); 18 | PrintWriter writer = new PrintWriter(outputStream); 19 | 20 | int count = 1; 21 | String line = reader.nextLine(); 22 | while (reader.hasNextLine()) { 23 | if (count % 3 == 0) { 24 | writer.println(line); 25 | } 26 | count++; 27 | line = reader.nextLine(); 28 | } 29 | 30 | writer.close(); 31 | reader.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Streams, Files and Directories - Lab/Solutions/WriteToFile_02.java: -------------------------------------------------------------------------------- 1 | package Streams_Files_Directories; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | 7 | public class WriteToFile_02 { 8 | public static void main(String[] args) throws IOException { 9 | String pathRead = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\input.txt"; 10 | String pathWrite = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\Java-Adv-May-2023\\src\\04. Java-Advanced-Files-and-Streams-Lab-Resources\\outputTask2.txt"; 11 | 12 | FileInputStream inputStream = new FileInputStream(pathRead); 13 | FileOutputStream outputStream = new FileOutputStream(pathWrite); 14 | 15 | int currentByte = inputStream.read(); //ascii кода на прочетения символ 16 | while (currentByte >= 0) { 17 | char currentSymbol = (char) currentByte; 18 | if (currentSymbol != '.' && currentSymbol != ',' && currentSymbol != '!' && currentSymbol != '?') { 19 | outputStream.write(currentSymbol); 20 | } 21 | 22 | currentByte = inputStream.read(); 23 | } 24 | 25 | inputStream.close(); 26 | outputStream.close(); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Demo/BruteForceDemo.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | public class BruteForceDemo { 4 | public static void main(String[] args) { 5 | //{0-9}{0-9}{0-9}{0-9}{0-9} 6 | int count = 0; //брой опити 7 | for (int first = 0; first <= 9; first++) { 8 | for (int second = 0; second <= 9; second++) { 9 | for (int third = 0; third <= 9; third++) { 10 | for (int forth = 0; forth <= 9; forth++) { 11 | for (int fifth = 0; fifth <= 9; fifth++) { 12 | count++; 13 | } 14 | } 15 | } 16 | } 17 | } 18 | 19 | System.out.println(count); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Demo/BubbleSortDemo.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | public class BubbleSortDemo { 4 | public static void main(String[] args) { 5 | int[] numbers = {1, 3, 4, 2, 5, 6}; 6 | for (int i = 0; i < numbers.length; i++) { 7 | for (int j = i + 1; j < numbers.length - 1; j++) { 8 | if (numbers[i] > numbers[j]) { 9 | //размяна 10 | int tempNumber = numbers[i]; 11 | numbers[i] = numbers[j]; 12 | numbers[j] = tempNumber; 13 | } 14 | } 15 | } 16 | 17 | for (int number : numbers) { 18 | System.out.print(number + " "); 19 | } 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Demo/Coins.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | 8 | public class Coins { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | int[] coins = {200, 100, 50, 20, 10, 5, 2, 1}; // Стойности на наличните монети 12 | int sumSt = Integer.parseInt(scanner.nextLine()); 13 | 14 | int[] selectedCoins = getMinimumCoins(coins, sumSt); 15 | System.out.println("Най-малко количество монети: " + selectedCoins.length); 16 | System.out.println("Избрани монети: " + Arrays.toString(selectedCoins)); 17 | } 18 | 19 | public static int[] getMinimumCoins(int[] coins, int amount) { 20 | Arrays.sort(coins); // Сортираме монетите във възходящ ред 21 | //[1, 2, 5, 10, 20, 50, 100, 200] 22 | 23 | int[] selectedCoins = new int[amount]; // Масив за избраните монети 24 | int index = 0; // Индекс в масива за избраните монети 25 | 26 | for (int i = coins.length - 1; i >= 0; i--) { 27 | while (amount >= coins[i]) { 28 | selectedCoins[index] = coins[i]; // Добавяме монетата към списъка 29 | amount -= coins[i]; // Намаляваме сумата 30 | index++; 31 | } 32 | } 33 | 34 | return Arrays.copyOf(selectedCoins, index); // Връщаме само използваните монети 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Demo/Demo.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | public class Demo { 4 | public static void main(String[] args) { 5 | //алгоритми 6 | //1. намиране на най-малко число 7 | //2. намиране на най-голямо число 8 | //3. факториел на дадено число 9 | //4. взимаме цифрите на число 10 | //5. проверка за просто число 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Demo/FibonacciDemo.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.Scanner; 4 | 5 | public class FibonacciDemo { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int n = Integer.parseInt(scanner.nextLine()); 9 | 10 | //F(n) = F(n-1) + F(n-2) 11 | System.out.println(calcFib(n)); 12 | 13 | 14 | } 15 | 16 | private static long calcFib (int n) { 17 | //дъно 18 | if (n == 0) { 19 | //F(0) 20 | return 0; 21 | } else if (n == 1) { 22 | //F(1) 23 | return 1; 24 | } 25 | return calcFib(n - 1) + calcFib(n - 2); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Solutions/BinarySearch_07.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class BinarySearch_07 { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int[] numbers = Arrays.stream(scan.nextLine().split("\\s+")).mapToInt(Integer::parseInt).toArray(); 10 | int number = Integer.parseInt(scan.nextLine()); 11 | int index = getIndex(numbers, number); 12 | System.out.println(index); 13 | } 14 | 15 | public static int getIndex(int[] arr, int key) { 16 | int start = 0; 17 | int end = arr.length - 1; 18 | while (start <= end) { 19 | if (arr[start] == key) { 20 | return start; 21 | } 22 | start++; 23 | } 24 | return -1; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Solutions/MergeSort_05.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class MergeSort_05 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | int[] sortedArray = mergeSort(Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray()); 10 | 11 | for (int num : sortedArray) { 12 | System.out.print(num + " "); 13 | } 14 | 15 | } 16 | 17 | private static int[] mergeSort(int[] array) { 18 | 19 | if (array.length == 1) { 20 | return array; 21 | } 22 | int halfIndex = array.length / 2; 23 | int[] firstPartition = Arrays.copyOfRange(array, 0, halfIndex); 24 | int[] secondPartition = Arrays.copyOfRange(array, halfIndex, array.length); 25 | 26 | firstPartition = mergeSort(firstPartition); 27 | secondPartition = mergeSort(secondPartition); 28 | 29 | return mergeTwoSortedArrays(firstPartition, secondPartition); 30 | } 31 | 32 | private static int[] mergeTwoSortedArrays(int[] firstPartition, int[] secondPartition) { 33 | int[] sorted = new int[firstPartition.length + secondPartition.length]; 34 | int firstIndex = 0; 35 | int secondIndex = 0; 36 | 37 | while (firstIndex < firstPartition.length && secondIndex < secondPartition.length) { 38 | if (firstPartition[firstIndex] < secondPartition[secondIndex]) { 39 | sorted[firstIndex + secondIndex] = firstPartition[firstIndex]; 40 | firstIndex++; 41 | } else { 42 | sorted[secondIndex + firstIndex] = secondPartition[secondIndex]; 43 | secondIndex++; 44 | } 45 | } 46 | 47 | while (firstIndex < firstPartition.length) { 48 | 49 | sorted[firstIndex + secondIndex] = firstPartition[firstIndex]; 50 | firstIndex++; 51 | } 52 | 53 | while (secondIndex < secondPartition.length) { 54 | sorted[secondIndex + firstIndex] = secondPartition[secondIndex]; 55 | secondIndex++; 56 | 57 | } 58 | 59 | return sorted; 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Solutions/Quicksort_06.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class Quicksort_06 { 7 | public static void main(String[] args) { 8 | 9 | Scanner scan = new Scanner(System.in); 10 | int[] array = Arrays.stream(scan.nextLine().split("\\s+")).mapToInt(Integer::parseInt).toArray(); 11 | 12 | sort(array, 0, array.length - 1); 13 | System.out.println(Arrays.toString(array).replaceAll("[\\[\\],]", "")); 14 | } 15 | 16 | static void sort(int[] subArray, int startIndex, int endIndex) { 17 | 18 | if (startIndex < endIndex) { 19 | int pivot = partition(subArray, startIndex, endIndex); 20 | sort(subArray, startIndex, pivot - 1); 21 | sort(subArray, pivot + 1, endIndex); 22 | } 23 | } 24 | 25 | static int partition(int[] subArray, int startIndex, int endIndex) { 26 | 27 | int pivot = subArray[endIndex]; 28 | int i = (startIndex - 1); 29 | 30 | for (int j = startIndex; j < endIndex; j++) { 31 | if (subArray[j] <= pivot) { 32 | i++; 33 | int temp = subArray[i]; 34 | subArray[i] = subArray[j]; 35 | subArray[j] = temp; 36 | } 37 | } 38 | int temp = subArray[i + 1]; 39 | subArray[i + 1] = subArray[endIndex]; 40 | subArray[endIndex] = temp; 41 | return i + 1; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Solutions/RecursiveArraySum_01.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class RecursiveArraySum_01 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | int [] array = Arrays.stream(scanner.nextLine().split("\\s+")).mapToInt(Integer::parseInt).toArray(); 10 | 11 | //3 4 5 6 8 9 12 | System.out.println(sumArray(array, 0)); 13 | } 14 | 15 | public static int sumArray(int [] array, int index) { 16 | if (index >= array.length) { 17 | return 0; 18 | } 19 | 20 | return array[index] + sumArray(array, index + 1); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Solutions/RecursiveFactorial_02.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.Scanner; 4 | 5 | public class RecursiveFactorial_02 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int n = Integer.parseInt(scanner.nextLine()); 9 | 10 | //n! -> факториел от n 11 | //n = 5 -> 5! = 5 * 4 * 3 * 2 * 1 12 | //5! = 5 * 4! 13 | //4! = 4 * 3! 14 | //3! = 3 * 2! 15 | //2! = 2 * 1! 16 | 17 | //0! = 1 18 | //1! = 1 19 | 20 | System.out.println(calcFact(n)); 21 | 22 | } 23 | 24 | public static long calcFact (int n) { 25 | //1! = 1 26 | //0! = 1 27 | 28 | //дъно 29 | if (n == 1 || n == 0) { 30 | return 1; 31 | } 32 | 33 | return n * calcFact(n - 1); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Workshop - Algorithms Introduction/Solutions/SumOfCoins_03.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | public class SumOfCoins_03 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | String[] elements = scanner.nextLine().substring(7).split(", "); 12 | int[] coins = new int[elements.length]; 13 | for (int i = 0; i < coins.length; i++) { 14 | coins[i] = Integer.parseInt(elements[i]); 15 | } 16 | 17 | int targetSum = Integer.parseInt(scanner.nextLine().substring(5)); 18 | 19 | Map usedCoins; 20 | 21 | try { 22 | usedCoins = chooseCoins(coins, targetSum); 23 | } catch (IllegalStateException e) { 24 | System.out.println(e.getMessage()); 25 | return; 26 | } 27 | 28 | for (Map.Entry usedCoin : usedCoins.entrySet()) { 29 | System.out.println(usedCoin.getKey() + " -> " + usedCoin.getValue()); 30 | } 31 | } 32 | 33 | public static Map chooseCoins(int[] coins, int targetSum) { 34 | 35 | Map coinsAmount = new LinkedHashMap<>(); 36 | 37 | int index = coins.length - 1; 38 | 39 | while (targetSum != 0 && index >= 0) { 40 | int coin = coins[index--]; 41 | int coinsToTake = targetSum / coin; 42 | targetSum = targetSum % coin; 43 | 44 | if (coinsToTake != 0) { 45 | coinsAmount.put(coin, coinsToTake); 46 | } 47 | } 48 | 49 | if (targetSum != 0) { 50 | throw new IllegalStateException("Error"); 51 | } 52 | 53 | return coinsAmount; 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Видеа на задачи от курса.txt: -------------------------------------------------------------------------------- 1 | Допълнителни видеа на задачи от курса: 2 | 04. Maximal Sum 3 | видео: https://youtu.be/d7xzSoeQnUQ?t=6549 4 | решение: https://pastebin.com/1jCzr9XG 5 | 07. Crossfire (с лист от листове) -> https://pastebin.com/dAGyPkt8 6 | видео: https://youtu.be/D2Zfs38iDZE?t=8803 7 | 06. Recursive Fibonacci -> https://pastebin.com/E58jfqgB 8 | видео: https://www.youtube.com/watch?v=z3wWIVUwNAo&t=10300s 9 | 10. Robotics (решение с Map) -> https://pastebin.com/r2yYHatm 10 | 10. Robotics (решение с масив) -> https://pastebin.com/h7FivYpT 11 | видео: https://www.youtube.com/watch?v=XK-rdc4oCl8&t=3345s 12 | 12. Сръбско Unleashed -> https://pastebin.com/HgdgUFCy 13 | видео: https://youtu.be/zz0oeaI4ayA?t=8365 14 | 07. Hands of Cards -> https://pastebin.com/xPkWvqDS 15 | видео: https://youtu.be/sFfxvhLYcy0?t=5697 -------------------------------------------------------------------------------- /Видеа на изпитни задачи.txt: -------------------------------------------------------------------------------- 1 | Здравейте, качвам малко видеа + решения на стари изпитни задачи за матрици. 2 | 02. Mouse and cheese 3 | Решение: https://pastebin.com/xi1RzPPx 4 | видео: https://youtu.be/6tLG9EHzeps?t=9706 5 | 6 | 02. Throne Conquering 7 | Решение: https://pastebin.com/tNbTKSpK 8 | видео: https://youtu.be/Tx2xO5zTqNk?t=8330 9 | 10 | 02. Formula One 11 | Решение: https://pastebin.com/RDwSX6fC 12 | Видео: https://youtu.be/ToZNX6FLWwg?t=11605 13 | 14 | 02. Sticky Fingers 15 | Решение: https://pastebin.com/DG1N7Eba 16 | Видео: https://softuni.bg/.../video-26-january-2023.../3959 17 | 18 | 02. The Squirrel 19 | Решение: https://pastebin.com/JHCS3maU 20 | Видео: https://softuni.bg/trainings/resources/video/84213/video-23-may-2023-%D0%B4%D0%B5%D1%81%D0%B8%D1%81%D0%BB%D0%B0%D0%B2%D0%B0-%D1%82%D0%BE%D0%BF%D1%83%D0%B7%D0%B0%D0%BA%D0%BE%D0%B2%D0%B0-raw-version-java-advanced-may-2023/4100 21 | 22 | 23 | 01. Rubber Duck Debuggers 24 | Решение: https://pastebin.com/GjiBZYZD 25 | Видео: https://softuni.bg/trainings/resources/video/84677/video-06-june-2023-desislava-topuzakova-java-advanced-may-2023/4100 26 | 27 | 28 | 03. Softuni Kindergarten 29 | Решение: https://pastebin.com/xPeeycV8 30 | Видео: https://softuni.bg/trainings/resources/video/84528/video-02-june-2023-%D0%B4%D0%B5%D1%81%D0%B8%D1%81%D0%BB%D0%B0%D0%B2%D0%B0-%D1%82%D0%BE%D0%BF%D1%83%D0%B7%D0%B0%D0%BA%D0%BE%D0%B2%D0%B0-java-advanced-may-2023/4100 --------------------------------------------------------------------------------