├── 01. Basic Syntax, Conditional Statements and Loops - Exercise ├── Solutions │ ├── Ages_01.java │ ├── Division_02.java │ ├── Login_05.java │ ├── Orders_09.java │ ├── PadawanEquipment_10.java │ ├── PrintAndSum_04.java │ ├── RageExpenses_11.java │ ├── StrongNumber_06.java │ ├── TriangleOfNumbers_08.java │ ├── Vacation_03.java │ └── VendingMachine_07.java └── Videos │ └── BasicSyntax_Videos.txt ├── 02. Data Types and Variables ├── Solutions │ ├── BeerKegs_08.java │ ├── Elevator_03.java │ ├── IntegerOperations_01.java │ ├── Pokemon_10.java │ ├── PrintPart_05.java │ ├── Snowballs_11.java │ ├── SpiceMustFlow_09.java │ ├── SumDigits_02.java │ ├── SumDigits_For_02.java │ ├── SumOfChars_04.java │ ├── TripletsOfLetters_06.java │ └── WaterOverflow_07.java └── Videos │ └── DataTypesAndVariables_Videos.txt ├── 03. Arrays ├── Solutions │ ├── ArrayModifier_09.java │ ├── ArrayRotation_04.java │ ├── CommonElements_02.java │ ├── EqualsSums_06.java │ ├── MagicSum_08.java │ ├── MaxSequenceEqualElements_07.java │ ├── TopIntegers_05.java │ ├── Train_01.java │ ├── TreasureHunt_10.java │ └── ZigZagArrays_3.java └── Videos │ └── Arrays - Exercise - Videos.txt ├── 04. Methods ├── Solutions │ ├── AddAndSubtract_05.java │ ├── CharactersInRange_03.java │ ├── FactorialDivision_08.java │ ├── MiddleCharacters_06.java │ ├── NxNMatrix_07.java │ ├── PalindromeIntegers_09.java │ ├── PasswordValidator_04.java │ ├── SmallestOfThreeNumbers_01.java │ ├── TopNumber_10.java │ └── VowelsCount_02.java └── Videos │ └── Methods - Videos.txt ├── 05. Lists ├── Solutions │ ├── AnonymousThreat_08.java │ ├── AppendArrays_07.java │ ├── BombNumbers_05.java │ ├── CardsGame_06.java │ ├── ChangeList_02.java │ ├── HouseParty_03.java │ ├── ListOperations_04.java │ ├── PokemonDontGo_09.java │ ├── SoftUniCoursePlanning_10.java │ └── Train_01.java └── Videos │ └── Lists_Exercise_Videos.txt ├── 06. Exam Preparation ├── HeartDelivery_03_Array.java ├── HeartDelivery_03_List.java ├── ShootForTheWin_02.java └── SoftUniReception_01.java ├── 07. Objects and Classes ├── Solutions │ ├── AdvertisementMessage_01 │ │ ├── Main.java │ │ └── Message.java │ ├── Articles_02 │ │ ├── Article.java │ │ └── Main.java │ ├── GroomingSalon_07 │ │ ├── GroomingSalon.java │ │ ├── Main.java │ │ └── Pet.java │ ├── OpinionPoll_03 │ │ ├── Main.java │ │ └── Person.java │ ├── OrderByAge_06 │ │ ├── Main.java │ │ └── Person.java │ ├── Students_04 │ │ ├── Main.java │ │ └── Student.java │ └── VehicleCatalogue_05 │ │ ├── Main.java │ │ └── Vehicle.java └── Videos │ └── ObjectsAndClasses_Exercise_Videos.txt ├── 08. Maps ├── Solutions │ ├── CompanyUsers_08.java │ ├── CountCharInString_01.java │ ├── Courses_05.java │ ├── Forcebook_09.java │ ├── LegendaryFarming_07.java │ ├── MinerTask_02.java │ ├── Orders_03.java │ ├── SoftuniParking_04.java │ └── StudentAcademy_06.java └── Videos │ └── Maps-Exercise_Videos.txt ├── 09. Text Processing ├── CaesarCipher_04.java ├── CharacterMultiplier_02.java ├── ExtractFile_03.java ├── LettersChangeNumbers_08.java ├── MultiplyBigNumber_05.java ├── MultiplyBigNumbers2_05.java ├── ReplaceRepeatingChars_06.java ├── StringExplosion_07.java └── ValidUsernames_01.java ├── 10. Regular Expressions ├── Exercise │ ├── ExtractEmails_05.java │ ├── Furniture_01.java │ ├── NetherRealms_04.java │ ├── SoftuniBarIncome_02.java │ ├── StarEnigma_03.java │ └── ValidPassword_06.java └── Lab │ ├── MatchDates_03.java │ ├── MatchFullNames_01.java │ ├── MatchPhoneNumber_02.java │ └── RegEx - Cheat Sheet.txt └── 11. Exam Preparation ├── Task_01.java ├── Task_02.java └── Task_03.java /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Ages_01.java: -------------------------------------------------------------------------------- 1 | package BasicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Ages_01 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //1. възраст - цяло число 10 | //2. проверка на възрастта 11 | //• 0-2 – baby; - ok 12 | //• 3-13 – child; - ok 13 | //• 14-19 – teenager; - ok 14 | //• 20-65 – adult; 15 | //• >=66 – elder; 16 | 17 | int age = Integer.parseInt(scanner.nextLine()); 18 | if (age >= 0 && age <= 2) { 19 | System.out.println("baby"); 20 | } else if (age >= 3 && age <= 13) { 21 | System.out.println("child"); 22 | } else if (age >= 14 && age <= 19) { 23 | System.out.println("teenager"); 24 | } else if (age >= 20 && age <= 65) { 25 | System.out.println("adult"); 26 | } else if (age >= 66) { 27 | System.out.println("elder"); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Division_02.java: -------------------------------------------------------------------------------- 1 | package basicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Division_02 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //1. прочитаме цяло число 10 | int number = Integer.parseInt(scanner.nextLine()); 11 | 12 | //2. проверки дали числото се дели: 10, 7, 6, 3, 2 13 | if (number % 10 == 0) { 14 | //числото се дели на 10 15 | System.out.println("The number is divisible by 10"); 16 | } else if (number % 7 == 0) { 17 | //числото се дели на 7 18 | System.out.println("The number is divisible by 7"); 19 | } else if (number % 6 == 0) { 20 | //числото се дели на 6 21 | System.out.println("The number is divisible by 6"); 22 | } else if (number % 3 == 0) { 23 | //числото се дели на 3 24 | System.out.println("The number is divisible by 3"); 25 | } else if (number % 2 == 0) { 26 | //числото се дели на 2 27 | System.out.println("The number is divisible by 2"); 28 | } else { 29 | System.out.println("Not divisible"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Login_05.java: -------------------------------------------------------------------------------- 1 | package basicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Login_05 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | //профил 9 | String username = scanner.nextLine(); //потребителско име -> "Desi1998" 10 | String password = ""; //парола -> username обърнат на обратно 11 | //последната към първата 12 | for (int position = username.length() - 1; position >= 0; position--) { 13 | char currentSymbol = username.charAt(position); 14 | password += currentSymbol; 15 | } 16 | 17 | //повтаряме: въвеждаме парола 18 | //стоп: въведената парола == password 19 | //продължаваме: въведената парола != password 20 | 21 | int countWrongPassword = 0; //брой грешни пароли 22 | String enteredPassword = scanner.nextLine(); //въведената парола 23 | 24 | while (!enteredPassword.equals(password)) { 25 | //грешна парола 26 | countWrongPassword++; 27 | //1. проверка дали имаме блокиране -> неуспешни опити = 4 28 | if (countWrongPassword == 4) { 29 | System.out.printf("User %s blocked!", username); 30 | break; 31 | } 32 | //2. ОПИТАЙ ОТНОВО 33 | System.out.println("Incorrect password. Try again."); 34 | enteredPassword = scanner.nextLine(); 35 | } 36 | 37 | //вярна парола 38 | if (enteredPassword.equals(password)) { 39 | System.out.printf("User %s logged in.", username); 40 | } 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Orders_09.java: -------------------------------------------------------------------------------- 1 | package BasicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Orders_09 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int orders = Integer.parseInt(scanner.nextLine()); 9 | double allMoney = 0; 10 | for (int order = 1; order <= orders; order++) { 11 | double pricePerCapsule = Double.parseDouble(scanner.nextLine()); 12 | int daysInMonth = Integer.parseInt(scanner.nextLine()); 13 | int capsulesCount = Integer.parseInt(scanner.nextLine()); 14 | double moneyForOrder = ((daysInMonth * capsulesCount) * pricePerCapsule); 15 | System.out.printf("The price for the coffee is: $%.2f%n", moneyForOrder); 16 | allMoney += moneyForOrder; 17 | } 18 | System.out.printf("Total: $%.2f", allMoney); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/PadawanEquipment_10.java: -------------------------------------------------------------------------------- 1 | package BasicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PadawanEquipment_10 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | //обща сума = сума за мечове + сума за одежди + сума за колани 9 | //1. сума за мечове = бр. мечове(ученици + 10%) * цена за мечовете(вход) 10 | //2. сума за одежди = бр. одежди = бр. ученици * цена за одеждите(вход) 11 | //3. сума за колани = бр. коланите (ученици - ученици / 6) * цена за коланите(вход) 12 | double budget = Double.parseDouble(scanner.nextLine()); 13 | int studentsCount = Integer.parseInt(scanner.nextLine()); 14 | double priceLight = Double.parseDouble(scanner.nextLine()); 15 | double priceRobe = Double.parseDouble(scanner.nextLine()); 16 | double priceBelt = Double.parseDouble(scanner.nextLine()); 17 | 18 | double sumLight = Math.ceil(studentsCount + 0.10 * studentsCount) * priceLight; //1.1 * studentsCount 19 | double sumRobes = studentsCount * priceRobe; 20 | double sumBelts = (studentsCount - studentsCount / 6) * priceBelt; 21 | 22 | double totalSum = sumLight + sumRobes + sumBelts; //крайната сума за плащане 23 | 24 | if(totalSum <= budget) { 25 | System.out.printf("The money is enough - it would cost %.2flv.", totalSum); 26 | } else { 27 | double needMoney = totalSum - budget; 28 | System.out.printf("George Lucas will need %.2flv more.", needMoney); 29 | } 30 | 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/PrintAndSum_04.java: -------------------------------------------------------------------------------- 1 | package basicSyntax; 2 | 3 | import java.util.Scanner; 4 | public class PrintAndSum_04 { 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | 8 | //1. принтираме числата от начално число до крайно число 9 | int startNumber = Integer.parseInt(scanner.nextLine()); //начало на интервала 10 | int endNumber = Integer.parseInt(scanner.nextLine()); //край на интервала 11 | 12 | //2. намерим сумата от числата в дадения интервал 13 | int sum = 0; //сумата на числата 14 | 15 | //FOR 16 | //повтаряме: отпечатваме число + интервал 17 | //начало: startNumber 18 | //край: endNumber 19 | //промяна: +1 20 | 21 | for (int number = startNumber; number <= endNumber; number++) { 22 | System.out.print(number + " "); 23 | sum = sum + number; //sum += number; 24 | } 25 | 26 | System.out.println(); //минава на нов ред 27 | System.out.println("Sum: " + sum); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/RageExpenses_11.java: -------------------------------------------------------------------------------- 1 | package basicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class RageExpenses_11 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //крайна сума = сума за слушалки (бр. слушалки * цена за 1 слушалки) 10 | // + сума за мишки (бр. мишки * цена за 1 мишка) 11 | // + сума за клавиатури (бр. клавиатури * цена за 1 клавиатура) 12 | // + сума за монитори (бр. монитори * цена за 1 монитор) 13 | 14 | int countLoseGames = Integer.parseInt(scanner.nextLine()); //брой загубени игри 15 | double priceHeadset = Double.parseDouble(scanner.nextLine()); //цена за 1 слушалки 16 | double priceMouse = Double.parseDouble(scanner.nextLine()); //цена за 1 мишка 17 | double priceKeyboard = Double.parseDouble(scanner.nextLine()); //цена за 1 клавиатура 18 | double priceDisplay = Double.parseDouble(scanner.nextLine()); //цена за 1 монитор 19 | 20 | int countHeadset = 0; //бр. слушалки 21 | int countMouse = 0; //бр. мишки 22 | int countKeyboard = 0; //бр. калвиатури 23 | int countDisplay = 0; //бр. монитори 24 | 25 | for (int loseGame = 1; loseGame <= countLoseGames; loseGame++) { 26 | if (loseGame % 2 == 0) { 27 | //всяка втора игра -> слушалки 28 | countHeadset++; 29 | } 30 | if (loseGame % 3 == 0) { 31 | //всяка трета игра -> мишка 32 | countMouse++; 33 | } 34 | if (loseGame % 6 == 0) { 35 | //всяка шеста игра -> калвиатура 36 | countKeyboard++; 37 | } 38 | if (loseGame % 12 == 0) { 39 | //всяка дванадесета игра -> монитор 40 | countDisplay++; 41 | } 42 | } 43 | 44 | double totalPrice = (countHeadset * priceHeadset) 45 | + (countMouse * priceMouse) 46 | + (countKeyboard * priceKeyboard) 47 | + (countDisplay * priceDisplay); 48 | 49 | System.out.printf("Rage expenses: %.2f lv.", totalPrice); 50 | 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/StrongNumber_06.java: -------------------------------------------------------------------------------- 1 | package basicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class StrongNumber_06 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int number = Integer.parseInt(scanner.nextLine()); 9 | int startNumber = number; //първоначалната стойност на числото 10 | 11 | int sumFact = 0; //сума на факториелитеч 12 | 13 | //стоп: число <= 0 -> нямаме повече цифри 14 | //продължавм: число > 0 -> имаме цифри в числото 15 | while (number > 0) { 16 | //1. последната цифра 17 | int lastDigit = number % 10; //взимаме последна или единствена цифра 18 | //2. факториел 19 | int fact = 1; //факториел на числото 20 | for (int i = 1; i <= lastDigit ; i++) { 21 | fact = fact * i; 22 | } 23 | //3. сумираме факториела 24 | sumFact += fact; 25 | //4. премахваме последната цифра 26 | number = number / 10; //number /= 10; 27 | } 28 | 29 | //проверка дали числото е силно или не 30 | //сума от факториелите == първоначалното число 31 | if (sumFact == startNumber) { 32 | System.out.println("yes"); 33 | } else { 34 | System.out.println("no"); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/TriangleOfNumbers_08.java: -------------------------------------------------------------------------------- 1 | package BasicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TriangleOfNumbers_08 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int n = Integer.parseInt(scanner.nextLine()); 9 | 10 | for (int row = 1; row <= n ; row++) { 11 | //колко пъти да печатам нещо 12 | for (int count = 1; count <= row ; count++) { 13 | System.out.print(row + " "); 14 | } 15 | System.out.println(); 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Vacation_03.java: -------------------------------------------------------------------------------- 1 | package BasicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Vacation_03 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | int countStudents = Integer.parseInt(scanner.nextLine()); 10 | String typeGroup = scanner.nextLine(); 11 | String day = scanner.nextLine(); 12 | double price = 0; 13 | 14 | if (typeGroup.equals("Students")) { 15 | if (day.equals("Friday")) { 16 | price = 8.45; 17 | 18 | } else if (day.equals("Saturday")) { 19 | price = 9.80; 20 | } else if (day.equals("Sunday")) { 21 | price = 10.46; 22 | } 23 | 24 | if (countStudents >= 30) { 25 | price = price * 0.85; 26 | } 27 | 28 | } else if (typeGroup.equals("Business")) { 29 | if (day.equals("Friday")) { 30 | price = 10.90; 31 | } else if (day.equals("Saturday")) { 32 | price = 15.60; 33 | } else if (day.equals("Sunday")) { 34 | price = 16; 35 | } 36 | if (countStudents >= 100) { 37 | countStudents = countStudents - 10; 38 | } 39 | 40 | } else if (typeGroup.equals("Regular")) { 41 | 42 | if (day.equals("Friday")) { 43 | price = 15; 44 | } else if (day.equals("Saturday")) { 45 | price = 20; 46 | } else if (day.equals("Sunday")) { 47 | price = 22.50; 48 | } 49 | if (countStudents >= 10 && countStudents <= 20) { 50 | price = price * 0.95; 51 | 52 | } 53 | } 54 | double totalPrice = countStudents * price; 55 | System.out.printf("Total price: %.2f", totalPrice); 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/VendingMachine_07.java: -------------------------------------------------------------------------------- 1 | package BasicSyntax; 2 | 3 | import java.util.Scanner; 4 | 5 | public class VendingMachine_07 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | String command = scanner.nextLine(); 9 | double sum = 0; 10 | //with 0.1, 0.2, 0.5, 1, and 2 11 | while(!command.equals("Start")) { 12 | double coin = Double.parseDouble(command); 13 | if(coin != 0.1 && coin != 0.2 && coin != 0.5 && coin != 1 && coin != 2) { 14 | System.out.printf("Cannot accept %.2f%n", coin); 15 | } else { 16 | sum += coin; 17 | } 18 | 19 | command = scanner.nextLine(); 20 | } 21 | 22 | String product = scanner.nextLine(); 23 | 24 | //"Nuts", "Water", "Crisps", "Soda", "Coke". The prices are: 2.0, 0.7, 1.5, 0.8, 1.0 25 | while(!product.equals("End")) { 26 | boolean hasMoney = true; 27 | switch(product) { 28 | case "Nuts": 29 | if(sum < 2) { 30 | System.out.println("Sorry, not enough money"); 31 | hasMoney = false; 32 | } else { 33 | sum -= 2; 34 | } 35 | break; 36 | case "Water": 37 | if(sum < 0.7) { 38 | System.out.println("Sorry, not enough money"); 39 | hasMoney = false; 40 | } else { 41 | sum -= 0.7; 42 | } 43 | break; 44 | case "Crisps": 45 | if(sum < 1.5) { 46 | System.out.println("Sorry, not enough money"); 47 | hasMoney = false; 48 | } else { 49 | sum -= 1.5; 50 | } 51 | break; 52 | case "Soda": 53 | if(sum < 0.8) { 54 | System.out.println("Sorry, not enough money"); 55 | hasMoney = false; 56 | } else { 57 | sum -= 0.8; 58 | } 59 | 60 | break; 61 | case "Coke": 62 | if(sum < 1) { 63 | System.out.println("Sorry, not enough money"); 64 | hasMoney = false; 65 | } else { 66 | sum -= 1; 67 | } 68 | break; 69 | default: 70 | System.out.println("Invalid product"); 71 | hasMoney = false; 72 | break; 73 | } 74 | if(!hasMoney) { 75 | product = scanner.nextLine(); 76 | continue; 77 | } 78 | System.out.printf("Purchased %s%n", product); 79 | 80 | 81 | product = scanner.nextLine(); 82 | } 83 | 84 | System.out.printf("Change: %.2f", sum); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /01. Basic Syntax, Conditional Statements and Loops - Exercise/Videos/BasicSyntax_Videos.txt: -------------------------------------------------------------------------------- 1 | 10. Padawan Equipment -> https://pastebin.com/udpW9C6D 2 | видео: https://youtu.be/tButUIUb7u8 3 | 4 | 05. Messages (More Exercises) -> https://pastebin.com/yjbH1Ren 5 | видео: https://youtu.be/fzg7eWRZdE0 -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/BeerKegs_08.java: -------------------------------------------------------------------------------- 1 | package dataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class BeerKegs_08 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | int countKegs = Integer.parseInt(scanner.nextLine()); //брой кегове 10 | 11 | //за всеки един кег от 1 до последния (countKegs): 12 | //1. модел -> String 13 | //2. радиус -> double 14 | //3. височина -> int 15 | //4. обем = пи * радиус * радиус * височина 16 | 17 | double maxVolume = 0; //максималния обем 18 | String maxModel = ""; //модел на кега, който е с най-голям обем 19 | 20 | for (int keg = 1; keg <= countKegs; keg++) { 21 | String model = scanner.nextLine(); 22 | double radius = Double.parseDouble(scanner.nextLine()); 23 | int height = Integer.parseInt(scanner.nextLine()); 24 | 25 | double volume = Math.PI * Math.pow(radius, 2) * height; 26 | 27 | //проверка дали изчисления обем е максимален 28 | if (volume > maxVolume) { 29 | maxVolume = volume; 30 | maxModel = model; 31 | } 32 | } 33 | 34 | System.out.println(maxModel); 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/Elevator_03.java: -------------------------------------------------------------------------------- 1 | package DataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Elevator_03 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int countPeople = Integer.parseInt(scanner.nextLine()); 9 | int capacity = Integer.parseInt(scanner.nextLine()); 10 | 11 | //курсове = хората / капацитета -> дробно число -> нагоре -> отпечатвам 12 | double courses = Math.ceil(countPeople * 1.0 / capacity); 13 | System.out.printf("%.0f", courses); 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/IntegerOperations_01.java: -------------------------------------------------------------------------------- 1 | package DataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class IntegerOperations_01 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int firstNumber = Integer.parseInt(scanner.nextLine()); 9 | int secondNumber = Integer.parseInt(scanner.nextLine()); 10 | int thirdNumber = Integer.parseInt(scanner.nextLine()); 11 | int forthNumber = Integer.parseInt(scanner.nextLine()); 12 | 13 | int result = ((firstNumber + secondNumber) / thirdNumber) * forthNumber; 14 | System.out.println(result); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/Pokemon_10.java: -------------------------------------------------------------------------------- 1 | package dataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Pokemon_10 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //1. входни данни 10 | int power = Integer.parseInt(scanner.nextLine()); //текуща сила (N) 11 | int startPower = power; //първоначалната сила 12 | int distance = Integer.parseInt(scanner.nextLine()); //разстоянието между целите (M) 13 | int factor = Integer.parseInt(scanner.nextLine()); //фактор на изтощение (Y) 14 | 15 | //повтаряме: 16 | //1. power - distance -> стигаме до целта си 17 | //2. намушкваме целта 18 | //стоп: power < distance 19 | //продължава: power >= distance 20 | 21 | int count = 0; //брой намушканите 22 | while (power >= distance) { 23 | //1. отивам до целта -> намаляваме силата с изминатото разстояние 24 | power -= distance; //power = power - distance; 25 | //2. наушкваме целта 26 | count++; 27 | 28 | //проверка за умора 29 | if (power == startPower / 2) { //if (power == startPower / 2 && factor != 0) 30 | //текущата сила / фактор 31 | boolean isDivisible = factor != 0; 32 | //isDivisible = true -> можем да извършим делението 33 | //isDivisible = false -> не можем да извършим делението 34 | if (isDivisible) { 35 | //възможна аритметична операция (деление) 36 | power = power / factor; //power /= factor; 37 | } 38 | } 39 | } 40 | 41 | System.out.println(power); 42 | System.out.println(count); 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/PrintPart_05.java: -------------------------------------------------------------------------------- 1 | package DataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PrintPart_05 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | int startCode = Integer.parseInt(scanner.nextLine()); //код, от който започвам 10 | int endCode = Integer.parseInt(scanner.nextLine()); // код, в който трябва да приключа 11 | 12 | //повтаряме: печатам кой е символа срещу съответния код 13 | //начало: startCode 14 | //край: endCode 15 | //промяна: +1 (преминавам към следващия код) 16 | 17 | for (int code = startCode; code <= endCode; code++) { 18 | System.out.print((char) code + " "); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/Snowballs_11.java: -------------------------------------------------------------------------------- 1 | package DataTypes; 2 | 3 | 4 | import java.util.*; 5 | 6 | public class Snowballs_11 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | int n = Integer.parseInt(scanner.nextLine()); 10 | double maxValue = Double.MIN_VALUE; 11 | int snowballSnowBiggest = 0; 12 | int snowballTTimeBiggest = 0; 13 | int snowballQualityBiggest = 0; 14 | 15 | 16 | for (int snowBall = 1; snowBall <= n; snowBall++) { 17 | int snowBallSnow = Integer.parseInt(scanner.nextLine()); 18 | int snowBallTime = Integer.parseInt(scanner.nextLine()); 19 | int snowBallQuality = Integer.parseInt(scanner.nextLine()); 20 | double snowBallValue = Math.pow(snowBallSnow / snowBallTime, snowBallQuality); 21 | 22 | if (snowBallValue > maxValue){ 23 | maxValue = snowBallValue; 24 | snowballSnowBiggest = snowBallSnow; 25 | snowballTTimeBiggest = snowBallTime; 26 | snowballQualityBiggest = snowBallQuality; 27 | } 28 | 29 | } 30 | System.out.printf("%d : %d = %.0f (%d) ",snowballSnowBiggest, snowballTTimeBiggest, maxValue ,snowballQualityBiggest ); 31 | 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/SpiceMustFlow_09.java: -------------------------------------------------------------------------------- 1 | package DataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SpiceMustFlow_09 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int source = Integer.parseInt(scanner.nextLine()); //бр. подправки в полето 9 | //повтаряме всеки ден -> добив = yield - 26; намалям силата на полето с 10 10 | //стоп: бр. подправки в полето < 100 11 | //продължаваме: бр. подправки в полето >= 100 12 | 13 | int days = 0; //бр дни добив 14 | int totalAmountSpices = 0; //общо количество добити подправки 15 | while (source >= 100) { 16 | int spices = source - 26; //добив 17 | totalAmountSpices += spices; 18 | days++; 19 | source = source - 10; 20 | } 21 | 22 | System.out.println(days); 23 | //изяждат 26 подправки при пътуването до другата нива 24 | if (totalAmountSpices >= 26) { 25 | totalAmountSpices -= 26; 26 | } 27 | System.out.println(totalAmountSpices); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/SumDigits_02.java: -------------------------------------------------------------------------------- 1 | package dataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SumDigits_02 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int number = Integer.parseInt(scanner.nextLine()); 9 | int sum = 0; //сума от цифрите 10 | 11 | //повтаряме: 12 | //1. взимаме последната цифра 13 | //2. сумираме 14 | //3. премахваме последната цифра 15 | //стоп: число <= 0 нямам повече цифри 16 | //продължаваме: число > 0 17 | 18 | while (number > 0) { 19 | int lastDigit = number % 10; 20 | sum += lastDigit; 21 | number /= 10; 22 | } 23 | 24 | System.out.println(sum); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/SumDigits_For_02.java: -------------------------------------------------------------------------------- 1 | package dataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SumDigits_For_02 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | int number = Integer.parseInt(scanner.nextLine()); 10 | int sum = 0; //сума от цифрите 11 | 12 | //1. int -> String 13 | //2. всички символи (цифри) 14 | //позиции от 0 до последната 15 | 16 | String numberAsString = "" + number; // "" + 543 = "543" -> String.valueOf(number) 17 | for (int position = 0; position <= numberAsString.length() - 1; position++) { 18 | char currentSymbol = numberAsString.charAt(position); //'5' 19 | //char -> String -> int 20 | //'5' -> 5 21 | int currentDigit = Integer.parseInt(currentSymbol + ""); 22 | sum += currentDigit; 23 | } 24 | 25 | System.out.println(sum); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/SumOfChars_04.java: -------------------------------------------------------------------------------- 1 | package dataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SumOfChars_04 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | int n = Integer.parseInt(scanner.nextLine()); //брой на символи 10 | 11 | //за всеки символ от първия до последния поватаряме: 12 | //1. прочитам стойността на символа от конзолата 13 | //2. сумирам аски кода на символа 14 | 15 | int sum = 0; //сума от аски кодовете на символите 16 | for (int count = 1; count <= n; count++) { 17 | char symbol = scanner.nextLine().charAt(0);//въведения символ 18 | sum += symbol; 19 | } 20 | 21 | System.out.println("The sum equals: " + sum); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/TripletsOfLetters_06.java: -------------------------------------------------------------------------------- 1 | package dataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TripletsOfLetters_06 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int n = Integer.parseInt(scanner.nextLine()); 9 | 10 | for (char letter1 = 'a'; letter1 < 'a' + n; letter1++) { //първата буква в тройката 11 | for (char letter2 = 'a'; letter2 < 'a' + n; letter2++) { //втората буква в тройката 12 | for (char letter3 = 'a'; letter3 < 'a' + n; letter3++) { //третата буква в тройката 13 | //{letter1}{letter2}{letter3} 14 | System.out.printf("%c%c%c%n", letter1, letter2, letter3); 15 | } 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Solutions/WaterOverflow_07.java: -------------------------------------------------------------------------------- 1 | package DataTypes; 2 | 3 | import java.util.Scanner; 4 | 5 | public class WaterOverflow_07 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int capacity = 255; 9 | int currentLiters = 0; 10 | int n = Integer.parseInt(scanner.nextLine()); 11 | for (int i = 1; i <= n; i++) { 12 | int pouredLiters = Integer.parseInt(scanner.nextLine()); 13 | currentLiters += pouredLiters; 14 | if(currentLiters > capacity) { 15 | System.out.println("Insufficient capacity!"); 16 | currentLiters -= pouredLiters; 17 | } 18 | } 19 | 20 | System.out.println(currentLiters); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /02. Data Types and Variables/Videos/DataTypesAndVariables_Videos.txt: -------------------------------------------------------------------------------- 1 | 07. Water Overflow -> https://pastebin.com/g3PJh8jQ 2 | видео: https://youtu.be/bMZkPePJ1Dw 3 | 4 | 11. Snowballs -> https://pastebin.com/9tkTBQx1 5 | видео: https://youtu.be/2fzK6GqGbkg 6 | 7 | 01. Data Type Finder (More Exercises) -> https://pastebin.com/tLbKDUzJ 8 | видео: https://youtu.be/vlDS4DD1Q4s 9 | 10 | 09. Spice Must Flow -> https://pastebin.com/2Nfzfgix 11 | видео: https://softuni.bg/trainings/resources/video/72245/video-27-may-2022-desislava-topuzakova-programming-fundamentals-with-java-may-2022/3731 12 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/ArrayModifier_09.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class ArrayModifier_09 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | int [] numbers = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray(); 10 | 11 | //повтарящо се действие: въвеждаме команди 12 | //стоп: входни данни == "end" 13 | //продължаваме: входни данни != "end" 14 | String command = scanner.nextLine(); 15 | 16 | while (!command.equals("end")) { 17 | //command != "end" -> валидна команда от условието 18 | if (command.contains("swap")) { 19 | //моята команда е swap: command == "swap 2 4".split(" ") -> ["swap", "2", "4"] 20 | int index1 = Integer.parseInt(command.split(" ")[1]); //parse("2") -> 2 21 | int index2 = Integer.parseInt(command.split(" ")[2]); //parse("4") -> 4 22 | 23 | int firstIndexNumber = numbers[index1]; 24 | int secondIndexNumber = numbers[index2]; 25 | 26 | numbers[index1] = secondIndexNumber; 27 | numbers[index2] = firstIndexNumber; 28 | 29 | } else if (command.contains("multiply")) { 30 | //моята команда е multiply: command = "multiply 3 6".split(" ") -> ["multiply", "3", "6"] 31 | int index1 = Integer.parseInt(command.split(" ")[1]); //parse("2") -> 2 32 | int index2 = Integer.parseInt(command.split(" ")[2]); //parse("4") -> 4 33 | 34 | int firstIndexNumber = numbers[index1]; 35 | int secondIndexNumber = numbers[index2]; 36 | 37 | int product = firstIndexNumber * secondIndexNumber; 38 | numbers[index1] = product; 39 | 40 | } else if (command.equals("decrease")) { 41 | //моята команда е decrease: command == "decrease" 42 | //обхождаме всички елементи -> -1 43 | for (int index = 0; index <= numbers.length - 1; index++) { 44 | numbers[index]--; 45 | //numbers[index] -= 1; 46 | } 47 | } 48 | command = scanner.nextLine(); 49 | } 50 | 51 | //отпечатваме числата в масива разделени с ", " 52 | //[34, 56, 76, 87].toString() -> "[34, 56, 76, 87]" 53 | 54 | //1-ви начин 55 | /* System.out.println(Arrays.toString(numbers) //"[34, 56, 76, 87]" 56 | .replace("[", "") //"34, 56, 76, 87]" 57 | .replace("]", "")); //"34, 56, 76, 87" 58 | */ 59 | 60 | //2-ри начин 61 | //след всяко число то масива слагаме ", ", без след последното 62 | for (int index = 0; index <= numbers.length - 1; index++) { 63 | int currentNumber = numbers[index]; 64 | if (index != numbers.length - 1) { 65 | System.out.print(currentNumber + ", "); 66 | } else { //index == numbers.length - 1 67 | //последния индекс -> последното число в масива 68 | System.out.print(currentNumber); 69 | } 70 | } 71 | 72 | 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/ArrayRotation_04.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ArrayRotation_04 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | //1. входни данни 9 | String [] array = scanner.nextLine() // "51 47 32 61 21" 10 | .split(" "); //["51", "47", "32", "61", "21"] 11 | int countRotation = Integer.parseInt(scanner.nextLine()); 12 | 13 | for (int rotation = 1; rotation <= countRotation; rotation++) { 14 | //ротация на масив 15 | //1. взимаме първия елемент 16 | String firstElement = array[0]; //"51" 17 | 18 | //2. преместване на елементите наляво 19 | //["51", "47", "32", "61", "21"] -> ["47", "32", "61", "21", "21"] 20 | for (int index = 0; index < array.length - 1; index++) { 21 | array[index] = array[index + 1]; 22 | } 23 | 24 | //3. поставям първия елемент на последно място 25 | //["47", "32", "61", "21", "51"] 26 | array[array.length - 1] = firstElement; 27 | } 28 | 29 | //приключваме с ротациите -> принтираме елементите на масива 30 | /*for (String element : array) { 31 | System.out.print(element + " "); 32 | }*/ 33 | //["47", "32", "61", "21", "51"] -> "47 32 61 21 51" 34 | System.out.println(String.join(" ", array)); //работи само за масив от текстове 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/CommonElements_02.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CommonElements_02 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | //1. входни данни 9 | 10 | String [] firstArray = scanner.nextLine().split("\\s+"); // "Hey hello 2 4" -> ["Hey", "hello", "2", "4"] 11 | String [] secondArray = scanner.nextLine().split(" "); //"10 hey 4 hello" -> ["10", "hey", "4", "hello"] 12 | 13 | //за всеки елемент на втория масив -> проверка дали го има в първия масив 14 | for (String el2 : secondArray) { 15 | for (String el1 : firstArray) { 16 | if (el2.equals(el1)) { 17 | System.out.print(el1 + " "); 18 | } 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/EqualsSums_06.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class EqualsSums_06 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | int [] numbers = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray(); 11 | 12 | for (int index = 0; index <= numbers.length - 1; index++) { 13 | int currentNumber = numbers[index]; 14 | 15 | int leftSum = 0; //сума на елементите в ляво 16 | int rightSum = 0; //сума на елементите в дясно 17 | 18 | //1. намеря сумата на елементите в ляво 19 | //лява сума: всички елементи от първия (0) до моя (не вкл.) 20 | for (int leftIndex = 0; leftIndex < index; leftIndex++) { 21 | leftSum += numbers[leftIndex]; 22 | } 23 | 24 | //2. намеря сумата на елементие в дясно 25 | //дясна сума: всички елементи след моя и до последния 26 | for (int rightIndex = index + 1; rightIndex <= numbers.length - 1; rightIndex++) { 27 | rightSum += numbers[rightIndex]; 28 | } 29 | 30 | //3. проверка дали са равни двете суми -> имам намерено число 31 | if (leftSum == rightSum) { 32 | System.out.println(index); 33 | return; //прекратява цялата програма 34 | } 35 | } 36 | 37 | //обходили всички числа и нито едно не е отговаряло на условието 38 | System.out.println("no"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/MagicSum_08.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class MagicSum_08 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | int [] numbers = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray(); 11 | int targetSum = Integer.parseInt(scanner.nextLine()); 12 | 13 | //обхождаме всички числа от масива 14 | for (int index = 0; index <= numbers.length - 1; index++) { 15 | int currentNumber = numbers[index]; //текущото число 16 | //обхождам всички числа след него 17 | for (int i = index + 1; i <= numbers.length - 1; i++) { //всички числа след моето 18 | int nextNumber = numbers[i]; //число, което е след моето 19 | 20 | if (currentNumber + nextNumber == targetSum) { 21 | System.out.println(currentNumber + " " + nextNumber); 22 | } 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/MaxSequenceEqualElements_07.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | 6 | public class MaxSequenceEqualElements_07 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | int [] array = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(e -> Integer.parseInt(e)).toArray(); 11 | int maxLength = 0; 12 | int length = 1; 13 | 14 | int startIndex = 0; 15 | int bestStart = 0; 16 | 17 | for (int i = 1; i < array.length; i++) { 18 | if(array[i] == array[i - 1]) { 19 | length++; 20 | } else { 21 | length = 1; 22 | startIndex = i; 23 | } 24 | 25 | if(length > maxLength) { 26 | maxLength = length; 27 | bestStart = startIndex; 28 | } 29 | } 30 | 31 | for (int i = bestStart; i < bestStart + maxLength; i++) { 32 | System.out.print(array[i] + " "); 33 | } 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/TopIntegers_05.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class TopIntegers_05 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | //1. входни данни 11 | int [] numbers = Arrays.stream(scanner.nextLine() // "1 4 3 2" 12 | .split(" ")) //["1", "4", "3", "2"] 13 | .mapToInt(Integer::parseInt) //[1, 4, 3, 2] 14 | .toArray(); 15 | 16 | //!!! последния елемент винаги е топ число -> отпечатваме 17 | for (int index = 0; index < numbers.length - 1; index++) { 18 | //всички числа без последното и ги проверяваме дали са топ числа 19 | int currentNumber = numbers[index]; //число на текущия индекс 20 | 21 | boolean isBigger = true; 22 | //true -> текущото число е по-голямо от всички в дясно 23 | //false -> текущото число не е по-голямо 24 | 25 | for (int i = index + 1; i <= numbers.length - 1; i++) { 26 | //всички елементи след моя до последния включително 27 | int numberAfter = numbers[i]; 28 | if (currentNumber <= numberAfter) { 29 | isBigger = false; 30 | break; 31 | //моето число е по-малко от някое след него 32 | } 33 | } 34 | 35 | if (isBigger) { 36 | //моето число винаги е било по-голямо от числото след него 37 | //топ число 38 | System.out.print(currentNumber + " "); 39 | } 40 | 41 | } 42 | 43 | //винаги отпечатваме последното число, защото то е топ число без да го проверяваме 44 | System.out.print(numbers[numbers.length - 1]); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/Train_01.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class Train_01 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | int countWagons = Integer.parseInt(scanner.nextLine()); 10 | //1. съхраним хората, които се качват 11 | int [] wagons = new int[countWagons]; 12 | for (int wagon = 0; wagon < countWagons; wagon++) { 13 | int countPeople = Integer.parseInt(scanner.nextLine()); 14 | wagons[wagon] = countPeople; 15 | } 16 | //[13, 24, 8] 17 | //2. отпечатаме 18 | //2.1. for -> индексите 19 | /*for (int index = 0; index <= wagons.length - 1; index++) { 20 | int currentElement = wagons[index]; 21 | System.out.print(currentElement + " "); 22 | } 23 | System.out.println();*/ 24 | 25 | //2.2. foreach -> елементите 26 | int sum = 0; 27 | for (int number : wagons) { 28 | //кодът, който искаме да повтаряме 29 | System.out.print(number + " "); 30 | sum += number; 31 | } 32 | System.out.println(); 33 | System.out.println(sum); 34 | //3. сумираме хората 35 | //System.out.println(Arrays.stream(wagons).sum()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/TreasureHunt_10.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TreasureHunt_10 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | String [] loots = scanner.nextLine().split("\\|"); 9 | //"Gold|Silver|Bronze|Medallion|Cup".split("|") -> ["Gold", "Silver", "Bronze", "Medallion", "Cup"] 10 | 11 | String command = scanner.nextLine(); //цялата команда, въведена от конзолата 12 | 13 | while (!command.equals("Yohoho!")) { 14 | //command = "Loot {item1} {item2}…{itemn}".split -> ["Loot", "itrem1", "item2", ...] 15 | 16 | //command = "Steal 2".split -> ["Steal", "2"] 17 | String[] commandParts = command.split(" "); //частите на командата 18 | String commandName = commandParts[0]; //име на команда: Loot, Drop, Steal 19 | 20 | switch (commandName) { 21 | case "Loot": 22 | break; 23 | case "Drop": 24 | //command = "Drop 4".split -> commandParts = ["Drop", "4"] 25 | int dropIndex = Integer.parseInt(commandParts[1]); //"4" -> 4 26 | //проверка на индекс 27 | if(dropIndex < 0 || dropIndex >= loots.length - 1) { 28 | //невалиден индекс -> индекс, на който нямаме елемент 29 | break; 30 | } else{ 31 | //валиден индекс 32 | //1. взимаме елемента за преместване 33 | String currentLoot = loots[dropIndex]; 34 | //2. премествам на ляво всички елементи след моя 35 | for (int leftIndex = dropIndex; leftIndex < loots.length - 1; leftIndex++) { 36 | loots[leftIndex] = loots[leftIndex + 1]; 37 | } 38 | //3. слагаме накрая елемента за преместване 39 | loots[loots.length - 1] = currentLoot; 40 | } 41 | break; 42 | case "Steal": 43 | break; 44 | } 45 | 46 | command = scanner.nextLine(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /03. Arrays/Solutions/ZigZagArrays_3.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ZigZagArrays_3 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); //sc 8 | 9 | int n = Integer.parseInt(scanner.nextLine()); //брой редове 10 | int [] firstArray = new int[n]; 11 | int [] secondArray = new int[n]; 12 | 13 | for (int row = 1; row <= n; row++) { 14 | String numbers = scanner.nextLine(); //"1 5".split(" ") -> ["1", "5"] 15 | int firstNumber = Integer.parseInt(numbers.split(" ")[0]); //"1" -> 1 16 | int secondNumber = Integer.parseInt(numbers.split(" ")[1]); //"5" -> 5 17 | 18 | if (row % 2 == 0) { 19 | //четен ред -> първото число (втори масив); второто число (първи масив) 20 | firstArray[row - 1] = secondNumber; 21 | secondArray[row - 1] = firstNumber; 22 | } else { 23 | //нечетен ред -> първото число (първи масив); второто число (втори масив) 24 | firstArray[row - 1] = firstNumber; 25 | secondArray[row - 1] = secondNumber; 26 | } 27 | } 28 | 29 | //отпечатваме елементите на първия масив 30 | for (int number : firstArray) { 31 | System.out.print(number + " "); 32 | } 33 | 34 | System.out.println(); 35 | 36 | //отпечатваме елементите на втория масив 37 | for (int number : secondArray) { 38 | System.out.print(number + " "); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /03. Arrays/Videos/Arrays - Exercise - Videos.txt: -------------------------------------------------------------------------------- 1 | 07. Max Sequence of Equal Elements -> https://pastebin.com/fiudHYva 2 | видео: https://youtu.be/Po6e3xLR_k8 3 | 4 | 10. Lady Bugs: https://youtu.be/gH7P3RXPTXQ -------------------------------------------------------------------------------- /04. Methods/Solutions/AddAndSubtract_05.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class AddAndSubtract_05 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | //1. входни данни -> 3 цели числа 9 | int firstNumber = Integer.parseInt(scanner.nextLine()); 10 | int secondNumber = Integer.parseInt(scanner.nextLine()); 11 | int thirdNumber = Integer.parseInt(scanner.nextLine()); 12 | //(firstNumber + secondNumber) - thirdNumber 13 | System.out.println(subtract(firstNumber, secondNumber, thirdNumber)); 14 | 15 | } 16 | 17 | //метод, който сумира две цели числа и връща сумата 18 | public static int sum (int n1, int n2) { 19 | return n1 + n2; 20 | } 21 | 22 | //метод, който ще извади от сумата на две числа третото и връща резултат 23 | public static int subtract (int n1, int n2, int n3) { 24 | return sum(n1, n2) - n3; 25 | } 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /04. Methods/Solutions/CharactersInRange_03.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CharactersInRange_03 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | char firstSymbol = scanner.nextLine().charAt(0); //"a".charAt(0) -> 'a' 10 | char secondSymbol = scanner.nextLine().charAt(0); 11 | 12 | printSymbolsInRange(firstSymbol, secondSymbol); 13 | 14 | } 15 | 16 | //метод, който отпечатва символите в даден диапазон 17 | public static void printSymbolsInRange (char firstSymbol, char secondSymbol) { 18 | //започваме от символа с по-малък аски код 19 | //проверка кой е по-малкия символ -> започвам от по-малкия 20 | 21 | if (firstSymbol < secondSymbol) { 22 | //започвам от firstSymbol -> символите в (firstSymbol; secondSymbol) 23 | for (char symbol = (char) (firstSymbol + 1); symbol < secondSymbol; symbol++) { 24 | System.out.print(symbol + " "); 25 | } 26 | } else { //firstSymbol >= secondSymbol 27 | //започваме от secondSymbol -> символи в (secondSymbol; firstSymbol) 28 | for (char symbol = (char) (secondSymbol + 1); symbol < firstSymbol; symbol++) { 29 | System.out.print(symbol + " "); 30 | } 31 | 32 | } 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /04. Methods/Solutions/FactorialDivision_08.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class FactorialDivision_08 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //1. входни данни -> 2 числа 10 | int firstNumber = Integer.parseInt(scanner.nextLine()); 11 | int secondNumber = Integer.parseInt(scanner.nextLine()); 12 | 13 | //2. факториел на първото число 14 | long factFirstNumber = calculateFactorial(firstNumber); 15 | 16 | //3. факториел на второто число 17 | long factSecondNumber = calculateFactorial(secondNumber); 18 | 19 | //4. ф1 / ф2 = дробно число -> %.2f 20 | double result = factFirstNumber * 1.0 / factSecondNumber; 21 | System.out.printf("%.2f", result); 22 | } 23 | 24 | //метод, който връща резултат (факториел на дадено число) 25 | //!!! изчисленият факториел може да бъде много голямо число!!! 26 | public static long calculateFactorial (int number) { 27 | //number = 7 28 | //7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 29 | long fact = 1; //стойността на факториел 30 | for (int i = 1; i <= number; i++) { 31 | fact = fact * i; 32 | } 33 | 34 | return fact; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /04. Methods/Solutions/MiddleCharacters_06.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class MiddleCharacters_06 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | String text = scanner.nextLine(); 10 | 11 | printMiddleCharacters(text); 12 | } 13 | 14 | //метод, който принтира средния символ 15 | public static void printMiddleCharacters (String text) { 16 | int length = text.length(); 17 | //нечетна дължина -> 1 среден символ 18 | if (length % 2 != 0) { 19 | //"aString" -> ['a', 'S', 't', 'r', 'i', 'n', 'g'] 20 | int indexOfMiddleCharacter = length / 2; 21 | System.out.println(text.charAt(indexOfMiddleCharacter)); 22 | } 23 | //четна дължина -> 2 средни символа 24 | else { 25 | //"someText" -> 8 символа -> eT (index: 3 и 4) 26 | //"dogs" -> 4 символа -> og (index: 1 и 2) 27 | int indexFirstMiddleCharacter = length / 2 - 1; 28 | int indexSecondMiddleCharacter = length / 2; 29 | 30 | System.out.print(text.charAt(indexFirstMiddleCharacter)); 31 | System.out.print(text.charAt(indexSecondMiddleCharacter)); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /04. Methods/Solutions/NxNMatrix_07.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class NxNMatrix_07 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int n = Integer.parseInt(scanner.nextLine()); //брой редове = брой колони 9 | printMatrix(n); 10 | } 11 | 12 | public static void printMatrix(int n) { 13 | for (int row = 1; row <= n; row++) { 14 | for (int col = 1; col <= n; col++) { 15 | System.out.print(n + " "); 16 | } 17 | System.out.println(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /04. Methods/Solutions/PalindromeIntegers_09.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PalindromeIntegers_09 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | String input = scanner.nextLine(); 10 | 11 | while (!input.equals("END")) { 12 | //input = "3456" 13 | //проверка дали въведения текст е палиндром 14 | System.out.println(checkPalindrome(input)); 15 | input = scanner.nextLine(); 16 | } 17 | } 18 | 19 | //метод, който проверява дали даден тескт е палиндром 20 | //true -> текстът е палиндром 21 | //false -> текстът не е палиндром 22 | public static boolean checkPalindrome (String text) { 23 | //text = "Desi" 24 | //reversedText = "iseD" 25 | //палиндром е всеки текст, кой е еднакъв с обърнатия си на обратно 26 | 27 | String reversedText = ""; //текстът, обърнат на обратно 28 | for (int index = text.length() - 1; index >= 0; index--) { 29 | reversedText += text.charAt(index); 30 | } 31 | 32 | return text.equals(reversedText); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /04. Methods/Solutions/PasswordValidator_04.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PasswordValidator_04 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | String password = scanner.nextLine(); 9 | 10 | //1. проверим дали дължината на паролата е валидна 11 | boolean isValidLength = isValidLength(password); 12 | //isValidLength = true -> валидна парола 13 | //isValidLength = false -> невалидна парола 14 | if (!isValidLength) { 15 | //паролата не е валидна 16 | System.out.println("Password must be between 6 and 10 characters"); 17 | } 18 | 19 | //2. проверим дали съдържанието е валидно 20 | boolean isValidContent = isValidContent(password); 21 | //isValidContent = true -> валидно съдържание 22 | //isValidContent = false -> невалидно съдържание 23 | if (!isValidContent) { 24 | System.out.println("Password must consist only of letters and digits"); 25 | } 26 | 27 | //3. проверим дали брой на цифрите е валиден 28 | boolean isValidCount = isValidCountDigits(password); 29 | //isValidCount = true -> валиден брой 30 | //isValidCount = false -> невалиден брой 31 | if (!isValidCount) { 32 | System.out.println("Password must have at least 2 digits"); 33 | } 34 | 35 | //4. проверяваме дали цялостно е валидна паролата 36 | if (isValidLength && isValidContent && isValidCount) { 37 | System.out.println("Password is valid"); 38 | } 39 | 40 | } 41 | 42 | //метод, който проверява дали ми е валидна дължината на паролата 43 | //true -> ако дължината на паролата е валидна 44 | //false -> ако дължината на паролата не е валидна 45 | public static boolean isValidLength (String password) { 46 | //валидна дължина: [6; 10] 47 | //невалидна дължина: < 6 или > 10 48 | return password.length() >= 6 && password.length() <= 10; 49 | } 50 | 51 | //метод, който проверява дали ми е валидно съдържанието на паролата 52 | //true -> ако съдържанието е валидно 53 | //false -> ако съдържанието не е валидно 54 | public static boolean isValidContent (String password) { 55 | //password = "logIn".toCharArray() -> ['l', 'o', 'g', 'I', 'n'] 56 | //валидно съдържание: букви или цифри 57 | //невалидно съдържание: нещо различно от буква или цифра 58 | for (char symbol : password.toCharArray()) { 59 | if (!Character.isLetterOrDigit(symbol)) { 60 | //isLetterOrDigit 61 | //true ако символа е буква или цифра 62 | //false ако символа не е нито буква, нито цифра 63 | return false; 64 | } 65 | } 66 | //обходили всички символи 67 | return true; 68 | } 69 | 70 | //метод, който проверява дали е валиден броя на цифрите в паролата 71 | //true -> ако броят е валиден >= 2 72 | //false -> ако броят е невалиден < 2 73 | public static boolean isValidCountDigits (String password) { 74 | int countDigits = 0; //брой на цифрите в паролата 75 | //password = "Pesho123".toCharArray() 76 | for (char symbol : password.toCharArray()) { 77 | if (Character.isDigit(symbol)) { 78 | //isDigit 79 | //true -> ако символа е цифра 80 | //false -> ако символа не е цифра 81 | countDigits++; 82 | } 83 | } 84 | //true -> брой >= 2 85 | //false -> брой < 2 86 | return countDigits >= 2; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /04. Methods/Solutions/SmallestOfThreeNumbers_01.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SmallestOfThreeNumbers_01 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | int firstNumber = Integer.parseInt(scanner.nextLine()); 10 | int secondNumber = Integer.parseInt(scanner.nextLine()); 11 | int thirdNumber = Integer.parseInt(scanner.nextLine()); 12 | 13 | printSmallestNumber(firstNumber, secondNumber, thirdNumber); 14 | 15 | } 16 | 17 | //метод, който принтира най-малкото от три зададени числa 18 | public static void printSmallestNumber (int n1, int n2, int n3) { 19 | if (n1 <= n2 && n1 < n3) { 20 | //първото да е най-малко 21 | System.out.println(n1); 22 | } else if (n2 <= n1 && n2 < n3) { 23 | //второто да е най-малко 24 | System.out.println(n2); 25 | } else { 26 | //третото да е най-малко 27 | System.out.println(n3); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /04. Methods/Solutions/TopNumber_10.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TopNumber_10 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int n = Integer.parseInt(scanner.nextLine()); 9 | 10 | for (int number = 8; number <= n; number++) { 11 | //проверка дали е топ 12 | //1. сумата от цифрите му да се дели на 8 -> checkSumDigitsIsDivisibleBy8 13 | //2. съдържа поне една нечетна цифра -> checkContainsOddDigit 14 | boolean isValidSumDigits = checkSumDigitsIsDivisibleBy8(number); 15 | if (isValidSumDigits) { 16 | boolean isContainsOddDigit = checkContainsOddDigit(number); 17 | if (isContainsOddDigit) { 18 | //топ число 19 | System.out.println(number); 20 | } 21 | } 22 | } 23 | } 24 | 25 | //метод, който проверява дали сумата от цифрите на числото се дели на 8 26 | //true -> сумата се дели на 8 27 | //false -> сумата не се дели на 8 28 | public static boolean checkSumDigitsIsDivisibleBy8 (int num) { 29 | //1. сума от цифрите на числото 30 | int sum = 0; //сума от цифрите 31 | while (num > 0) { 32 | int lastDigit = num % 10; //последна цифра 33 | sum += lastDigit; //сумираме последна цифра 34 | num = num / 10; //премахваме последната цифра 35 | } 36 | //2. проверка дали сумата се дели на 8 37 | return sum % 8 == 0; 38 | 39 | /*if (sum % 8 == 0){ 40 | return true; 41 | } else { 42 | return false; 43 | }*/ 44 | } 45 | 46 | //метод, който проверява дали имаме поне една нечетна цифра в числото 47 | //true -> ако имаме поне една нечетна цифра 48 | //false -> ако нямаме нито една нечетна цифра 49 | public static boolean checkContainsOddDigit (int number) { 50 | //3657 51 | while (number > 0) { 52 | int lastDigit = number % 10; //последна цифра 53 | if (lastDigit % 2 != 0) { 54 | //нечетна цифра -> поне една нечетна 55 | return true; 56 | } else { 57 | //четна цифра -> премахваме 58 | number = number / 10; 59 | } 60 | } 61 | //проверили всички цифри и никоя не е била нечетна 62 | return false; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /04. Methods/Solutions/VowelsCount_02.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class VowelsCount_02 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | String text = scanner.nextLine().toLowerCase(); 10 | //"Test".toLowerCase() -> "test" 11 | //"ElizA".toLowerCase() -> "eliza" 12 | 13 | printCountVowels(text); 14 | 15 | } 16 | 17 | //метод, който отпечатва брой на малките гласни букви в текста 18 | public static void printCountVowels (String text) { 19 | int count = 0; //брой гласните букви 20 | //text = "eliza".toCharArray() -> ['e', 'l', 'i', 'z', 'a'] 21 | for (char symbol : text.toCharArray()) { 22 | //гласни букви: a, e, i, o, u 23 | if (symbol == 'a' || symbol == 'e' || symbol == 'i' || symbol == 'o' || symbol == 'u') { 24 | count++; 25 | } 26 | } 27 | System.out.println(count); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /04. Methods/Videos/Methods - Videos.txt: -------------------------------------------------------------------------------- 1 | 04. Password Validator -> https://youtu.be/ZY-yP8Epv8w?t=5398 2 | -------------------------------------------------------------------------------- /05. Lists/Solutions/AnonymousThreat_08.java: -------------------------------------------------------------------------------- 1 | package Lists_Exercise; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.stream.Collectors; 7 | 8 | public class AnonymousThreat_08 { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | List texts = Arrays.stream(scanner.nextLine().split("\\s+")) //["Ivo", "Johny", "Tony", "Bony", "Mony"] 13 | .collect(Collectors.toList()); //{"Ivo", "Johny", "Tony", "Bony", "Mony"} 14 | 15 | String command = scanner.nextLine(); 16 | 17 | while (!command.equals("3:1")) { 18 | if (command.contains("merge")) { 19 | //command = "merge {startIndex} {endIndex}" 20 | int startIndex = Integer.parseInt(command.split(" ")[1]); 21 | int endIndex = Integer.parseInt(command.split(" ")[2]); 22 | 23 | //проверка startIndex 24 | if (startIndex < 0) { 25 | startIndex = 0; 26 | } 27 | 28 | //проверка за endIndex 29 | if (endIndex > texts.size() - 1) { 30 | endIndex = texts.size() - 1; 31 | } 32 | 33 | //валидиране на индексите -> [0, дълж - 1] 34 | if (startIndex >= 0 && startIndex <= texts.size() - 1 && endIndex >= 0 && endIndex <= texts.size() - 1) { 35 | //валидни индекси -> преминем към изпълняване на командата 36 | //{"Ivo", "Johny", "Tony", "Bony", "Mony"} 37 | //merge 1 3 38 | //взимаме елементите и ги обединяваме 39 | String resultMerge = ""; //резултат от обединението на елементите 40 | for (int index = startIndex; index <= endIndex; index++) { 41 | String current = texts.get(index); 42 | resultMerge += current; 43 | } 44 | 45 | //resulMerge = "JohnyTonyBony" 46 | //премахваме обединените елементи 47 | for (int index = startIndex; index <= endIndex; index++) { 48 | texts.remove(startIndex); 49 | } 50 | //{"Ivo", "Mony"} 51 | 52 | //добавяме обединението на startIndex 53 | texts.add(startIndex, resultMerge); 54 | //{"Ivo", "JohnyTonyBony", "Mony"} 55 | } 56 | } else if (command.contains("divide")) { 57 | //command = "divide {index} {partitions}" 58 | int index = Integer.parseInt(command.split(" ")[1]); 59 | int parts = Integer.parseInt(command.split(" ")[2]); //брой на частите 60 | 61 | //валидираме индекса, от който ще взимаме текст 62 | if (index >= 0 && index <= texts.size() - 1) { 63 | //{"abcdef", "ghi", "jkl"} 64 | //divide 0 3 65 | String textForDivide = texts.get(index); //"abcdef" 66 | texts.remove(index); 67 | //{"ghi", "jkl"} 68 | 69 | //1. колко символа ще има всяка част 70 | int countSymbolsPerPart = textForDivide.length() / parts; 71 | 72 | //всички равни части без последната 73 | int beginIndex = 0; //index в текста за деление 74 | for (int part = 1; part < parts; part++) { 75 | String textPerPart = textForDivide.substring(beginIndex, beginIndex + countSymbolsPerPart); 76 | texts.add(index, textPerPart); 77 | index++; //място на поставяне на разбитата част в главния списък 78 | beginIndex += countSymbolsPerPart; 79 | } 80 | 81 | //последната част 82 | String textLastParts = textForDivide.substring(beginIndex, textForDivide.length()); 83 | texts.add(index, textLastParts); 84 | } 85 | 86 | } 87 | 88 | 89 | command = scanner.nextLine(); 90 | } 91 | 92 | //!!!!отпчетваме списък с тесктовете -> String.join!!! 93 | System.out.println(String.join(" ", texts)); 94 | 95 | /*for (String text : texts) { 96 | System.out.print(text + " "); 97 | }*/ 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /05. Lists/Solutions/AppendArrays_07.java: -------------------------------------------------------------------------------- 1 | package Lists_Exercise; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | import java.util.stream.Collectors; 8 | 9 | public class AppendArrays_07 { 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | String input = scanner.nextLine(); //"1 2 3 |4 5 6 | 7 8" 13 | List listSeparatedByPipe = Arrays.stream(input.split("\\|")).collect(Collectors.toList()); 14 | //"1 2 3 |4 5 6 | 7 8" -> split -> ["1 2 3 ", "4 5 6 ", " 7 8"] -> {"1 2 3 ", "4 5 6 ", " 7 8"} 15 | Collections.reverse(listSeparatedByPipe); 16 | // reverse -> {" 7 8", "4 5 6 ", "1 2 3 "} 17 | 18 | //list.toString() -> "7 8 4 5 6 1 2 3" 19 | System.out.println(listSeparatedByPipe.toString() //"[ 7 8, 4 5 6 , 1 2 3 ]" 20 | .replace("[", "") //" 7 8, 4 5 6 , 1 2 3 ]" 21 | .replace("]", "") //" 7 8, 4 5 6 , 1 2 3 " 22 | .trim() //"7 8, 4 5 6 , 1 2 3" 23 | .replaceAll(",", "") //"7 8 4 5 6 1 2 3" 24 | .replaceAll("\\s+", " ")); //"7 8 4 5 6 1 2 3" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /05. Lists/Solutions/BombNumbers_05.java: -------------------------------------------------------------------------------- 1 | package Lists_Exercise; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.stream.Collectors; 7 | 8 | public class BombNumbers_05 { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | List elements = Arrays.stream(scanner.nextLine() 13 | .split("\\s+")) 14 | .collect(Collectors.toList()); 15 | 16 | String[] data = scanner.nextLine().split("\\s+"); 17 | String bombNumber = data[0]; 18 | int power = Integer.parseInt(data[1]); 19 | 20 | while (elements.contains(bombNumber)) { 21 | int elementIndex = elements.indexOf(bombNumber); 22 | 23 | int left = Math.max(0, elementIndex - power); 24 | int right = Math.min(elementIndex + power, elements.size() - 1); 25 | 26 | for (int i = right; i >= left; i--) { 27 | elements.remove(i); 28 | 29 | } 30 | } 31 | System.out.println(elements.stream().mapToInt(Integer::parseInt).sum()); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /05. Lists/Solutions/CardsGame_06.java: -------------------------------------------------------------------------------- 1 | package Lists_Exercise; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | import java.util.Scanner; 5 | import java.util.stream.Collectors; 6 | 7 | public class CardsGame_06 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | List firstPlayerCards = Arrays.stream(scanner.nextLine().split(" ")) 11 | .map(Integer::parseInt).collect(Collectors.toList()); 12 | //{20 30 40 50} 13 | List secondPlayerCards = Arrays.stream(scanner.nextLine().split(" ")) 14 | .map(Integer::parseInt).collect(Collectors.toList()); 15 | //{10 20 30 40} 16 | 17 | //1. взимам първата карта от ръката 18 | //2. премахвам картата от ръката 19 | //3. проверка кой печели: 20 | // карта 1 > карта 2 -> слагам накрая на ръката на първия -> карта 1 -> карта 2 21 | //карта 2 > карта 1 -> слагам накрая на ръката на втория -> карта 2 -> карта 1 22 | //карта 1 == карта 2 -> не ги добавяме никъде 23 | 24 | //играта продължава когато и двамата имат карти 25 | //играта спира, когато някой остане без карти 26 | 27 | while (firstPlayerCards.size() != 0 && secondPlayerCards.size() != 0) { 28 | int firstPlayerCard = firstPlayerCards.get(0); 29 | int secondPlayerCard = secondPlayerCards.get(0); 30 | firstPlayerCards.remove(0); 31 | secondPlayerCards.remove(0); 32 | 33 | if (firstPlayerCard > secondPlayerCard) { 34 | firstPlayerCards.add(firstPlayerCard); 35 | firstPlayerCards.add(secondPlayerCard); 36 | } else if (secondPlayerCard > firstPlayerCard) { 37 | secondPlayerCards.add(secondPlayerCard); 38 | secondPlayerCards.add(firstPlayerCard); 39 | } 40 | } 41 | 42 | //1. ако на първия му свършат картите 43 | if (firstPlayerCards.size() == 0) { 44 | //втория печели -> сума от картите на втория 45 | System.out.printf("Second player wins! Sum: %d", getCardsSum(secondPlayerCards)); 46 | } 47 | //2. ако на втория му свършат картите 48 | else if (secondPlayerCards.size() == 0) { 49 | //първия печели 50 | System.out.printf("First player wins! Sum: %d", getCardsSum(firstPlayerCards)); 51 | } 52 | } 53 | 54 | private static int getCardsSum(List listCards) { 55 | int sum = 0; 56 | for (int card : listCards) { 57 | sum += card; 58 | } 59 | 60 | return sum; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /05. Lists/Solutions/ChangeList_02.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.stream.Collectors; 7 | 8 | public class ChangeList_02 { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | //1. входни данни -> списък от цели числа 12 | List numbers = Arrays.stream(scanner.nextLine() //"1 2 3 4 5 5 5 6" 13 | .split(" ")) //["1", "2", "3", "4", "5", "5", "5", "6"] 14 | .map(Integer::parseInt) //[1, 2, 3, 4, 5, 5, 5, 6] 15 | .collect(Collectors.toList()); //{1, 2, 3, 4, 5, 5, 5, 6} 16 | 17 | //2. получаваме команди -> "end" 18 | String command = scanner.nextLine(); //"end" или валидна команда 19 | //repeat: въвеждаме нова команда 20 | //stop: command == "end" 21 | //continue: command != "end" 22 | while (!command.equals("end")) { 23 | //1. command = "Delete 4".split(" ") -> ["Delete", "4"] 24 | if (command.contains("Delete")) { 25 | int numberForRemove = Integer.parseInt(command.split(" ")[1]); //число, което ще премахваме 26 | //премахнем всички елементи в списъка, които са равни на numberForRemove 27 | numbers.removeAll(Arrays.asList(numberForRemove)); 28 | } 29 | //2. command = "Insert 3 1".split(" ") -> ["Insert", "3", "1"] 30 | else if (command.contains("Insert")) { 31 | //insert element at the given position 32 | int element = Integer.parseInt(command.split(" ")[1]); 33 | int position = Integer.parseInt(command.split(" ")[2]); 34 | numbers.add(position, element); 35 | } 36 | command = scanner.nextLine(); 37 | } 38 | 39 | //списък с числа -> печатаме -> {3, 4, 5, 6} 40 | for (int number : numbers) { 41 | System.out.print(number + " "); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /05. Lists/Solutions/HouseParty_03.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | 7 | public class HouseParty_03 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | List guestsList = new ArrayList<>(); //списък с гостите 11 | 12 | //1. входни данни 13 | int countCommands = Integer.parseInt(scanner.nextLine()); 14 | for (int count = 1; count <= countCommands; count++) { 15 | String command = scanner.nextLine(); 16 | String[] commandParts = command.split(" "); //брой думи на командата 17 | String name = commandParts[0]; //име на човека, който трябва да премахна / добавя 18 | if (command.contains("not")) { //commandPart.length == 4 19 | //command = "{name} is not going!".split(" ") -> ["{name}", "is", "not", "going!"] 20 | //премахваме от списъка 21 | //1. има такъв човек в списъка 22 | if (guestsList.contains(name)) { 23 | guestsList.remove(name); 24 | } 25 | //2. няма такъв човек в списъка 26 | else { 27 | System.out.println(name + " is not in the list!"); 28 | } 29 | } else { 30 | //command = "{name} is going!".split(" ") -> ["{name}", "is", "going!"] 31 | //добавяме към списъка 32 | //1. има такъв човек в списъка 33 | if (guestsList.contains(name)) { 34 | System.out.println(name + " is already in the list!"); 35 | } 36 | //2. няма такъв човек в списъка 37 | else { 38 | guestsList.add(name); 39 | } 40 | } 41 | } 42 | 43 | //списък с гостите 44 | for (String guestName : guestsList) { 45 | System.out.println(guestName); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /05. Lists/Solutions/ListOperations_04.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.stream.Collectors; 7 | 8 | public class ListOperations_04 { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | List numbers = Arrays.stream(scanner.nextLine() //"4 5 6 7 2 3" 13 | .split(" "))//["4", "5", "6", "7", "2", "3"] 14 | .map(Integer::parseInt)// [4, 5, 6, 7, 2, 3] 15 | .collect(Collectors.toList());// {4, 5, 6, 7, 2, 3} 16 | 17 | String command = scanner.nextLine(); 18 | 19 | while (!command.equals("End")) { 20 | String[] commandParts = command.split(" "); 21 | String commandName = commandParts[0]; //"Add", "Insert", "Remove", "Shift" 22 | switch (commandName) { 23 | case "Add": 24 | //command = "Add {number}".split(" ") -> ["Add", "{number}"] 25 | int numberToAdd = Integer.parseInt(commandParts[1]); 26 | numbers.add(numberToAdd); 27 | break; 28 | case "Insert": 29 | //command = "Insert {number} {index}".split(" ") -> ["Insert", "{number}", "{index}"] 30 | int numberForInsert = Integer.parseInt(commandParts[1]); 31 | int indexForInsert = Integer.parseInt(commandParts[2]); 32 | //проверка дали дадения индекс е валиден -> индекс е [0; size - 1] 33 | if (isValidIndex(indexForInsert, numbers.size())) { 34 | numbers.add(indexForInsert, numberForInsert); 35 | } else { 36 | //невалиден индекс 37 | System.out.println("Invalid index"); 38 | } 39 | break; 40 | case "Remove": 41 | //command = "Remove {index}".split(" ") -> ["Remove", "{index}"] 42 | int indexToRemove = Integer.parseInt(commandParts[1]); 43 | //проверка дали дадения индекс е валиден -> индекс е [0; size - 1] 44 | if (isValidIndex(indexToRemove, numbers.size())) { 45 | numbers.remove(indexToRemove); 46 | //remove index -> numbers.remove((int) index); 47 | //remove element -> numbers.remove(Integer.valueOf(number)); 48 | } else { 49 | //невалиден индекс 50 | System.out.println("Invalid index"); 51 | } 52 | break; 53 | case "Shift": 54 | String direction = commandParts[1]; //посока: "left" или "right" 55 | int countTimes = Integer.parseInt(commandParts[2]); //брой на пътите, в които правите промяна 56 | if (direction.equals("left")) { 57 | //command = "Shift left {count}".split(" ") -> ["Shift", "left", "{count}"] 58 | for (int i = 1; i <= countTimes; i++) { 59 | //повтаряме: първия елемент става последен 60 | //{3, 4, 5, 7, 8} 61 | //1. взимам първия елемент -> 3 62 | int firstElement = numbers.get(0); 63 | //2. премахвам го -> {4, 5, 7, 8} 64 | numbers.remove(0); 65 | //3. поставям го като последен -> {4, 5, 7, 8, 3} 66 | numbers.add(firstElement); 67 | } 68 | } else if (direction.equals("right")) { 69 | //command = "Shift right {count}".split(" ") -> ["Shift", "right", "{count}"] 70 | for (int i = 1; i <= countTimes; i++) { 71 | //повтаряме: последния елемент става първи 72 | //{8, 4, 5, 6, 2} 73 | //1. взимаме последния елемент -> 2 74 | int lastElement = numbers.get(numbers.size() - 1); 75 | //2. премахваме последния елемент -> {8, 4, 5, 6} 76 | numbers.remove(numbers.size() - 1); 77 | //3. добавяме в началото -> {2, 8, 4, 5, 6} 78 | numbers.add(0, lastElement); 79 | } 80 | } 81 | break; 82 | } 83 | command = scanner.nextLine(); 84 | } 85 | 86 | //краен списък -> отпечатвам 87 | for (int number : numbers) { 88 | System.out.print(number + " "); 89 | } 90 | 91 | } 92 | 93 | //метод, който проверява дали даден индекс е валиден 94 | //true -> ако индексът е валиден 95 | //false -> ако индексът не е валиден 96 | public static boolean isValidIndex (int index, int size) { 97 | return index >= 0 && index <= size - 1; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /05. Lists/Solutions/PokemonDontGo_09.java: -------------------------------------------------------------------------------- 1 | package Lists_Exercise; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.stream.Collectors; 7 | 8 | public class PokemonDontGo_09 { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | List numbers = Arrays.stream(scanner.nextLine() 13 | .split("\\s+")) 14 | .map(Integer::parseInt) 15 | .collect(Collectors.toList()); // {4, 5, 3} 16 | 17 | //повтаряме: въвеждаме индекс 18 | //стоп: нямаме елементи в списъка (size <= 0) 19 | //продължаваме: имаме елементи в списъка (size > 0) 20 | 21 | int sum = 0; //сума на премахнатите елементи 22 | 23 | while (numbers.size() > 0) { 24 | int index = Integer.parseInt(scanner.nextLine()); 25 | //1. index < 0 26 | if (index < 0) { 27 | // {8, 5, 3, 6, 7, 8} 28 | //1. взимам кой ми е първия елемент в списъка 29 | int firstElement = numbers.get(0); 30 | //2. премахваме елемента от първото място -> сумиране 31 | numbers.remove(0); 32 | sum += firstElement; 33 | //3. взимам кой ми е последния елемент в списъка 34 | int lastElement = numbers.get(numbers.size() - 1); 35 | //4. сложим последния елемент на първо място 36 | numbers.add(0, lastElement); 37 | //5. модифицирам списъка спрямо премахнатия елемент 38 | modifyList(numbers, firstElement); 39 | } 40 | //2. index > последния индекс в списъка 41 | else if (index > numbers.size() - 1) { 42 | //1. взимаме последния елемент 43 | int lastElement = numbers.get(numbers.size() - 1); 44 | //2. премахваме последния елемент 45 | numbers.remove(numbers.size() - 1); 46 | sum += lastElement; 47 | //3. взимаме първия елемент 48 | int firstElement = numbers.get(0); 49 | //4. вмъкнем първия елемент на последно място 50 | numbers.add(firstElement); 51 | //5. модифицираме списъка спрямо премахнатия елемент 52 | modifyList(numbers, lastElement); 53 | } 54 | //3. index да е валиден -> index >= 0 и index <= последния 55 | else if (index >= 0 && index <= numbers.size() - 1) { 56 | //1. взимам кой е елемента на дадения индекс 57 | int removedNumber = numbers.get(index); 58 | sum += removedNumber; 59 | //2. премахваме елемента на дадения индекс 60 | numbers.remove(index); 61 | //3. модифицирам списъка спрямо премахнатото число 62 | modifyList(numbers, removedNumber); 63 | } 64 | } 65 | 66 | System.out.println(sum); 67 | } 68 | 69 | public static void modifyList(List numbers, int removedNumber) { 70 | for (int index = 0; index <= numbers.size() - 1; index++) { 71 | int currentElement = numbers.get(index); //текущ елемент 72 | if (currentElement <= removedNumber) { 73 | currentElement += removedNumber; 74 | } else { 75 | currentElement -= removedNumber; 76 | } 77 | 78 | numbers.set(index, currentElement); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /05. Lists/Solutions/SoftUniCoursePlanning_10.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.stream.Collectors; 7 | 8 | public class SoftUniCoursePlanning_10 { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | //1. входни данни -> списък с теми на занятия 12 | List topics = Arrays.stream(scanner.nextLine() //"Data Types, Objects, Lists" 13 | .split(", ")) //["Data Types", "Objects", "Lists"] 14 | .collect(Collectors.toList()); //{"Data Types", "Objects", "Lists"} 15 | 16 | String command = scanner.nextLine(); 17 | while (!command.equals("course start")) { 18 | //1. command = "Add:{lessonTitle}".split(":") -> ["Add", "{lessonTitle}"] 19 | //2. command = "Insert:{lessonTitle}:{index}".split(":") -> ["Insert", "{lessonTitle}", "{index}"] 20 | //3. command = "Remove:{lessonTitle}".split(":") -> ["Remove", "{lessonTitle}"] 21 | //4. command = "Swap:{lessonTitle}:{lessonTitle}".split()-> ["Swap", "{lessonTitle1}", "{lessonTitle2}"] 22 | //5. command = "Exercise:{lessonTitle}".split(":") -> ["Exercise", "{lessonTitle}"] 23 | String [] commandParts = command.split(":"); 24 | String commandName = commandParts[0]; //"Add", "Insert", "Remove", "Swap", "Exercise" 25 | String topic = commandParts[1]; //тема / лекция 26 | 27 | switch (commandName) { 28 | case "Add": 29 | //"Add:Databases" 30 | //добавяме темата, ако я няма 31 | if (!topics.contains(topic)) { 32 | topics.add(topic); 33 | } 34 | break; 35 | case "Insert": 36 | //"Insert:Databases:3" 37 | int index = Integer.parseInt(commandParts[2]); 38 | //добавяме темата на индекс, ако я няма 39 | if (!topics.contains(topic)) { 40 | topics.add(index, topic); 41 | } 42 | break; 43 | case "Remove": 44 | //List, Array, Databases 45 | //"Remove:Databases" 46 | //премахваме темата (topic), ако я има 47 | if (topics.contains(topic)) { 48 | int indexTopic = topics.indexOf(topic); //мястото на темата 49 | String exercise = topic + "-Exercise"; //име на упражнение 50 | boolean hasExercise = indexTopic != topics.size() - 1 && topics.get(indexTopic + 1).equals(exercise); 51 | //true -> имаме упражнение към темата 52 | //false -> нямаме упражнение към темата 53 | topics.remove(topic); 54 | //премахвам упражнението към тази тема -> само ако го има 55 | if (hasExercise) { 56 | topics.remove(exercise); 57 | //topics.remove(indexTopic + 1); 58 | } 59 | } 60 | 61 | break; 62 | case "Swap": 63 | //разменяме местата на двете дадени теми: topic, topic2 64 | //{Arrays, Arrays-Exercise, Lists, Methods, Methods-Exercise} 65 | //"Swap:Arrays:Methods" 66 | //topic -> първата тема -> "Arrays" 67 | //topic2 -> втората тема -> "Methods" 68 | String topic2 = commandParts[2]; 69 | if (topics.contains(topic) && topics.contains(topic2)) { 70 | int indexFirst = topics.indexOf(topic); // 0 71 | int indexSecond = topics.indexOf(topic2); // 3 72 | 73 | topics.set(indexFirst, topic2); //{Methods, Arrays-Exercise, Lists, Methods, Methods-Exercise} 74 | topics.set(indexSecond, topic); //{Methods, Arrays-Exercise, Lists, Arrays, Methods-Exercise} 75 | 76 | //{Methods, Arrays-Exercise, Lists, Arrays, Methods-Exercise} 77 | //размяна и на упражненията 78 | String exFirst = topic + "-Exercise"; //упражнение за първата тема 79 | String exSecond = topic2 + "-Exercise"; //упражнение за втората тема 80 | 81 | if (topics.contains(exFirst)) { 82 | topics.remove(exFirst); //{Methods, Lists, Arrays, Methods-Exercise} 83 | topics.add(topics.indexOf(topic) + 1, exFirst); 84 | } 85 | 86 | if (topics.contains(exSecond)) { 87 | topics.remove(exSecond); 88 | topics.add(topics.indexOf(topic2) + 1, exSecond); 89 | } 90 | } 91 | break; 92 | case "Exercise": 93 | //име на темата -> topic 94 | String exerciseName = topic + "-Exercise"; //име на упражнението 95 | //добавяме за съответната тема упражнение 96 | //{Arrays, Lists, Methods} 97 | //Exercise:Lists 98 | //{Arrays, Lists, Lists-Exercise, Methods} 99 | 100 | //1. проверка дали тази тема, за която ще добавям упражнение, съществува 101 | if (topics.contains(topic)) { 102 | //имам такава тема -> добавям упражнение 103 | //проверка дали имам вече упражнение 104 | int index1 = topics.indexOf(topic); 105 | if (index1 == topics.size() - 1) { 106 | //моята тема е последна в списъка -> НЯМАМЕ УПРАЖНЕНИЕ СЛЕД НЕЯ 107 | topics.add(index1 + 1, exerciseName); 108 | } else if (!topics.get(index1 + 1).equals(exerciseName)) { 109 | //след моята тема няма упражнение 110 | topics.add(index1 + 1, exerciseName); 111 | } 112 | } else { 113 | //нямаме такава тема -> 1. добавяме темата в края на списъка 2. добавяме упражнение 114 | topics.add(topic); //добавяме темата 115 | topics.add(exerciseName); //добавяме и упражнение веднага след темата 116 | 117 | } 118 | 119 | break; 120 | } 121 | 122 | command = scanner.nextLine(); 123 | } 124 | 125 | //списък с темите 126 | //номер.тема 127 | int count = 1; 128 | for (String topic : topics) { 129 | System.out.println(count + "." + topic); 130 | count++; 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /05. Lists/Solutions/Train_01.java: -------------------------------------------------------------------------------- 1 | package Lists_Exercise; 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.stream.Collectors; 7 | public class Train_01 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | //"32 54 21 12 4 0 23" -> ["32", "54", "21", "12", "4", "0", "23"] 11 | List wagons = Arrays.stream(scanner.nextLine().split(" ")).map(Integer::parseInt).collect(Collectors.toList()); 12 | int maxCapacity = Integer.parseInt(scanner.nextLine()); //макс брой пасажери във всеки един вагон 13 | 14 | String command = scanner.nextLine(); 15 | while(!command.equals("end")) { 16 | //"Add {passengers}" -> ["Add", "5"] 17 | //"{passengers}" -> ["45"] 18 | String[] commandData = command.split(" ");//["Add", "5"] или ["45"] 19 | if (commandData[0].equals("Add")) { 20 | //команда Add 21 | int passengers = Integer.parseInt(commandData[1]); 22 | wagons.add(passengers); 23 | } else { 24 | //команда -> число 25 | int passengersToAdd = Integer.parseInt(commandData[0]); 26 | for(int index = 0; index < wagons.size(); index++) { 27 | int currentWagon = wagons.get(index); 28 | if(currentWagon + passengersToAdd <= maxCapacity) { 29 | wagons.set(index, currentWagon + passengersToAdd); 30 | break; 31 | } 32 | } 33 | } 34 | 35 | command = scanner.nextLine(); 36 | } 37 | 38 | for (int wagon : wagons) { 39 | System.out.print(wagon + " "); 40 | } 41 | 42 | //wagons.forEach(wagon -> System.out.print(wagon + " ")); 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /05. Lists/Videos/Lists_Exercise_Videos.txt: -------------------------------------------------------------------------------- 1 | 01. Train -> https://pastebin.com/iNUGcesV 2 | видео: https://youtu.be/3VTWzepe9Bw?t=125 3 | 05. Bomb Numbers -> https://pastebin.com/etfjys5k 4 | 06. Cards Game -> https://pastebin.com/S3wHpqps 5 | видео: https://youtu.be/qjqKzdzS8cU?t=7789 6 | 07. Append Arrays -> https://pastebin.com/uEgm6z6p 7 | видео: https://youtu.be/qjqKzdzS8cU?t=9615 8 | 08. Anonymous Threat -> https://pastebin.com/rDZKRHam 9 | 09. Pokemon Don't Go -> https://pastebin.com/9G5wB3Ln -------------------------------------------------------------------------------- /06. Exam Preparation/HeartDelivery_03_Array.java: -------------------------------------------------------------------------------- 1 | package ExamPreparation; 2 | import java.util.Arrays; 3 | import java.util.Scanner; 4 | public class HeartDelivery_03_Array { 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | 8 | //входни данни 9 | int [] houses = Arrays.stream(scanner.nextLine() //"10@10@10@2" 10 | .split("@")) //["10", "10", "10", "2"] 11 | .mapToInt(Integer::parseInt) //[10, 10, 10, 2] 12 | .toArray(); 13 | 14 | int currentIndex = 0; //на коя къща се намира Купидон 15 | 16 | String command = scanner.nextLine(); 17 | 18 | while (!command.equals("Love!")) { 19 | //command = "Jump 3".split(" ") -> ["Jump", "3"] 20 | int jumpLength = Integer.parseInt(command.split(" ")[1]); 21 | //скача 22 | currentIndex += jumpLength; 23 | 24 | //проверка дали е извън квартала 25 | if (currentIndex > houses.length - 1) { 26 | currentIndex = 0; 27 | } 28 | 29 | //къщата, в която отива -> проверка има ли нужда -> дава сърца 30 | if (houses[currentIndex] != 0) { //имаме нужда от сърца, защото бр. нужни сърца != 0 31 | houses[currentIndex] -= 2; 32 | //ако след даването вече нямаме нужда 33 | if (houses[currentIndex] == 0) { 34 | System.out.printf("Place %d has Valentine's day.%n", currentIndex); 35 | } 36 | } else { 37 | //къщата, в която отива -> брой нужни сърца = 0 38 | System.out.printf("Place %d already had Valentine's day.%n", currentIndex); 39 | } 40 | command = scanner.nextLine(); 41 | } 42 | 43 | //къща = 0 -> няма нужда да и даваме -> може да празнува празника 44 | //къща != 0 -> има нужда от даване на сърца 45 | System.out.printf("Cupid's last position was %d.%n", currentIndex); 46 | //успешна мисия -> всички стойности на къщите да са 0 47 | boolean isFailed = false; 48 | //isFailed = true -> провал 49 | //isFailed = false -> успешна 50 | int countFailedHouse = 0; 51 | for (int house : houses) { 52 | if (house != 0) { 53 | isFailed = true; 54 | countFailedHouse++; 55 | } 56 | } 57 | //isFailed = false -> преминали през всички къщи = 0 58 | if (isFailed) { 59 | System.out.printf("Cupid has failed %d places.%n", countFailedHouse); 60 | } else { 61 | //isFailed = false 62 | System.out.println("Mission was successful."); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /06. Exam Preparation/HeartDelivery_03_List.java: -------------------------------------------------------------------------------- 1 | package ExamPreparation; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.stream.Collectors; 7 | 8 | public class HeartDelivery_03_List { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | //входни данни 13 | List houses = Arrays.stream(scanner.nextLine() //"10@10@10@2" 14 | .split("@")) //["10", "10", "10", "2"] 15 | .map(Integer::parseInt) //[10, 10, 10, 2] 16 | .collect(Collectors.toList()); 17 | 18 | int currentIndex = 0; //на коя къща се намира Купидон 19 | 20 | String command = scanner.nextLine(); 21 | 22 | while (!command.equals("Love!")) { 23 | //command = "Jump 3".split(" ") -> ["Jump", "3"] 24 | int jumpLength = Integer.parseInt(command.split(" ")[1]); 25 | //скача 26 | currentIndex += jumpLength; 27 | 28 | //проверка дали е извън квартала 29 | if (currentIndex > houses.size() - 1) { 30 | currentIndex = 0; 31 | } 32 | 33 | //къщата, в която отива -> проверка има ли нужда -> дава сърца 34 | if (houses.get(currentIndex) != 0) { //имаме нужда от сърца, защото бр. нужни сърца != 0 35 | houses.set(currentIndex, houses.get(currentIndex) - 2); 36 | //ако след даването вече нямаме нужда 37 | if (houses.get(currentIndex) == 0) { 38 | System.out.printf("Place %d has Valentine's day.%n", currentIndex); 39 | } 40 | } else { 41 | //къщата, в която отива -> брой нужни сърца = 0 42 | System.out.printf("Place %d already had Valentine's day.%n", currentIndex); 43 | } 44 | command = scanner.nextLine(); 45 | } 46 | 47 | //къща = 0 -> няма нужда да и даваме -> може да празнува празника 48 | //къща != 0 -> има нужда от даване на сърца 49 | System.out.printf("Cupid's last position was %d.%n", currentIndex); 50 | //успешна мисия -> всички стойности на къщите да са 0 51 | boolean isFailed = false; 52 | //isFailed = true -> провал 53 | //isFailed = false -> успешна 54 | int countFailedHouse = 0; 55 | for (int house : houses) { 56 | if (house != 0) { 57 | isFailed = true; 58 | countFailedHouse++; 59 | } 60 | } 61 | //isFailed = false -> преминали през всички къщи = 0 62 | if (isFailed) { 63 | System.out.printf("Cupid has failed %d places.%n", countFailedHouse); 64 | } else { 65 | //isFailed = false 66 | System.out.println("Mission was successful."); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /06. Exam Preparation/ShootForTheWin_02.java: -------------------------------------------------------------------------------- 1 | package ExamPreparation; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class ShootForTheWin_02 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | //входни данни 11 | int [] targets = Arrays.stream(scanner.nextLine() //"24 50 36 70" 12 | .split(" ")) //["24", "50", "36", "70"] 13 | .mapToInt(Integer::parseInt) //[24, 50, 36, 70] 14 | .toArray(); 15 | int countShotTargets = 0; //брой успешни уцелени мишени 16 | 17 | String input = scanner.nextLine(); //"End" или индекс под формата на текст 18 | while (!input.equals("End")) { 19 | int shotIndex = Integer.parseInt(input); //целя мишената на дадения индекс 20 | 21 | //проверка дали индексът е валиден 22 | //валиден индекс: [0; length - 1] 23 | if (shotIndex >= 0 && shotIndex <= targets.length - 1) { 24 | int shotTarget = targets[shotIndex]; //мишена, която е уцелена 25 | 26 | //преди уцелването -> променяме всички останали мишени 27 | for (int i = 0; i <= targets.length - 1; i++) { 28 | int currentTarget = targets[i]; 29 | //всички мишени 30 | //променяме само: 31 | //1. мишени, които не са моята, която ще целя 32 | //2. мишени, които не са -1 33 | //мишена = -1 -> УЦЕЛЕНА 34 | if (i != shotIndex && currentTarget != -1) { 35 | if (currentTarget > shotTarget) { 36 | currentTarget -= shotTarget; 37 | } else { 38 | //currentTarget <= shotTarget 39 | currentTarget += shotTarget; 40 | } 41 | targets[i] = currentTarget; //слагаме новата стойност 42 | } 43 | 44 | } 45 | 46 | //целя мишената на дадения индекс -> след промяната на останалите мишени 47 | targets[shotIndex] = -1; 48 | countShotTargets++; 49 | } 50 | 51 | input = scanner.nextLine(); 52 | } 53 | 54 | 55 | //финална информация 56 | //1. брой на успешни мишени 57 | //2. масив с мишените и техните стойности 58 | 59 | System.out.print("Shot targets: " + countShotTargets + " -> "); 60 | for (int target : targets) { 61 | System.out.print(target + " "); 62 | } 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /06. Exam Preparation/SoftUniReception_01.java: -------------------------------------------------------------------------------- 1 | package ExamPreparation; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SoftUniReception_01 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //1. входни данни 10 | int firstEmployeeStudents = Integer.parseInt(scanner.nextLine()); //брой студенти, които обслужва първия служител на час 11 | int secondEmployeeStudents = Integer.parseInt(scanner.nextLine()); //брой студенти, които обслужва втория служител на час 12 | int thirdEmployeeStudents = Integer.parseInt(scanner.nextLine()); //брой студенти, които обслужва третия служител на час 13 | int studentsCount = Integer.parseInt(scanner.nextLine()); //общ брой студенти, които трябва да бъдат обслужени 14 | 15 | int studentsPerHour = firstEmployeeStudents + secondEmployeeStudents + thirdEmployeeStudents; //брой студенти, обслужени за 1 час 16 | int totalHours = 0; //брой часове, нужни за обслужването на всички студенти 17 | 18 | //повтаряме: обслужваме максималния брой студенти за служител 19 | //спираме: студенти <= 0 20 | //продължаваме: студенти > 0 21 | 22 | while (studentsCount > 0) { 23 | //обслужване 24 | totalHours++; 25 | if (totalHours % 4 == 0) { 26 | continue; 27 | } 28 | //общ брой студенти, обслужени за 1 час 29 | studentsCount -= studentsPerHour; 30 | } 31 | 32 | System.out.printf("Time needed: %dh.", totalHours); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/AdvertisementMessage_01/Main.java: -------------------------------------------------------------------------------- 1 | package AdvertisementMessage_01; 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 | Message message = new Message(); 10 | int n = Integer.parseInt(scanner.nextLine()); 11 | 12 | for (int i = 0; i < n; i++) { 13 | String output = message.randomMessage(); 14 | System.out.println(output); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/AdvertisementMessage_01/Message.java: -------------------------------------------------------------------------------- 1 | package AdvertisementMessage_01; 2 | 3 | import java.util.Random; 4 | 5 | public class Message { 6 | 7 | private Random random = new Random(); 8 | 9 | private String[] phrases = {"Excellent product.", "Such a great product.", 10 | "I always use that product.", "Best product of its category." 11 | , "Exceptional product.", "I can’t live without this product."}; 12 | private String[] events = {"Now I feel good.", "I have succeeded with this product.", 13 | "Makes miracles. I am happy of the results!", 14 | "I cannot believe but now I feel awesome.", 15 | "Try it yourself, I am very satisfied.", "I feel great!"}; 16 | private String[] author = {"Diana", "Petya", "Stella", "Elena", "Katya", "Iva", "Annie", "Eva"}; 17 | private String[] town = {"Burgas", "Sofia", "Plovdiv", "Varna", "Ruse"}; 18 | 19 | public String randomMessage() { 20 | 21 | return String.format("%s %s %s - %s", 22 | phrases[random.nextInt(phrases.length)], 23 | events[random.nextInt(events.length)], 24 | author[random.nextInt(author.length)], 25 | town[random.nextInt(town.length)]); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/Articles_02/Article.java: -------------------------------------------------------------------------------- 1 | package articles; 2 | 3 | public class Article { 4 | //описание на статия 5 | //полета -> характеристики 6 | private String title; 7 | private String content; 8 | private String author; 9 | 10 | //конструктор -> метод, чрез който създаваме обекти от класа 11 | 12 | //меню за генериране на методи 13 | //ALT + INSERT 14 | //десен бутон някъде в класа -> Generate 15 | public Article(String title, String content, String author) { 16 | //създава нов празен обект 17 | this.title = title; 18 | this.content = content; 19 | this.author = author; 20 | } 21 | 22 | //getters -> методи, чрез които си даваме достъп до стойността на поле 23 | public String getTitle() { 24 | return this.title; 25 | } 26 | 27 | public String getContent() { 28 | return this.content; 29 | } 30 | 31 | public String getAuthor() { 32 | return this.author; 33 | } 34 | 35 | //методи -> действия 36 | 37 | //1. edit -> променя съдържанието 38 | public void edit (String newContent) { 39 | this.content = newContent; 40 | } 41 | 42 | //2. change author -> променя автора 43 | public void changeAuthor (String newAuthor) { 44 | this.author = newAuthor; 45 | } 46 | 47 | //3. rename -> променя заглавие 48 | public void rename (String newTitle) { 49 | this.title = newTitle; 50 | } 51 | 52 | //вградени методи -> toString 53 | //метод toString -> метод, който ми показва как да изглежда обекта под формата на текст 54 | //default: "{package}.{class}@{address}" 55 | //искам: "{title} - {content}: {author}" 56 | 57 | @Override //пренаписване на вграден метод 58 | public String toString() { 59 | return this.title + " - " + this.content + ": " + this.author; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/Articles_02/Main.java: -------------------------------------------------------------------------------- 1 | package articles; 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 | String articleData = scanner.nextLine(); //"{title}, {content}, {author}".split(", ") -> ["{title}", "{content}", "{author}"] 10 | String title = articleData.split(", ")[0]; //заглавие на статия 11 | String content = articleData.split(", ")[1]; //съдържанието на статия 12 | String author = articleData.split(", ")[2]; //автор на статия 13 | 14 | //статия -> title, content, author 15 | Article article = new Article(title, content, author); 16 | 17 | int countCommands = Integer.parseInt(scanner.nextLine()); //бр. команди 18 | for (int count = 1; count <= countCommands; count++) { 19 | String command = scanner.nextLine(); //текст на командата 20 | //command = "Edit: {new content}".split(": ") -> ["Edit", "{new content}"] 21 | //command = "ChangeAuthor: {new author}".split(": ") -> ["ChangeAuthor", "{new author}"] 22 | //command = "Rename: {new title}".split(": ") -> ["Rename", "{new title}"] 23 | 24 | String commandName = command.split(": ")[0]; // "Edit", "ChangeAuthor", "Rename" 25 | String commandParam = command.split(": ")[1]; 26 | 27 | switch (commandName) { 28 | case "Edit": 29 | //commandParam = "{new content}" 30 | //сменя съдържанието на статията 31 | article.edit(commandParam); 32 | break; 33 | case "ChangeAuthor": 34 | //commandParam = "{new author}" 35 | //сменя автора на статията 36 | article.changeAuthor(commandParam); 37 | break; 38 | case "Rename": 39 | //commandParam = "{new title}" 40 | //сменя заглавието на статията 41 | article.rename(commandParam); 42 | break; 43 | } 44 | } 45 | 46 | //принтиране на статията 47 | //"{title} - {content}: {author}" 48 | System.out.println(article.toString()); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/GroomingSalon_07/GroomingSalon.java: -------------------------------------------------------------------------------- 1 | package groomingSalon; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class GroomingSalon { 7 | //полета -> характеристики (списък с дом. животни, капацитет) 8 | private List data; 9 | private int capacity; 10 | 11 | //конструктор 12 | public GroomingSalon(int capacity) { 13 | //нов празен обект {capacity = 0, data = null} 14 | this.capacity = capacity; 15 | this.data = new ArrayList<>(); 16 | } 17 | 18 | //методи -> действия 19 | 20 | //Add 21 | public void add(Pet pet) { 22 | if (this.data.size() < this.capacity) { 23 | this.data.add(pet); 24 | } 25 | } 26 | 27 | //Remove 28 | public boolean remove(String name) { 29 | //true -> ако има такова животно с даденото име и го премахна 30 | //false -> ако няма такова животно с даденото име 31 | 32 | for (Pet pet : this.data) { 33 | if (pet.getName().equals(name)) { 34 | this.data.remove(pet); 35 | return true; 36 | } 37 | } 38 | //обходила всички животни в списъка 39 | return false; 40 | } 41 | 42 | //getPet 43 | public Pet getPet(String name, String owner) { 44 | //ако има животно с дадените параметри -> връщаме го 45 | //няма животно с дадените параметри -> връщаме null 46 | for (Pet pet : this.data) { 47 | if (pet.getName().equals(name) && pet.getOwner().equals(owner)) { 48 | return pet; 49 | } 50 | } 51 | //обходила всички животни в списъка 52 | return null; 53 | } 54 | 55 | //getCount 56 | public int getCount() { 57 | return this.data.size(); 58 | } 59 | 60 | //getStatistics 61 | public String getStatistics() { 62 | String output = ""; 63 | 64 | output += "The grooming salon has the following clients:\n"; 65 | 66 | for (Pet pet : this.data) { 67 | output += pet.getName() + " " + pet.getOwner() + "\n"; 68 | } 69 | 70 | return output; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/GroomingSalon_07/Main.java: -------------------------------------------------------------------------------- 1 | package groomingSalon; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Main { 7 | public static void main(String[] args) { 8 | // Initialize the repository 9 | GroomingSalon salon = new GroomingSalon(20); 10 | 11 | // Initialize entity 12 | Pet dog = new Pet("Ellias", 5, "Tim"); 13 | 14 | // Print Pet 15 | System.out.println(dog); // Ellias 5 - (Tim) 16 | 17 | // Add Pet 18 | salon.add(dog); 19 | 20 | // Remove Pet 21 | System.out.println(salon.remove("Ellias")); // true 22 | System.out.println(salon.remove("Pufa")); // false 23 | 24 | Pet cat = new Pet("Bella", 2, "Mia"); 25 | Pet bunny = new Pet("Zak", 4, "Jon"); 26 | 27 | salon.add(cat); 28 | salon.add(bunny); 29 | 30 | // Get Pet 31 | Pet pet = salon.getPet("Bella", "Mia"); 32 | System.out.println(pet); // Bella 2 - (Mia) 33 | 34 | // Count 35 | System.out.println(salon.getCount()); // 2 36 | 37 | // Get Statistics 38 | System.out.println(salon.getStatistics()); 39 | // The grooming salon has the following clients: 40 | //Bella Mia 41 | //Zak Jon 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/GroomingSalon_07/Pet.java: -------------------------------------------------------------------------------- 1 | package groomingSalon; 2 | 3 | public class Pet { 4 | //полета -> характеристики (name, age, owner) 5 | private String name; 6 | private int age; 7 | private String owner; 8 | 9 | //конструктор, който създава обект по зададени всички полета 10 | //alt+insert 11 | public Pet (String name, int age, String owner) { 12 | //нов празен обект 13 | this.name = name; 14 | this.age = age; 15 | this.owner = owner; 16 | } 17 | 18 | //getters and setters 19 | 20 | //field name 21 | public String getName() { 22 | return this.name; 23 | } 24 | 25 | public void setName(String name) { 26 | this.name = name; 27 | } 28 | 29 | //field age 30 | public int getAge() { 31 | return this.age; 32 | } 33 | 34 | public void setAge(int age) { 35 | this.age = age; 36 | } 37 | 38 | //field owner 39 | public String getOwner() { 40 | return this.owner; 41 | } 42 | 43 | public void setOwner(String owner) { 44 | this.owner = owner; 45 | } 46 | 47 | //default -> "{package}.{class}@{address}" 48 | @Override //пренапишем 49 | public String toString() { 50 | //"{name} {age} - ({owner})" 51 | return this.name + " " + this.age + " - (" + this.owner + ")"; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/OpinionPoll_03/Main.java: -------------------------------------------------------------------------------- 1 | package opinionPoll; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | 7 | public class Main { //решаваме задачата 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | int n = Integer.parseInt(scanner.nextLine()); //бр. редове с лична информация 11 | 12 | List peopleList = new ArrayList<>(); 13 | 14 | for (int row = 1; row <= n; row++) { 15 | String data = scanner.nextLine(); 16 | //data = "Peter 12".split(" ") -> ["Peter", "12"] 17 | String name = data.split(" ")[0]; //въведено име 18 | int age = Integer.parseInt(data.split(" ")[1]); //въведена възраст 19 | 20 | if (age > 30) { 21 | Person person = new Person(name, age); //обект от класа 22 | peopleList.add(person); 23 | } 24 | } 25 | 26 | //списък с хората 27 | //всеки един човек -> отпечатваме 28 | for (Person person : peopleList) { 29 | //име - възраст 30 | System.out.println(person.getName() + " - " + person.getAge()); 31 | } 32 | } 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/OpinionPoll_03/Person.java: -------------------------------------------------------------------------------- 1 | package opinionPoll; 2 | 3 | public class Person { 4 | //описва всеки един човек 5 | 6 | //полета -> характеристики (име, възраст) 7 | private String name; 8 | private int age; 9 | 10 | //конструктор -> метод, чрез който създаваме обект от класа 11 | public Person(String name, int age) { 12 | //нов празен обект 13 | this.name = name; 14 | this.age = age; 15 | } 16 | 17 | //методи -> действия; 18 | //getters -> методи, които използваме, за да достъпваме/взимаме стойностите на полетата 19 | 20 | //1. getter на полето name -> взимам стойността на полето name 21 | public String getName() { 22 | return this.name; 23 | } 24 | 25 | //2. getter на полето age -> взимам стойността на полето age 26 | public int getAge() { 27 | return this.age; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/OrderByAge_06/Main.java: -------------------------------------------------------------------------------- 1 | package OrderByAge_06; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | 8 | public class Main { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | List peopleList = new ArrayList<>(); 13 | String data = scanner.nextLine(); 14 | 15 | while (!data.equals("End")) { 16 | //data = "{name} {ID} {age}".split("\\s+") -> ["{name}", "{ID}", "{age}"] 17 | String name = data.split("\\s+")[0]; //име 18 | String id = data.split("\\s+")[1]; //ID 19 | int age = Integer.parseInt(data.split("\\s+")[2]); //"10" -> 10 20 | 21 | Person person = new Person(name, id, age); 22 | peopleList.add(person); 23 | 24 | data = scanner.nextLine(); 25 | } 26 | 27 | //списък с хората 28 | //1. сортирам по възраст (ascending order) 29 | peopleList.sort(Comparator.comparing(Person::getAge)); 30 | 31 | //2. принтираме данните за всеки човек 32 | for (Person person : peopleList) { 33 | //"Stephan with ID: 524244 is 10 years old." 34 | System.out.println(person.getName() + " with ID: " + person.getId() + " is " + person.getAge() + " years old."); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/OrderByAge_06/Person.java: -------------------------------------------------------------------------------- 1 | package OrderByAge_06; 2 | 3 | public class Person { 4 | //полета -> характеристики (name, id, age) 5 | private String name; 6 | private String id; 7 | private int age; 8 | 9 | //constructor 10 | public Person(String name, String id, int age) { 11 | //нов празен обект 12 | this.name = name; 13 | this.id = id; 14 | this.age = age; 15 | } 16 | 17 | //getters 18 | public String getName() { 19 | return this.name; 20 | } 21 | 22 | public String getId() { 23 | return this.id; 24 | } 25 | 26 | public int getAge() { 27 | return this.age; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/Students_04/Main.java: -------------------------------------------------------------------------------- 1 | package students; 2 | 3 | import java.util.*; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | int n = Integer.parseInt(scanner.nextLine()); //бр. студенти 10 | 11 | List studentList = new ArrayList<>(); 12 | 13 | for (int i = 1; i <= n; i++) { 14 | String data = scanner.nextLine(); 15 | //data = "{firstName} {lastName} {grade}".split(" ") -> ["{fN}", "{lN}", "{gr}"] 16 | String firstName = data.split(" ")[0]; 17 | String lastName = data.split(" ")[1]; 18 | double grade = Double.parseDouble(data.split(" ")[2]); 19 | 20 | Student student = new Student(firstName, lastName, grade); 21 | studentList.add(student); 22 | } 23 | 24 | //списък със студенти -> сортираме по оценка (descending order) -> отпечатваме 25 | Collections.sort(studentList, Comparator.comparingDouble(Student::getGrade) //ascending order 26 | .reversed()); //descending order 27 | 28 | for (Student student : studentList) { 29 | //име фамилия: оценка 30 | System.out.printf("%s %s: %.2f%n", student.getFirstName(), student.getLastName(), student.getGrade()); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/Students_04/Student.java: -------------------------------------------------------------------------------- 1 | package students; 2 | 3 | public class Student { 4 | //описание на всеки студент 5 | //полета -> характеристики 6 | private String firstName; 7 | private String lastName; 8 | private double grade; 9 | 10 | //конструктор -> метод, чрез който създаваме обекти от класа 11 | public Student (String firstName, String lastName, double grade) { 12 | //нов празен обект 13 | this.firstName = firstName; 14 | this.lastName = lastName; 15 | this.grade = grade; 16 | } 17 | 18 | //методи -> действия 19 | //1. getter за полето grade -> достъп до стойността на полето 20 | public double getGrade() { 21 | return this.grade; 22 | } 23 | 24 | //2. getter за полето firstName 25 | public String getFirstName() { 26 | return this.firstName; 27 | } 28 | 29 | //3. getter за полето lastName 30 | public String getLastName() { 31 | return this.lastName; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/VehicleCatalogue_05/Main.java: -------------------------------------------------------------------------------- 1 | package VehicleCatalogue_05; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | 7 | public class Main { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | String input = scanner.nextLine(); 11 | List vehicles = new ArrayList<>(); 12 | 13 | while (!input.equals("End")) { 14 | String[] tokens = input.split("\\s+"); 15 | vehicles.add(new Vehicle(tokens[0], tokens[1], tokens[2], Integer.parseInt(tokens[3]))); 16 | input = scanner.nextLine(); 17 | } 18 | 19 | String model = scanner.nextLine(); 20 | double sumCar = 0; 21 | double sumTruck = 0; 22 | int countCar = 0; 23 | int countTruck = 0; 24 | while (!model.equals("Close the Catalogue")) { 25 | for (Vehicle vehicle : vehicles) { 26 | if (vehicle.getModel().equals(model)) { 27 | System.out.println(vehicle); 28 | 29 | } 30 | } 31 | model = scanner.nextLine(); 32 | } 33 | 34 | for (Vehicle vehicle : vehicles) { 35 | if (vehicle.getType().equals("car")) { 36 | sumCar += vehicle.getHorsePower(); 37 | countCar++; 38 | } else if (vehicle.getType().equals("truck")) { 39 | sumTruck += vehicle.getHorsePower(); 40 | countTruck++; 41 | } 42 | } 43 | 44 | double averageCars = sumCar / countCar; 45 | if(countCar == 0) {averageCars = 0;} 46 | System.out.printf("Cars have average horsepower of: %.2f.%n", averageCars); 47 | double averageTrucks = sumTruck / countTruck; 48 | if(countTruck == 0) {averageTrucks = 0;} 49 | System.out.printf("Trucks have average horsepower of: %.2f.%n", averageTrucks); 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /07. Objects and Classes/Solutions/VehicleCatalogue_05/Vehicle.java: -------------------------------------------------------------------------------- 1 | package VehicleCatalogue_05; 2 | 3 | public class Vehicle { 4 | //{typeOfVehicle} {model} {color} {horsepower} 5 | private String type; 6 | private String model; 7 | 8 | public void setType(String type) { 9 | this.type = type; 10 | } 11 | 12 | public void setModel(String model) { 13 | this.model = model; 14 | } 15 | 16 | public void setColor(String color) { 17 | this.color = color; 18 | } 19 | 20 | public void setHorsePower(int horsePower) { 21 | this.horsePower = horsePower; 22 | } 23 | 24 | public String getType() { 25 | return type; 26 | } 27 | 28 | public String getModel() { 29 | return model; 30 | } 31 | 32 | public String getColor() { 33 | return color; 34 | } 35 | 36 | public int getHorsePower() { 37 | return horsePower; 38 | } 39 | 40 | private String color; 41 | private int horsePower; 42 | 43 | public Vehicle(String type, String model, String color, int horsePower) { 44 | this.type = type; 45 | this.model = model; 46 | this.color = color; 47 | this.horsePower = horsePower; 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | String typeVeh = type.equals("car") ? "Car" : "Truck"; 53 | return "Type: " + typeVeh + "\n" + 54 | "Model: " + model + "\n" + 55 | "Color: " + color + "\n" + 56 | "Horsepower: " + horsePower; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /07. Objects and Classes/Videos/ObjectsAndClasses_Exercise_Videos.txt: -------------------------------------------------------------------------------- 1 | 05. Vehicle Catalogue -> https://pastebin.com/i7u1fvYp 2 | видео: https://youtu.be/3yxpwIGZnzc 3 | 4 | 02. Articles -> https://pastebin.com/PPLYjm6K 5 | видео от 52:00 -> https://softuni.bg/trainings/resources/video/77020/video-28-october-2022-desislava-topuzakova-programming-fundamentals-with-java-september-2022/3837 -------------------------------------------------------------------------------- /08. Maps/Solutions/CompanyUsers_08.java: -------------------------------------------------------------------------------- 1 | package Maps; 2 | import java.util.*; 3 | 4 | public class CompanyUsers_08 { 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | 8 | Map> listOfEmployees = new LinkedHashMap<>(); 9 | 10 | String input = scanner.nextLine(); 11 | while (!input.equals("End")) { 12 | String[] info = input.split(" -> "); 13 | 14 | List currentCompanyEmployees = listOfEmployees.get(info[0]); 15 | boolean containsId = currentCompanyEmployees != null && currentCompanyEmployees.contains(info[1]); 16 | 17 | if (!containsId) { 18 | listOfEmployees.putIfAbsent(info[0], new ArrayList<>()); 19 | listOfEmployees.get(info[0]).add(info[1]); 20 | } 21 | 22 | 23 | input = scanner.nextLine(); 24 | } 25 | 26 | listOfEmployees.entrySet().stream() 27 | .forEach(c -> { 28 | System.out.printf("%s%n", c.getKey()); 29 | c.getValue().forEach(e -> System.out.printf("-- %s%n", e)); 30 | }); 31 | 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /08. Maps/Solutions/CountCharInString_01.java: -------------------------------------------------------------------------------- 1 | package maps; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | public class CountCharInString_01 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | String input = scanner.nextLine().replaceAll(" ",""); //текст -> "Desi".toCharArray() -> ['D', 'e', 's', 'i'] 12 | 13 | //запис: символ -> бр. срещания 14 | Map symbolsCount = new LinkedHashMap<>(); 15 | //HashMap -> нямаме конкретна подредба на записите 16 | //LinkedHashMap -> редът зависи от реда на доабвянето 17 | //TreeMap -> нарежда записите по стойността на ключа 18 | 19 | for (char symbol : input.toCharArray()) { 20 | //проверка за интервал 21 | if (symbol == ' ') { 22 | continue; 23 | } 24 | //проверка дали вече сме го срещали 25 | if (symbolsCount.containsKey(symbol)) { 26 | int currentCount = symbolsCount.get(symbol); 27 | symbolsCount.put(symbol, currentCount + 1); 28 | } 29 | //проверка дали не сме го срещали 30 | else { 31 | symbolsCount.put(symbol, 1); 32 | } 33 | } 34 | 35 | //map: key(символ) -> value(бр. срещания) 36 | //символ -> бр. срещания 37 | 38 | //1 начин за отпечатване 39 | for (Map.Entry entry : symbolsCount.entrySet()) { 40 | //entry 41 | //entry.getKey() -> символ 42 | //entry.getValue() -> бр. срещания 43 | System.out.println(entry.getKey() + " -> " + entry.getValue()); 44 | } 45 | 46 | //2 начин за отпечатване 47 | //symbolsCount.forEach((key, value) -> System.out.println(key + " -> " + value)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /08. Maps/Solutions/Courses_05.java: -------------------------------------------------------------------------------- 1 | package Maps; 2 | import java.util.*; 3 | public class Courses_05 { 4 | public static void main(String[] args) { 5 | Scanner scanner = new Scanner(System.in); 6 | String input = scanner.nextLine(); 7 | //име на курс -> списък с имената на студенти 8 | Map> courses = new LinkedHashMap<>(); 9 | while(!input.equals("end")) { 10 | //"{име на курс} : {име на човек}" -> split (" : ") -> ["{courseName}", "{personName}"] 11 | String courseName = input.split(" : ")[0]; 12 | String personName = input.split(" : ")[1]; 13 | //прверка имам ли такъв курс 14 | //ако нямам такъв курс 15 | if(!courses.containsKey(courseName)) { 16 | courses.put(courseName, new ArrayList<>()); 17 | } 18 | 19 | //ако курсът е нов -> връща празен списък 20 | //ако курсът е стар -> връща моментния списък с хора 21 | courses.get(courseName).add(personName); 22 | 23 | input = scanner.nextLine(); 24 | } 25 | //courseName -> List 26 | courses.entrySet() 27 | .forEach(entry -> { 28 | //key: име на курса 29 | //value: списък с хората 30 | //име на курса -> бр. хората 31 | System.out.println(entry.getKey() + ": " + entry.getValue().size()); 32 | entry.getValue().forEach(studentName -> System.out.println("-- " + studentName)); 33 | //ascending order / нарастващ ред 34 | }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /08. Maps/Solutions/Forcebook_09.java: -------------------------------------------------------------------------------- 1 | package maps; 2 | 3 | import java.util.*; 4 | 5 | public class Forcebook_09 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | String input = scanner.nextLine(); 9 | 10 | //отбор -> списък с играчите 11 | Map> teams = new LinkedHashMap<>(); 12 | 13 | while (!input.equals("Lumpawaroo")) { 14 | if (input.contains(" | ")) { 15 | //input = "{force_side} | {force_user}".split(" | ") -> ["{force_side}", "{force_user}"] 16 | String team = input.split(" \\| ")[0]; 17 | String player = input.split(" \\| ")[1]; 18 | //проверка за отбора 19 | //1. нямаме такъв отбор 20 | if (!teams.containsKey(team)) { 21 | teams.put(team, new ArrayList<>()); 22 | } 23 | //2. имаме такъв отбор 24 | //добавяме играча към отбора, ако го няма в някой друг отбор 25 | boolean isExist = false; //играча го има в друг отбор 26 | //isExist = true -> играчът го има в друг отбор 27 | //isExist = false -> играчът го няма в друг отбор 28 | for (List list : teams.values()) { 29 | if (list.contains(player)) { 30 | isExist = true; 31 | break; 32 | } 33 | } 34 | 35 | if (!isExist) { 36 | teams.get(team).add(player); 37 | } 38 | } else if (input.contains(" -> ")) { 39 | //input = "{force_user} -> {force_side}".split(" -> ") -> ["{force_user}", "{force_side}"] 40 | String player = input.split(" -> ")[0]; //играч, който се мести 41 | String team = input.split(" -> ")[1]; //отбор, в който се мести 42 | 43 | //1. премахваме играча ако го има в някой отбор 44 | teams.entrySet().forEach(entryTeam -> entryTeam.getValue().remove(player)); 45 | 46 | //2. преместване в новия отбор 47 | //2.1. има ли такъв отбор -> няма 48 | if (!teams.containsKey(team)) { 49 | teams.put(team, new ArrayList<>()); 50 | teams.get(team).add(player); 51 | } 52 | //2.2. има ли такъв отбор -> има 53 | else { 54 | teams.get(team).add(player); 55 | } 56 | 57 | System.out.printf("%s joins the %s side!%n", player, team); 58 | } 59 | input = scanner.nextLine(); 60 | } 61 | 62 | //print 63 | //премахваме отборите без играчи 64 | teams.entrySet().stream().filter(teamEntry -> teamEntry.getValue().size() > 0) //оставяме само тези записи, които отговарят на условието 65 | .forEach(entry -> { 66 | //entry: key (team) -> value (list of players) 67 | //"Side: {forceSide}, Members: {forceUsers.Count} 68 | System.out.printf("Side: %s, Members: %d%n", entry.getKey(), entry.getValue().size()); 69 | entry.getValue().forEach(player -> System.out.println("! " + player)); 70 | }); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /08. Maps/Solutions/LegendaryFarming_07.java: -------------------------------------------------------------------------------- 1 | package maps; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | public class LegendaryFarming_07 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | //материали 12 | //shards -> количество 13 | //fragments -> количество 14 | //motes -> количество 15 | 16 | Map materials = new LinkedHashMap<>(); //материали, които са ни нужни 17 | materials.put("shards", 0); 18 | materials.put("fragments", 0); 19 | materials.put("motes", 0); 20 | 21 | Map junks = new LinkedHashMap<>(); //материали, които са боклуци 22 | 23 | boolean isWin = false; 24 | //isWin = false -> не сме спечелили и играта продължава 25 | //isWin = true -> сме спечелили и играта приключва 26 | while (!isWin) { 27 | String input = scanner.nextLine(); 28 | //input = "6 leathers 255 fragments 7 Shards" 29 | String [] inputData = input.split("\\s+"); 30 | //inputData = ["6", "leathers", "255", "fragments", "7", "shards"] 31 | 32 | for (int index = 0; index <= inputData.length - 1; index += 2) { 33 | int quantity = Integer.parseInt(inputData[index]); //количество 34 | String material = inputData[index + 1].toLowerCase(); //материал 35 | 36 | //проверка на материала -> събрали сме го 37 | if (material.equals("shards") || material.equals("fragments") || material.equals("motes")) { 38 | //валиден материал -> събираме 39 | int currentQuantity = materials.get(material); 40 | materials.put(material, currentQuantity + quantity); 41 | } else { 42 | //боклук 43 | if (junks.containsKey(material)) { 44 | int currentQuantity = junks.get(material); 45 | junks.put(material, currentQuantity + quantity); 46 | } else { 47 | junks.put(material, quantity); 48 | } 49 | } 50 | 51 | //проверка дали сме спечелили легендарен предмет 52 | if (materials.get("shards") >= 250) { 53 | //печелим Shadowmourne 54 | System.out.println("Shadowmourne obtained!"); 55 | materials.put("shards", materials.get("shards") - 250); 56 | isWin = true; 57 | break; 58 | } else if (materials.get("fragments") >= 250) { 59 | //печелим Valanyr 60 | System.out.println("Valanyr obtained!"); 61 | materials.put("fragments", materials.get("fragments") - 250); 62 | isWin = true; 63 | break; 64 | } else if (materials.get("motes") >= 250) { 65 | //печелим Dragonwrath 66 | System.out.println("Dragonwrath obtained!"); 67 | materials.put("motes", materials.get("motes") - 250); 68 | isWin = true; 69 | break; 70 | } 71 | } 72 | 73 | if (isWin) { 74 | break; 75 | } 76 | } 77 | 78 | //всички валидни материали -> materials 79 | //entry: key (материал) -> value (количество) 80 | materials.entrySet().forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue())); 81 | 82 | //всички боклуци -> junks 83 | //entry: key (боклук) -> value (количество) 84 | junks.entrySet().forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue())); 85 | 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /08. Maps/Solutions/MinerTask_02.java: -------------------------------------------------------------------------------- 1 | package Maps; 2 | import java.util.*; 3 | 4 | public class MinerTask_02 { 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | Map resourcesQuantity = new LinkedHashMap<>(); 8 | //ресурс -> сума от количество 9 | String resource = scanner.nextLine(); //ресурс или "stop" 10 | while(!resource.equals("stop")) { 11 | //ресурс 12 | int quantity = Integer.parseInt(scanner.nextLine()); 13 | //проверка имам ли такъв ресурс 14 | //ако нямам такъв ресурс 15 | if(!resourcesQuantity.containsKey(resource)) { 16 | resourcesQuantity.put(resource, quantity); 17 | } 18 | //ако имам такъв ресурс 19 | else { 20 | int currentQuantity = resourcesQuantity.get(resource); 21 | resourcesQuantity.put(resource, currentQuantity + quantity); 22 | } 23 | resource = scanner.nextLine(); 24 | } 25 | 26 | //resourcesQuantity.forEach((key, value) -> System.out.println(key + " -> " + value)); 27 | resourcesQuantity.entrySet().forEach(entry -> System.out.println(entry.getKey() + " -> " + entry.getValue())); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /08. Maps/Solutions/Orders_03.java: -------------------------------------------------------------------------------- 1 | package Maps; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | public class Orders_03 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | String data = scanner.nextLine(); 12 | Map productsQuantity = new LinkedHashMap<>(); //product -> quantity 13 | Map productsPrice = new LinkedHashMap<>(); //product -> price 14 | 15 | //Map>: продукт -> {количество, цена} 16 | 17 | while (!data.equals("buy")) { 18 | //data = "{name} {price} {quantity}".split(" ") -> ["{name}", "{price}", "{quantity}"] 19 | String product = data.split("\\s+")[0]; //име на продукта 20 | double price = Double.parseDouble(data.split("\\s+")[1]); //цена на продукта 21 | int quantity = Integer.parseInt(data.split("\\s+")[2]); //количество на продукта 22 | 23 | //за количество -> не сме срещали такъв продукт 24 | if (!productsQuantity.containsKey(product)) { 25 | productsQuantity.put(product, quantity); 26 | } else { 27 | int currentQuantity = productsQuantity.get(product); 28 | productsQuantity.put(product, currentQuantity + quantity); 29 | } 30 | 31 | //за цена -> всеки път да добавяме срещу продукта въведената 32 | productsPrice.put(product, price); 33 | 34 | data = scanner.nextLine(); 35 | } 36 | 37 | //продукт -> количество 38 | //продукт -> ед. цена 39 | 40 | 41 | //продукт -> колко е платено за него (количество * ед. цена) 42 | for (Map.Entry entry : productsQuantity.entrySet()) { 43 | //entry 44 | //key (име на продукта) 45 | //value (брой) 46 | String productName = entry.getKey(); 47 | double finalSum = productsQuantity.get(productName) * productsPrice.get(productName); 48 | System.out.printf("%s -> %.2f%n", productName, finalSum); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /08. Maps/Solutions/SoftuniParking_04.java: -------------------------------------------------------------------------------- 1 | package maps; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | public class SoftuniParking_04 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | int countCommands = Integer.parseInt(scanner.nextLine()); 11 | 12 | //собственик -> номер на колата 13 | Map parkingData = new LinkedHashMap<>(); 14 | 15 | for (int count = 1; count <= countCommands; count++) { 16 | String command = scanner.nextLine(); 17 | //1. command = "register {username} {licensePlateNumber}" 18 | //2. command = "unregister {username}" 19 | String [] commandParts = command.split(" "); 20 | //commandParts = ["register", "{username}", "{licensePlateNumber}"] 21 | //commandParts = ["unregister", "{username}"] 22 | String commandName = commandParts[0]; //име на команда: "register" или "unregister" 23 | String username = commandParts[1]; //име на собственик 24 | 25 | switch (commandName) { 26 | case "register": 27 | String carNumber = commandParts[2]; //номер на колата 28 | //1. имаме такъв собственик 29 | if (parkingData.containsKey(username)) { 30 | System.out.printf("ERROR: already registered with plate number %s%n", parkingData.get(username)); 31 | } 32 | //2. нямаме такъв собственик 33 | else { 34 | parkingData.put(username, carNumber); 35 | System.out.printf("%s registered %s successfully%n", username, carNumber); 36 | } 37 | break; 38 | case "unregister": 39 | //1. имали сме такъв собственик 40 | if (parkingData.containsKey(username)) { 41 | parkingData.remove(username); 42 | System.out.printf("%s unregistered successfully%n", username); 43 | } 44 | //2. нямали сме такъв собственик 45 | else { 46 | System.out.printf("ERROR: user %s not found%n", username); 47 | } 48 | break; 49 | } 50 | } 51 | 52 | //map: собственик (ключ) -> номер на колата (value) 53 | //собственика => номер 54 | parkingData.forEach((key, value) -> System.out.println(key + " => " + value)); 55 | 56 | //3 начин за отпечатване 57 | //entry: key(username) -> value(car number) 58 | //parkingData.entrySet().forEach(entry -> System.out.println(entry.getKey() + " => " + entry.getValue())); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /08. Maps/Solutions/StudentAcademy_06.java: -------------------------------------------------------------------------------- 1 | package maps; 2 | 3 | import java.util.*; 4 | 5 | public class StudentAcademy_06 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int n = Integer.parseInt(scanner.nextLine()); 9 | 10 | //студент -> списък от оценките 11 | Map> studentGrades = new LinkedHashMap<>(); 12 | 13 | for (int i = 1; i <= n; i++) { 14 | String studentName = scanner.nextLine(); 15 | double grade = Double.parseDouble(scanner.nextLine()); 16 | //1. имам такъв студент 17 | if (studentGrades.containsKey(studentName)) { 18 | List currentGrades = studentGrades.get(studentName); 19 | currentGrades.add(grade); 20 | } 21 | //2. нямаме такъв студент 22 | else { 23 | studentGrades.put(studentName, new ArrayList<>()); 24 | studentGrades.get(studentName).add(grade); 25 | } 26 | } 27 | 28 | 29 | //студент -> ср. оценка 30 | //Ivan -> 5.6 31 | Map studentAverageGrade = new LinkedHashMap<>(); 32 | //студенти със средна оценка >= 4.50 33 | 34 | for (Map.Entry> entry : studentGrades.entrySet()) { 35 | //entry: key(име на студента) -> value (списък с оценки) 36 | String studentName = entry.getKey(); 37 | List grades = entry.getValue(); 38 | double averageGrade = getAverageGrade(grades); 39 | 40 | if (averageGrade >= 4.50) { 41 | studentAverageGrade.put(studentName, averageGrade); 42 | } 43 | } 44 | 45 | //print 46 | //map: key(име на студента) -> value (ср. оценка) 47 | studentAverageGrade.entrySet().forEach(entry -> System.out.printf("%s -> %.2f%n", entry.getKey(), entry.getValue())); 48 | } 49 | 50 | private static double getAverageGrade(List grades) { 51 | //{5, 4, 6, 2} 52 | double sum = 0; 53 | for (double grade : grades) { 54 | sum += grade; 55 | } 56 | return sum / grades.size(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /08. Maps/Videos/Maps-Exercise_Videos.txt: -------------------------------------------------------------------------------- 1 | 02. A Miner Task -> https://pastebin.com/33NN2cwG 2 | видео: https://youtu.be/ChHMQXbx-BE?t=2560 3 | 4 | 03. Orders -> https://pastebin.com/BHiCkuGW 5 | видео: https://youtu.be/ChHMQXbx-BE?t=3516 6 | 7 | 05. Courses -> https://pastebin.com/HiHB0BHe 8 | видео: https://youtu.be/ChHMQXbx-BE?t=3710 9 | 10 | 10. SoftUni Exam Results -> https://pastebin.com/LFaraC9W 11 | видео: https://youtu.be/ChHMQXbx-BE?t=7414 -------------------------------------------------------------------------------- /09. Text Processing/CaesarCipher_04.java: -------------------------------------------------------------------------------- 1 | package textProcessing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CaesarCipher_04 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //входни данни -> текст 10 | String text = scanner.nextLine(); //"Programming is cool!" 11 | 12 | for (char symbol : text.toCharArray()) { 13 | //'A' -> 'D' 14 | char encryptSymbol = (char) (symbol + 3); 15 | System.out.print(encryptSymbol); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /09. Text Processing/CharacterMultiplier_02.java: -------------------------------------------------------------------------------- 1 | package TextProcessing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CharacterMultiplier_02 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | String input = scanner.nextLine(); //"George Peter" 10 | String [] names = input.split("\\s+"); //["George", "Peter"] 11 | 12 | String firstText = names[0]; //"George" -> 6 13 | String secondText = names[1]; //"Peter" -> 5 14 | 15 | int minLength = Math.min(firstText.length(), secondText.length()); //дължина на по-късия текст -> 5 16 | int maxLength = Math.max(firstText.length(), secondText.length()); //дължина на по-дългия текст -> 6 17 | 18 | int sum = 0; 19 | for (int index = 0; index < minLength; index++) { 20 | sum += (firstText.charAt(index) * secondText.charAt(index)); 21 | } 22 | 23 | //еднакви дължини на текстовете 24 | if (maxLength == minLength) { 25 | System.out.println(sum); 26 | return; 27 | } 28 | 29 | sum = getLeftSymbols(firstText, secondText, minLength, maxLength, sum); 30 | 31 | System.out.println(sum); 32 | 33 | } 34 | 35 | private static int getLeftSymbols(String firstText, String secondText, int minLength, int maxLength, int sum) { 36 | //кой е по-дългия текст -> останалите букви, които не са участвали в умножението 37 | if (maxLength == firstText.length()) { 38 | //първия текст ми е по-дълъг -> взимам останалите символи 39 | for (int index = minLength; index < firstText.length(); index++) { 40 | sum += firstText.charAt(index); 41 | } 42 | } else { 43 | //втория текст ми е по-дълъг -> взимам останали символи 44 | for (int index = minLength; index < secondText.length(); index++) { 45 | sum += secondText.charAt(index); 46 | } 47 | } 48 | return sum; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /09. Text Processing/ExtractFile_03.java: -------------------------------------------------------------------------------- 1 | package textProcessing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ExtractFile_03 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | String path = scanner.nextLine(); 10 | //"C:\Internal\training-internal\Template.pptx".split("\") 11 | String [] parts = path.split("\\\\"); //["C:", "Internal", "training-internal", "Template.pptx"] 12 | String fullFileName = parts[parts.length - 1]; //"Template.pptx" 13 | 14 | //"Template.pptx".split(".") -> ["Template", "pptx"] 15 | String name = fullFileName.split("\\.")[0]; //"Template" 16 | String extension = fullFileName.split("\\.")[1]; //"pptx" 17 | 18 | System.out.println("File name: " + name); 19 | System.out.println("File extension: " + extension); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /09. Text Processing/LettersChangeNumbers_08.java: -------------------------------------------------------------------------------- 1 | package textProcessing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class LettersChangeNumbers_08 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | //входни данни 9 | String input = scanner.nextLine(); //"P34562Z q2576f H456z" 10 | String[] codes = input.split("\\s+"); //["P34562Z", "q2576f", "H456z"] 11 | 12 | double totalSum = 0; //сума от модифицираните числа на всички кодове 13 | for (String code : codes) { 14 | //code: "{буква}{число}{буква}" => "А23r" 15 | //1. модифицирам числото в кода спрямо буквите 16 | double modifiedNumber = getModifiedNumber(code); 17 | //2. сумирам модифицираното число 18 | totalSum += modifiedNumber; 19 | } 20 | 21 | System.out.printf("%.2f", totalSum); 22 | } 23 | 24 | private static double getModifiedNumber(String code) { 25 | //код: "{буква}{число}{буква}" => "R234u" 26 | char letterBefore = code.charAt(0); //'R' 27 | char letterAfter = code.charAt(code.length() - 1); //'u' 28 | double number = Double.parseDouble(code.replace(letterBefore, ' ') //" 234u" 29 | .replace(letterAfter, ' ') //" 234 " 30 | .trim()); //"234" -> parseDouble -> 234 31 | 32 | 33 | //модификация спрямо буквата преди -> letterBefore 34 | if (Character.isUpperCase(letterBefore)) { 35 | //главна -> А(65) до Z(90) 36 | int positionUpperLetter = (int) letterBefore - 64; //позиция на буквата в азбуката 37 | number /= positionUpperLetter; 38 | //number = number / positionUpperLetter; 39 | } else { 40 | //малка -> a(97) до z(122) 41 | int positionLowerLetter = (int)letterBefore - 96; //позиция на буквата в азбуката 42 | number *= positionLowerLetter; 43 | //number = number * positionLowerLetter; 44 | } 45 | 46 | //модификация спрямо буквата след -> letterAfter 47 | if (Character.isUpperCase(letterAfter)) { 48 | //главна -> А(65) до Z(90) 49 | int positionUpperLetter = (int) letterAfter - 64; //позиция на буквата в азбуката 50 | number -= positionUpperLetter; 51 | //number = number - positionUpperLetter; 52 | } else { 53 | //малка -> a(97) до z(122) 54 | int positionLowerLetter = (int) letterAfter - 96; //позиция на буквата в азбуката 55 | number += positionLowerLetter; 56 | //number = number + positionLowerLetter; 57 | } 58 | 59 | return number; 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /09. Text Processing/MultiplyBigNumber_05.java: -------------------------------------------------------------------------------- 1 | package textProcessing; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.BigInteger; 5 | import java.util.Scanner; 6 | 7 | public class MultiplyBigNumber_05 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | String firstInput = scanner.nextLine(); //"923847238931983192462832102" 12 | String secondInput = scanner.nextLine(); //"4" 13 | 14 | BigInteger firstNumber = new BigInteger(firstInput); //923847238931983192462832102 15 | BigInteger secondNumber = new BigInteger(secondInput);// 4 16 | 17 | System.out.println(firstNumber.multiply(secondNumber)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /09. Text Processing/MultiplyBigNumbers2_05.java: -------------------------------------------------------------------------------- 1 | package TextProcessing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class MultiplyBigNumbers2_05 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | String first = scanner.nextLine(); 9 | int second = Integer.parseInt(scanner.nextLine()); 10 | StringBuilder sb = new StringBuilder(); 11 | int remain = 0; 12 | int printable = 0; 13 | for (int i = first.length() - 1; i >= 0; i--) { 14 | int digit = Integer.parseInt(first.substring(i, i + 1)); 15 | int current = digit * second; 16 | current += remain; 17 | sb.append((current % 10)); 18 | remain = current / 10; 19 | } 20 | if (remain != 0) { 21 | sb.append(remain); 22 | } 23 | boolean zero = true; 24 | for (int i = 0; i < sb.length(); i++) { 25 | if (Integer.parseInt(sb.substring(i, i + 1)) != 0) { 26 | zero = false; 27 | } 28 | } 29 | if (zero) { 30 | System.out.println(0); 31 | } else { 32 | StringBuilder output = new StringBuilder(); 33 | boolean trailing = true; 34 | for (int i = sb.length() - 1; i >= 0; i--) { 35 | if (Integer.parseInt(sb.substring(i, i + 1)) == 0 && trailing) { 36 | 37 | } else { 38 | trailing = false; 39 | output.append(sb.charAt(i)); 40 | } 41 | } 42 | System.out.println(output.toString()); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /09. Text Processing/ReplaceRepeatingChars_06.java: -------------------------------------------------------------------------------- 1 | package TextProcessing; 2 | import java.util.Scanner; 3 | public class ReplaceRepeatingChars_06 { 4 | public static void main(String[] args) { 5 | Scanner scanner = new Scanner(System.in); 6 | String inputText = scanner.nextLine(); 7 | StringBuilder builder = new StringBuilder(inputText); 8 | 9 | for (int index = 0; index < builder.length() - 1 ; index++) { 10 | if(builder.charAt(index) == builder.charAt(index + 1)) { 11 | builder.deleteCharAt(index + 1); 12 | index--; 13 | } 14 | } 15 | 16 | System.out.println(builder); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /09. Text Processing/StringExplosion_07.java: -------------------------------------------------------------------------------- 1 | package textProcessing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class StringExplosion_07 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //входни данни 10 | String input = scanner.nextLine(); //"abv>1>1>2>2asdasd" 11 | StringBuilder textBuilder = new StringBuilder(input); //"abv>1>1>2>2asdasd" 12 | 13 | int totalStrength = 0; //обща сила на експлозията 14 | for (int position = 0; position <= textBuilder.length() - 1; position++) { 15 | char currentSymbol = textBuilder.charAt(position); 16 | if (currentSymbol == '>') { 17 | //експлозия 18 | //char '1' -> string "1" -> int 1 19 | int explosionStrength = Integer.parseInt(textBuilder.charAt(position + 1) + ""); //сила на експлозия 20 | totalStrength += explosionStrength; 21 | } else if (currentSymbol != '>' && totalStrength > 0){ 22 | //премахвам 23 | textBuilder.deleteCharAt(position); 24 | totalStrength--; 25 | position--; //да се мине отново през текущата позиция 26 | } 27 | } 28 | 29 | System.out.println(textBuilder); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /09. Text Processing/ValidUsernames_01.java: -------------------------------------------------------------------------------- 1 | package textProcessing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ValidUsernames_01 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | //входни данни 10 | String input = scanner.nextLine(); //"sh, too_long_username, !lleg@l ch@rs, jeffbutt" 11 | String[] usernames = input.split(", "); //["sh", "too_long_username", "!lleg@l ch@rs", "jeffbutt"] 12 | 13 | //обходя всички username 14 | for (String username : usernames) { 15 | //проверка дали е валидно -> принт 16 | if (isValidUsername(username)) { 17 | System.out.println(username); 18 | } 19 | } 20 | } 21 | //метод, който проверява дали username е валидно 22 | //true -> ако е валидно 23 | //false -> ако не е валидно 24 | public static boolean isValidUsername (String username) { 25 | //1. валидна дължина 26 | //[3; 16] -> валиден 27 | if (username.length() < 3 || username.length() > 16) { 28 | //невалидна дължина -> невалиден username 29 | return false; 30 | } 31 | //дължина е [3;16] -> валидна дължина 32 | 33 | //2. валидно съдържание -> букви, цифри, -, _ 34 | //username = "TestUser".toCharArray() -> ['T', 'e', 's', 't', 'U', 's', 'e', 'r'] 35 | for (char symbol : username.toCharArray()) { 36 | if (!Character.isLetterOrDigit(symbol) && symbol != '-' && symbol != '_') { 37 | //невалиден символ -> невалиден username 38 | return false; 39 | } 40 | } 41 | 42 | //валидно съдържание и валидна дължина -> валиден username 43 | return true; 44 | 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /10. Regular Expressions/Exercise/ExtractEmails_05.java: -------------------------------------------------------------------------------- 1 | package regex_exercise; 2 | 3 | import java.util.Scanner; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class ExtractEmails_05 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | String text = scanner.nextLine(); 11 | //да намерим валидните имейли във въведения текст 12 | //text = "Just send email to s.miller@mit.edu and j.hopking@york.ac.uk for more information." 13 | String regexUsername = "[A-Za-z0-9]+[\\.\\-\\_]?[A-Za-z0-9]+"; 14 | String regexHost = "[A-Za-z]+\\-?[A-Za-z]+(\\.[A-Za-z]+\\-?[A-Za-z]+)+"; 15 | String fullRegex = regexUsername + "@" + regexHost; 16 | Pattern pattern = Pattern.compile(fullRegex); 17 | 18 | Matcher matcher = pattern.matcher(text); 19 | //text = "Just send email to s.miller@mit.edu and j.hopking@york.ac.uk for more information." 20 | //matcher -> всички текстове, които ми отговарят на шаблона -> всички валидни имейли 21 | //matcher = ["s.miller@mit.edu", "j.hopking@york.ac.uk"] 22 | 23 | while (matcher.find()) { 24 | System.out.println(matcher.group()); 25 | } 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /10. Regular Expressions/Exercise/Furniture_01.java: -------------------------------------------------------------------------------- 1 | package regex_exercise; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | public class Furniture_01 { 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | String regex = ">>(?[A-Za-z]+)<<(?[0-9]+\\.?[0-9]*)!(?[0-9]+)"; //текст на шаблона 13 | Pattern pattern = Pattern.compile(regex); //шаблон 14 | List furniture = new ArrayList<>(); //закупените мебели 15 | double totalPrice = 0; //общо изхарчена сума за всички закупени мебели 16 | 17 | String input = scanner.nextLine(); //входни данни 18 | //">>{furniture name}<<{price}!{quantity}" 19 | while (!input.equals("Purchase")) { 20 | //input = ">>Sofa<<312.23!3" 21 | Matcher matcher = pattern.matcher(input); 22 | //matcher = [">>(?TV)<<(?312.23)!(?3)"] 23 | //find 24 | //true -> ако input отговарят на regex 25 | //false -> ако input не отговарят 26 | if (matcher.find()) { 27 | //input отговаря на regex -> валидни входни данни -> купуваме мебели 28 | String furnitureName = matcher.group("furnitureName"); //мебел -> "TV" 29 | double price = Double.parseDouble(matcher.group("price")); //ед. цена -> "312.23" -> parse -> 312.23 30 | int quantity = Integer.parseInt(matcher.group("quantity")); //количество -> "3" -> parse -> 3 31 | 32 | furniture.add(furnitureName); 33 | //сума, която сме заплатили за текущата мебел 34 | double currentPrice = price * quantity; //заплатили за текущата мебел 35 | totalPrice += currentPrice; 36 | } 37 | input = scanner.nextLine(); 38 | } 39 | 40 | //списък със закупените мебели 41 | System.out.println("Bought furniture:"); 42 | for (String f : furniture) { 43 | System.out.println(f); 44 | } 45 | 46 | //обща сума за закупените мебели 47 | System.out.printf("Total money spend: %.2f", totalPrice); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /10. Regular Expressions/Exercise/NetherRealms_04.java: -------------------------------------------------------------------------------- 1 | package RegEx; 2 | 3 | import java.util.*; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | import java.util.stream.Collectors; 7 | public class NetherRealms_05 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | List namesList = Arrays.stream(scanner.nextLine().split("\\s*,\\s*")).collect(Collectors.toList()); 12 | String regexHealth = "[^0-9+*-\\/.]"; 13 | Pattern patternHealth = Pattern.compile(regexHealth); 14 | String regexDamage = "\\+?\\-?\\d+\\.?\\d*"; 15 | Pattern patternDamage = Pattern.compile(regexDamage); 16 | 17 | for (String name : namesList) { 18 | Matcher matcherHealth = patternHealth.matcher(name); 19 | int health = 0; 20 | while (matcherHealth.find()) { 21 | char symbol = matcherHealth.group().charAt(0); 22 | health += symbol; 23 | } 24 | 25 | Matcher matcherDamage = patternDamage.matcher(name); 26 | double damage = 0; 27 | while (matcherDamage.find()) { 28 | double currentDamage = Double.parseDouble(matcherDamage.group()); 29 | damage += currentDamage; 30 | } 31 | for (Character symbol : name.toCharArray()) { 32 | if (symbol == '/') { 33 | damage /= 2; 34 | } else if (symbol == '*') { 35 | damage *= 2; 36 | } 37 | } 38 | 39 | System.out.printf("%s - %d health, %.2f damage%n", name, health, damage); 40 | 41 | } 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /10. Regular Expressions/Exercise/SoftuniBarIncome_02.java: -------------------------------------------------------------------------------- 1 | package regex_exercise; 2 | 3 | import java.util.Scanner; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class SoftuniBarIncome_02 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | String regex = "%(?[A-Z][a-z]+)%[^\\|$%\\.]*<(?\\w+)>[^\\|\\$%\\.]*\\|(?[0-9]+)\\|[^\\|\\$%\\.]*?(?[0-9]+\\.?[0-9]*)\\$"; 11 | Pattern pattern = Pattern.compile(regex); //шаблон 12 | 13 | double totalIncome = 0; //приход от всички поръчки 14 | 15 | String input = scanner.nextLine(); //входни данни 16 | while (!input.equals("end of shift")) { 17 | //входни данни представляват поръчка 18 | //input = "%George%|2|10.3$" 19 | Matcher matcher = pattern.matcher(input); 20 | 21 | if (matcher.find()) { 22 | //валидна поръчка 23 | //matcher = "%(?George)%<(?Croissant)>|(?2)|(?10.3)$" 24 | String customerName = matcher.group("customerName"); //"George" 25 | String product = matcher.group("product"); //"Croissant" 26 | int count = Integer.parseInt(matcher.group("count")); //"2" -> parse -> 2 27 | double price = Double.parseDouble(matcher.group("price")); //"10.3" -> parse -> 10.3 28 | 29 | double totalPricePerOrder = count * price; //цена за текушата поръчка 30 | totalIncome += totalPricePerOrder; 31 | System.out.printf("%s: %s - %.2f%n", customerName, product, totalPricePerOrder); 32 | } 33 | input = scanner.nextLine(); 34 | } 35 | 36 | System.out.printf("Total income: %.2f", totalIncome); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /10. Regular Expressions/Exercise/StarEnigma_03.java: -------------------------------------------------------------------------------- 1 | package RegEx; 2 | 3 | import java.util.*; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class StarEnigma_04 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | int countMessages = Integer.parseInt(scanner.nextLine()); 11 | String regex = "@(?[A-Za-z]+)[^@!:>-]*:(?[0-9]+)[^@!:>-]*!(?[AD])![^@!:>-]*->(?[0-9]+)"; 12 | Pattern pattern = Pattern.compile(regex); 13 | 14 | List attackersPlanets = new ArrayList<>(); //атакуващи планети (attackType е "А") 15 | List destroyedPlanets = new ArrayList<>(); //унищожени планети (attackType е "D") 16 | 17 | for (int messageCount = 1; messageCount <= countMessages; messageCount++) { 18 | String encryptedMessage = scanner.nextLine(); //криптираното съобщение 19 | String decryptedMessage = getDecryptedMessage(encryptedMessage); //декриптирано съобщение 20 | //декриптирано: "PQ@Alderaa1:30000!A!->20000" 21 | Matcher matcher = pattern.matcher(decryptedMessage); 22 | //matcher: "@(?Alderaa)[^@!:>-]*:(?30000)[^@!:>-]*!(?A)![^@!:>-]*->(?20000)"; 23 | if (matcher.find()) { 24 | String planetName = matcher.group("planetName"); 25 | //int population = Integer.parseInt(matcher.group("population")); 26 | String attackType = matcher.group("attackType"); 27 | //int soldiersCount = Integer.parseInt(matcher.group("soldiersCount")); 28 | 29 | if (attackType.equals("A")) { 30 | //атакуваща планета 31 | attackersPlanets.add(planetName); 32 | } else if (attackType.equals("D")) { 33 | //унищожена планета 34 | destroyedPlanets.add(planetName); 35 | } 36 | } 37 | } 38 | 39 | System.out.println("Attacked planets: " + attackersPlanets.size()); 40 | Collections.sort(attackersPlanets); //сортирам планетите по име 41 | attackersPlanets.forEach(planet -> System.out.println("-> " + planet)); 42 | 43 | System.out.println("Destroyed planets: " + destroyedPlanets.size()); 44 | Collections.sort(destroyedPlanets); //сортирам планетите по име 45 | destroyedPlanets.forEach(planet -> System.out.println("-> " + planet)); 46 | } 47 | 48 | //върне декриптираното съобщение 49 | private static String getDecryptedMessage(String encryptedMessage) { 50 | //1. брой на символите [s, t, a, r, S, T, A, R] 51 | //криптирано съобщение: STCDoghudd4=63333$D$0A53333 -> 3 специални букви 52 | int countLetters = getSpecialLettersCount(encryptedMessage); 53 | 54 | //декриптиране -> контруираме ново съобщение 55 | StringBuilder decryptedMessage = new StringBuilder(); 56 | //1. всеки символ от критпираното съобщение 57 | //2. нов символ -> ascii на нов символ = ascii на текущия символ - countLetters 58 | //3. добавяме нов символ 59 | for (char symbol : encryptedMessage.toCharArray()) { 60 | char newSymbol = (char)(symbol - countLetters); 61 | decryptedMessage.append(newSymbol); 62 | } 63 | 64 | return decryptedMessage.toString(); 65 | } 66 | 67 | //върне общия брой на буквите: [s, t, a, r, S, T, A, R] 68 | private static int getSpecialLettersCount(String encryptedMessage) { 69 | //криптирано съобщение: STCDoghudd4=63333$D$0A53333 -> 3 специални букви 70 | int count = 0; 71 | for (char symbol : encryptedMessage.toCharArray()) { 72 | switch (symbol) { 73 | case 's': 74 | case 't': 75 | case 'a': 76 | case 'r': 77 | case 'S': 78 | case 'T': 79 | case 'A': 80 | case 'R': 81 | count++; 82 | break; 83 | } 84 | } 85 | 86 | return count; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /10. Regular Expressions/Exercise/ValidPassword_06.java: -------------------------------------------------------------------------------- 1 | package regex_exercise; 2 | 3 | import java.util.Scanner; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class ValidPassword_06 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | int n = Integer.parseInt(scanner.nextLine()); //брой на въведените редове 11 | String passwordRegex = "_\\.+(?[A-Z][A-Za-z0-9]{4,}[A-Z])_\\.+"; 12 | Pattern pattern = Pattern.compile(passwordRegex); 13 | 14 | for (int row = 1; row <= n; row++) { 15 | String password = scanner.nextLine(); //"_...ChelseA_." 16 | //проверка дали въведената парола е валидна 17 | Matcher matcher = pattern.matcher(password); 18 | //matcher = ["_...ChelseA_."] 19 | 20 | if (matcher.find()) { 21 | //валидна парола -> категоризация в група 22 | String textPassword = matcher.group("passwordText"); //"ChelseA" 23 | StringBuilder sbCategory = new StringBuilder(); //долепям намерените цифри 24 | //категория = съвкупността от всички цифри 25 | for (char symbol : textPassword.toCharArray()) { 26 | if (Character.isDigit(symbol)) { 27 | //цифра 28 | sbCategory.append(symbol); 29 | } 30 | } 31 | //isEmpty <=> дължина == 0 32 | if (sbCategory.length() == 0) { 33 | //нямаме цифри в паролата 34 | System.out.println("Group: default"); 35 | } else { 36 | //имаме цифри в паролата 37 | System.out.println("Group: " + sbCategory.toString()); 38 | } 39 | 40 | } else { 41 | System.out.println("Invalid pass!"); 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /10. Regular Expressions/Lab/MatchDates_03.java: -------------------------------------------------------------------------------- 1 | package regex_lab; 2 | 3 | import java.util.Scanner; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class MatchDates_03 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | String text = scanner.nextLine(); 12 | //"13/Jul/1928, 10-Nov-1934, , 01/Jan-1951,f 25.Dec.1937 23/09/1973, 1/Feb/2016" 13 | String regex = "(?\\d{2})(?[\\.\\-\\/])(?[A-Z][a-z]{2})\\2(?\\d{4})"; //текст на шаблона 14 | Pattern pattern = Pattern.compile(regex); //шаблон 15 | Matcher matcher = pattern.matcher(text); //текстовете от променливата text, които отговрят на шаблона 16 | //matcher = {"13/Jul/1928", "10-Nov-1934", "25.Dec.1937"} 17 | 18 | while (matcher.find()) { 19 | //"13/Jul/1928" 20 | String day = matcher.group("day"); //"13" 21 | String month = matcher.group("month"); //"Jul" 22 | String year = matcher.group("year"); //"1928" 23 | 24 | //Day: 13, Month: Jul, Year: 1928 25 | System.out.printf("Day: %s, Month: %s, Year: %s%n", day, month, year); 26 | 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /10. Regular Expressions/Lab/MatchFullNames_01.java: -------------------------------------------------------------------------------- 1 | package regex_lab; 2 | 3 | import java.util.Scanner; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class MatchFullNames_01 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | String text = scanner.nextLine(); 12 | //"Ivan Ivanov, Ivan ivanov, ivan Ivanov, IVan Ivanov, Georgi Georgiev, Ivan Ivanov" 13 | String regex = "\\b(?[A-Z][a-z]+) (?[A-Z][a-z]+)\\b"; //текст на шаблона 14 | Pattern pattern = Pattern.compile(regex); //шаблон 15 | Matcher matcher = pattern.matcher(text); //съвкупност от текстовете от променливата text, които отговарят на шаблона 16 | //matcher = {"Ivan Ivanov", "Georgi Georgiev"} 17 | 18 | // matcher.find() -> true ако имаме намерени текстове, false ако нямаме намерени текстове 19 | while (matcher.find()) { 20 | System.out.println("First name: " + matcher.group("firstName")); 21 | System.out.println("Last name: " + matcher.group("lastName")); 22 | } 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /10. Regular Expressions/Lab/MatchPhoneNumber_02.java: -------------------------------------------------------------------------------- 1 | package regex_lab; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | public class MatchPhoneNumber_02 { 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | 13 | String text = scanner.nextLine(); 14 | //"+359 2 222 2222,359-2-222-2222, +359/2/222/2222, +359-2 222 2222 +359 2-222-2222, +359-2-222-222, +359-2-222-22222 +359-2-222-2222" 15 | //+359{разделител}{areaCode = 2}{разделител}{3 цифри}{разделител}{4 цифри} 16 | String regex = "\\+359([ -])2\\1\\d{3}\\1\\d{4}\\b"; //текст на шаблона 17 | Pattern pattern = Pattern.compile(regex); //шаблон 18 | Matcher matcher = pattern.matcher(text); //съвкупност от текстовете от промениливата text, които отговарят на шаблона 19 | //matcher = {"+359 2 222 2222", "+359-2-222-2222"} 20 | 21 | List validPhoneNumbers = new ArrayList<>(); //валидни номера 22 | while (matcher.find()) { 23 | validPhoneNumbers.add(matcher.group()); 24 | } 25 | 26 | System.out.println(String.join(", ", validPhoneNumbers)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /10. Regular Expressions/Lab/RegEx - Cheat Sheet.txt: -------------------------------------------------------------------------------- 1 | Regular Expressions - cheat sheet 2 | 3 | Основен синтаксис: 4 | [A-Z] - една главна буква (аски код от 65 до 90) 5 | [a-z] - една малка буква (аски код от 97 до 120) 6 | [0-9] - една цифра [0-9] (аски код от 48 до 57) 7 | [A-Za-z] - една буква, която или е малка, или е голяма 8 | [aeiou] - всички гласни букви 9 | [^aeiou] - всички съгласни букви 10 | \w - един символ, който може да е малка буква, главна буква, цифра или _ 11 | \W - един символ, различен от малка буква, главна буква, цифра или _ 12 | \s - един интервал 13 | \S - един символ, различен от интервал 14 | \d - една цифра [0-9] (аски код от 48 до 57) 15 | \D - един символ, различен от цифра 16 | 17 | Брой на срещанията: 18 | * -> срещания 0 или безброй много пъти 19 | + -> срещания 1 или безброй много пъти 20 | ? -> срещания 0 или 1 пъти 21 | {число} -> срещания {число} пъти 22 | {число, } -> минимум колко пъти 23 | {число1, число2} -> минимум се среща число1 пъти, максимум се среща число2 брой пъти 24 | () -> обособяваме група 25 | (? шаблон) -> обособяваме група с име 26 | 27 | Използване в Java: 28 | String text = scanner.nextLine(); 29 | String regex = "\\b[A-Z][a-z]+ [A-Z][a-z]+\\b"; //текст на шаблона 30 | Pattern pattern = Pattern.compile(regex); // шаблон 31 | Matcher matcher = pattern.matcher(text); //текстовете от променливата text, които отговарят на шаблона -------------------------------------------------------------------------------- /11. Exam Preparation/Task_01.java: -------------------------------------------------------------------------------- 1 | package exam_prepration; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Task_01 { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | String encryptedMessage = scanner.nextLine(); //криптирано съобщение 10 | StringBuilder modifyMessage = new StringBuilder(encryptedMessage); //модифицирам криптираното съобщение 11 | 12 | String command = scanner.nextLine(); 13 | while(!command.equals("Decode")) { 14 | if (command.contains("Move")) { 15 | //command = "Move|5".split("|") -> ["Move", "5"] 16 | int countLetters = Integer.parseInt(command.split("\\|")[1]);//брой на буквите, които трябва да взема от текста 17 | //"Desislava" -> първите 5 -> "Desis" 18 | String firstLetters = modifyMessage.substring(0, countLetters); 19 | //премахвам от текста 20 | modifyMessage.delete(0, countLetters); //премахвам взетите букви от началото -> "lava" 21 | //modifyMessage.replace(0, countLetters, ""); 22 | //слагам накрая -> "lava" + "Desis" = "lavaDesis" 23 | modifyMessage.append(firstLetters); 24 | } else if (command.contains("Insert")) { 25 | //command = "Insert|2|Desi".split("|") -> ["Insert", "2", "Desi"] 26 | int index = Integer.parseInt(command.split("\\|")[1]); //индекс, на който искаме да вмъкнем 27 | String textToInsert = command.split("\\|")[2]; //текст за вмъкване 28 | if (index >= 0 && index <= modifyMessage.length() - 1) { 29 | modifyMessage.insert(index, textToInsert); 30 | } 31 | } else if (command.contains("ChangeAll")) { 32 | //command = "ChangeAll|ab|vr".split("|") -> ["ChangeAll", "ab", "vr"] 33 | String textForChange = command.split("\\|")[1]; //текст, който трябва да се замени 34 | String replacement = command.split("\\|")[2]; //текст, който ще замества 35 | 36 | String currentMessage = modifyMessage.toString(); //моментно съобщение 37 | currentMessage = currentMessage.replace(textForChange, replacement); //замяна в текста 38 | modifyMessage = new StringBuilder(currentMessage); 39 | } 40 | 41 | command = scanner.nextLine(); 42 | } 43 | 44 | System.out.println("The decrypted message is: " + modifyMessage); 45 | 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /11. Exam Preparation/Task_02.java: -------------------------------------------------------------------------------- 1 | package exam_prepration; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | public class Task_02 { 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | 13 | String allDestinations = scanner.nextLine(); //всички дестинации 14 | 15 | String regex = "([=\\/])(?[A-Z][a-zA-Z]{2,})\\1"; 16 | Pattern pattern = Pattern.compile(regex); 17 | Matcher matcher = pattern.matcher(allDestinations); 18 | //съвкупност от текстовете, които отговарят на шаблона -> валидни дестинации 19 | //"=Hawai=/Cyprus/=Invalid/invalid==i5valid=/I5valid/=i=" 20 | //matcher = ["=Hawai=", "/Cyprus/"] 21 | 22 | List validDestinations = new ArrayList<>(); 23 | while(matcher.find()) { 24 | //matcher.group -> "=Hawai=" -> "destination" -> "Hawai" 25 | String destination = matcher.group("destination"); 26 | validDestinations.add(destination); 27 | } 28 | 29 | System.out.println("Destinations: " + String.join(", ", validDestinations)); 30 | 31 | int travelPoints = 0; 32 | for (String destination : validDestinations) { 33 | travelPoints += destination.length(); 34 | } 35 | 36 | System.out.println("Travel Points: " + travelPoints); 37 | 38 | 39 | 40 | 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /11. Exam Preparation/Task_03.java: -------------------------------------------------------------------------------- 1 | package exam_prepration; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | public class Task_03 { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | //1 ЧАСТ: ПОДГОТОВКА ЗА ЗАПОЧВАНЕ НА ИГРА 12 | //име на героя -> hp 13 | Map heroesHP = new LinkedHashMap<>(); 14 | //име на героя -> mp 15 | Map heroesMP = new LinkedHashMap<>(); 16 | 17 | int countHeroes = Integer.parseInt(scanner.nextLine()); //брой на героите 18 | for (int hero = 1; hero <= countHeroes; hero++) { 19 | String heroInfo = scanner.nextLine(); //информация за героя 20 | //"Solmyr 85 120".split(" ") -> ["Solmyr", "86", "120"] 21 | String[] heroData = heroInfo.split("\\s+"); //["Solmyr", "86", "120"] 22 | String heroName = heroData[0]; //име на героя 23 | int hp = Integer.parseInt(heroData[1]); //хит точки на героя 24 | int mp = Integer.parseInt(heroData[2]); //мана точки на героя 25 | 26 | //проверка за hp -> hp <= 100 27 | if (hp <= 100) { 28 | //име на играча -> hp 29 | heroesHP.put(heroName, hp); 30 | } 31 | 32 | //проверка за mp -> mp <= 200 33 | if (mp <= 200) { 34 | //име на герой -> mp 35 | heroesMP.put(heroName, mp); 36 | } 37 | } 38 | 39 | //heroesHP: всеки един герой колко hp има 40 | //heroesMP: всеки един герой колко mp има 41 | 42 | //2 ЧАСТ: ЗАПОЧВАМЕ ИГРАТА 43 | String command = scanner.nextLine(); 44 | 45 | while (!command.equals("End")) { 46 | String [] commandParts = command.split("\\s+-\\s+"); 47 | String commandName = commandParts[0]; //име на командата: "CastSpell", "TakeDamage", "Recharge", "Heal" 48 | String heroName = commandParts[1]; //име на героя 49 | 50 | switch (commandName) { 51 | case "CastSpell": 52 | //command = "CastSpell – {hero name} – {MP needed} – {spell name}" 53 | //commandParts = ["CastSpell", "{hero name}", "{MP needed}", "{spell name}"] 54 | int mpNeeded = Integer.parseInt(commandParts[2]); //нужни мана точки за магията 55 | String spellName = commandParts[3]; //име на магията 56 | int currentMP = heroesMP.get(heroName); //текущите мана точки на героя 57 | 58 | //1. можем да правим магията -> currentMP >= mpNeeded 59 | if (currentMP >= mpNeeded) { 60 | //ПРАВИМ МАГИЯТА 61 | int mpLeft = currentMP - mpNeeded; //мана точки, останали след магията 62 | heroesMP.put(heroName, mpLeft); 63 | System.out.printf("%s has successfully cast %s and now has %d MP!%n", heroName, spellName, mpLeft); 64 | } 65 | //2. НЕ можем да правим магията -> currentMP < mpNeeded 66 | else { 67 | System.out.printf("%s does not have enough MP to cast %s!%n", heroName, spellName); 68 | } 69 | break; 70 | case "TakeDamage": 71 | //command = "TakeDamage – {hero name} – {damage} – {attacker}" 72 | //commandParts = ["TakeDamage", "{hero name}", "{damage}", "{attacker}"] 73 | int damage = Integer.parseInt(commandParts[2]); //отнети точки при атака 74 | String attacker = commandParts[3]; //атакуващ 75 | 76 | int currentHP = heroesHP.get(heroName); //текущи хит точки 77 | //АТАКА -> намаляваме текущите точки с отнети точки при атака 78 | currentHP -= damage; 79 | 80 | //дали е жив 81 | if (currentHP > 0) { 82 | System.out.printf("%s was hit for %d HP by %s and now has %d HP left!%n", heroName, damage, attacker, currentHP); 83 | heroesHP.put(heroName, currentHP); 84 | } 85 | //дали е умрял -> currentHP <= 0 86 | else { 87 | System.out.printf("%s has been killed by %s!%n", heroName, attacker); 88 | heroesHP.remove(heroName); 89 | heroesMP.remove(heroName); 90 | } 91 | break; 92 | case "Recharge": 93 | //command = "Recharge – {hero name} – {amount}" 94 | //commandParts = ["Recharge", "{hero name}", "{amount}"] 95 | int amount = Integer.parseInt(commandParts[2]); //количество за възстановяване(MP) 96 | int currentMPHero = heroesMP.get(heroName); //текущите MP 97 | //възстановяване на MP 98 | currentMPHero += amount; 99 | 100 | if(currentMPHero > 200) { 101 | currentMPHero = 200; 102 | } 103 | 104 | //с колко се е увеличило: увеличеното - първоначалното 105 | System.out.printf("%s recharged for %d MP!%n", heroName, currentMPHero - heroesMP.get(heroName)); 106 | heroesMP.put(heroName, currentMPHero); 107 | break; 108 | case "Heal": 109 | //command = "Heal – {hero name} – {amount}" 110 | //commandParts = ["Heal", "{hero name}", "{amount}"] 111 | int amountHeal = Integer.parseInt(commandParts[2]); //количество за възстановяване за HP 112 | int currentHPHero = heroesHP.get(heroName); //теукущите HP 113 | 114 | //възстановяване на HP 115 | currentHPHero += amountHeal; 116 | 117 | if (currentHPHero > 100) { 118 | currentHPHero = 100; 119 | } 120 | //с колко се е увеличило: увеличеното - първоначалното 121 | System.out.printf("%s healed for %d HP!%n", heroName, currentHPHero - heroesHP.get(heroName)); 122 | heroesHP.put(heroName, currentHPHero); 123 | 124 | break; 125 | } 126 | command = scanner.nextLine(); 127 | } 128 | 129 | //heroesHP: име на играч -> хит точки 130 | //heroesMP: име на играч -> мана точки 131 | 132 | 133 | heroesHP.entrySet() 134 | //(key) име на играч -> (value) хит точки 135 | .forEach(entry -> { 136 | String heroName = entry.getKey(); 137 | System.out.println(heroName); //име на играча 138 | System.out.println(" HP: " + entry.getValue()); //HP 139 | System.out.println(" MP: " + heroesMP.get(heroName)); 140 | }); 141 | } 142 | } 143 | --------------------------------------------------------------------------------