├── Defining Classes - Exercise
├── Demo
│ └── 03. SoftUni's Students
│ │ └── softUni
│ │ ├── .idea
│ │ ├── .gitignore
│ │ ├── misc.xml
│ │ └── modules.xml
│ │ ├── Main.java
│ │ ├── SoftUni.java
│ │ ├── Student.java
│ │ ├── out
│ │ └── production
│ │ │ └── softUni
│ │ │ └── softUni
│ │ │ ├── .idea
│ │ │ ├── .gitignore
│ │ │ ├── misc.xml
│ │ │ └── modules.xml
│ │ │ ├── Main.class
│ │ │ ├── SoftUni.class
│ │ │ ├── Student.class
│ │ │ └── softUni.iml
│ │ └── softUni.iml
└── Solutions
│ ├── 01. Opinion Poll
│ ├── Main.java
│ └── Person.java
│ ├── 02. Company Roster
│ ├── Department.java
│ ├── Employee.java
│ └── Main.java
│ ├── 03. Speed Racing
│ ├── Car.java
│ └── Main.java
│ ├── 04. Raw Data
│ ├── Car.java
│ ├── Cargo.java
│ ├── Engine.java
│ ├── Main.java
│ └── Tire.java
│ ├── 05. Car Salesman
│ ├── Car.java
│ ├── Engine.java
│ └── Main.java
│ ├── 06. Pokemon Trainer
│ ├── Main.java
│ ├── Pokemon.java
│ └── Trainer.java
│ ├── 07. Google
│ ├── Car.java
│ ├── Child.java
│ ├── Company.java
│ ├── Main.java
│ ├── Parent.java
│ ├── Person.java
│ └── Pokemon.java
│ ├── 08. Family Tree
│ ├── Main.java
│ └── Person.java
│ └── 09. Cat Lady
│ ├── Cat.java
│ ├── Cymric.java
│ ├── Main.java
│ ├── Siamese.java
│ └── StreetExtraordinaire.java
├── Functional Porgramming - Exercise
├── Demo
│ ├── Demo_FunctionalProgramming.java
│ └── StickyFingers_02.java
├── Solutions
│ ├── AppliedArithmetics_04.java
│ ├── ConsumerPrint_01.java
│ ├── CustomComparator_08.java
│ ├── CustomMinFunction_03.java
│ ├── FindSmallestElement_07.java
│ ├── KnightsHonor_02.java
│ ├── ListPredicates_09.java
│ ├── PredicateForNames_06.java
│ ├── PredicateParty_10.java
│ ├── ReverseAndExclude_05.java
│ └── ThePartyReservationFilterModule_11.java
├── Theory
│ └── FunctionalProgramming_Exercise_Theory.txt
└── Videos
│ └── FunctionalProgramming_Videos.txt
├── Multidimensional Arrays - Exercise
├── Demo
│ └── RallyRacing_02.java
├── Solutions
│ ├── Crossfire_07.java
│ ├── DiagonalDifference_03.java
│ ├── FillTheMatrix_01.java
│ ├── MatrixOfPalindromes_02.java
│ ├── MatrixShuffling_05.java
│ ├── MaximalSum_04.java
│ ├── ParkingSystem_09.java
│ ├── RadioactiveMutantVampireBunnies_10.java
│ ├── ReverseMatrixDiagonals_11.java
│ ├── StringMatrixRotation_06.java
│ └── TheHeiganDance_08.java
├── Theory
│ └── MultidimensionalArrays_Theory.txt
└── Videos
│ └── MultidimensionalArrays_Videos.txt
├── Sets and Maps Advanced - Exercise
├── Demo
│ ├── Demo_Sort.java
│ └── Demo_Sort_By_List_Count.java
├── Solutions
│ ├── CountSymbols_04.java
│ ├── DragonArmy_13.java
│ ├── FixEmails_06.java
│ ├── HandsOfCards_07.java
│ ├── LegendaryFarming_11.java
│ ├── LoggsAggregator_10.java
│ ├── PeriodicTable_03.java
│ ├── Phonebook_05.java
│ ├── PopulationCounter_09.java
│ ├── SerbeanUnleashed_12.java
│ ├── SetsOfElements_02.java
│ ├── UniqueUsernames_01.java
│ └── UserLogs_08.java
├── Theory
│ └── SetsAndMapsAdvanced_Theory.txt
└── Videos
│ └── SetsAndMaps_Videos.txt
├── Stacks And Queues - Exercise
├── Demo
│ ├── Demo_Fibonacci.java
│ └── Demo_Recursion_Factorial.java
├── Solutions
│ ├── BalancesParenthesses_05.java
│ ├── BasicQueueOperations_04.java
│ ├── BasicStackOperations_02.java
│ ├── InfixToPostfix_08.java
│ ├── MaximumElement_03.java
│ ├── PoisonousPlants_09.java
│ ├── RecursiveFibonacci_06.java
│ ├── ReverseNumbersWithStack_01.java
│ ├── Robotics_10.java
│ └── SimpleTextEditor_07.java
├── Theory
│ └── StacksAndQueue_Theory.txt
└── Videos
│ └── StacksAndQueues_Videos.txt
└── Streams, Files and Directories - Exercise
├── Demo
├── Demo.java
└── NavyBattle_02.java
├── Solutions
├── AllCapitals_03.java
├── CountCharacterTypes_04.java
├── GetFolderSize_08.java
├── LineNumbers_05.java
├── MergeTwoFiles_07.java
├── SumBytes_02.java
├── SumLines_01.java
└── WordsCount_06.java
└── Videos
└── StreamsFilesDirectories_Videos.txt
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/Main.java:
--------------------------------------------------------------------------------
1 | package softUni;
2 |
3 | public class Main {
4 | public static void main(String[] args) {
5 |
6 | // Initialize the repository
7 | SoftUni softUni = new SoftUni(7);
8 |
9 | // Initialize entities
10 | Student student = new Student("Boryana", "Dimitrova", "JavaScript");
11 | Student studentTwo = new Student("Joana", "Jonkova", "Java");
12 | Student studentThree = new Student("Desislava", "Topuzakova", "FundamentalsInMathematics");
13 | Student studentFour = new Student("Alex", "Raykova", "Python");
14 | Student studentFive = new Student("Rosica", "Nenova", "C#");
15 |
16 | // Register Student
17 | String adding = softUni.insert(student);
18 | System.out.println(adding); // Added student Boryana Dimitrova.
19 | String adding1 = softUni.insert(studentTwo);
20 | System.out.println(adding1); // Added student Joana Jonkova.
21 | softUni.insert(studentThree);
22 | softUni.insert(studentFour);
23 | // Remove Student
24 | String removal = softUni.remove(studentTwo);
25 | System.out.println(removal); // Removed student Joana Jonkova.
26 | String removal1 = softUni.remove(studentFive);
27 | System.out.println(removal1); // Student not found.
28 |
29 | // Get Student
30 | System.out.println(softUni.getStudent("Alex", "Raykova")); // Student: Alex Raykova, Best Course – Python
31 |
32 | // Get Statistics
33 | System.out.println(softUni.getStatistics());
34 | //Hall size: 3
35 | //Student: Boryana Dimitrova, Best Course = JavaScript
36 | //Student: Desislava Topuzakova, Best Course = FundamentalsInMathematics
37 | //Student: Alex Raykova, Best Course = Python
38 |
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/SoftUni.java:
--------------------------------------------------------------------------------
1 | package softUni;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class SoftUni {
7 | //ХАРАКТЕРИСТИКИ
8 | private int capacity;
9 | private List data;
10 |
11 | //конструктор
12 | public SoftUni(int capacity) {
13 | //нов празен обект
14 | this.capacity = capacity;
15 | //заменяме null с празен списък, за да мога да добавям в списъка
16 | this.data = new ArrayList<>();
17 | }
18 |
19 | //методи
20 | public int getCapacity() {
21 | return capacity;
22 | }
23 |
24 | public int getCount() {
25 | return this.data.size();
26 | }
27 |
28 | public String insert(Student student) {
29 | //o Returns "Added student {firstName} {lastName}." – if the student is successfully added.
30 | //o Returns "Student is already in the hall." – if the student is already in the hall.
31 | if (getCount() + 1 > this.capacity) {
32 | //не може да влезе още един студент
33 | return "The hall is full.";
34 | } else {
35 | //може да влезе в залата, но вече го има
36 | if (this.data.contains(student)) {
37 | return "Student is already in the hall.";
38 | } else {
39 | //може да влезе в залата и го вече го няма
40 | this.data.add(student);
41 | return String.format("Added student %s %s.", student.getFirstName(), student.getLastName());
42 | }
43 | }
44 | }
45 |
46 | public String remove(Student student) {
47 | //имаме такъв студент -> махаме от списъка
48 | if (this.data.contains(student)) {
49 | this.data.remove(student);
50 | return String.format("Removed student %s %s.", student.getFirstName(), student.getLastName());
51 | }
52 | //нямаме такъв студент
53 | else {
54 | return "Student not found.";
55 | }
56 | }
57 |
58 | public Student getStudent(String firstName, String lastName) {
59 | for (Student student : this.data ) {
60 | if (student.getFirstName().equals(firstName) && student.getLastName().equals(lastName)) {
61 | return student;
62 | }
63 | }
64 | return null;
65 | }
66 |
67 | public String getStatistics() {
68 | StringBuilder sb = new StringBuilder();
69 | sb.append("Hall size: ").append(getCount()).append(System.lineSeparator());
70 | this.data.forEach(student -> sb.append(student.toString()).append(System.lineSeparator()));
71 | return sb.toString();
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/Student.java:
--------------------------------------------------------------------------------
1 | package softUni;
2 |
3 | public class Student {
4 | //ХАРАКТЕРИСТИКИ (ПОЛЕТА)
5 | private String firstName;
6 | private String lastName;
7 | private String bestCourse;
8 |
9 | //конструктор
10 | public Student(String firstName, String lastName, String bestCourse) {
11 | //нов празен обект
12 | this.firstName = firstName;
13 | this.lastName = lastName;
14 | this.bestCourse = bestCourse;
15 | }
16 |
17 | //getters (взимате стойност на полето) and setters (задаваме стойност на полето)
18 |
19 |
20 | //field firstName
21 | public String getFirstName() {
22 | return firstName;
23 | }
24 |
25 | public void setFirstName(String firstName) {
26 | this.firstName = firstName;
27 | }
28 |
29 | //field lastName
30 | public String getLastName() {
31 | return lastName;
32 | }
33 |
34 | public void setLastName(String lastName) {
35 | this.lastName = lastName;
36 | }
37 |
38 | //field bestCourse
39 | public String getBestCourse() {
40 | return bestCourse;
41 | }
42 |
43 | public void setBestCourse(String bestCourse) {
44 | this.bestCourse = bestCourse;
45 | }
46 |
47 | @Override
48 | public String toString() {
49 | //представя всеки един обект под формата на текст
50 | //"Student: {firstName} {lastName}, Best Course = {bestCourse}"
51 | return String.format("Student: %s %s, Best Course = %s", this.firstName, this.lastName, this.bestCourse);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/Main.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DesislavaTopuzakova/Java-Advanced-January-2023/3a7cae491591b5c5eaf78b8701fd5990e10f961d/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/Main.class
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/SoftUni.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DesislavaTopuzakova/Java-Advanced-January-2023/3a7cae491591b5c5eaf78b8701fd5990e10f961d/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/SoftUni.class
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/Student.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DesislavaTopuzakova/Java-Advanced-January-2023/3a7cae491591b5c5eaf78b8701fd5990e10f961d/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/Student.class
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/out/production/softUni/softUni/softUni.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Demo/03. SoftUni's Students/softUni/softUni.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/01. Opinion Poll/Main.java:
--------------------------------------------------------------------------------
1 | package OpinionPoll_01;
2 |
3 | import java.util.*;
4 | import java.util.stream.Collectors;
5 |
6 | public class Main {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | int n = Integer.parseInt(scanner.nextLine());
10 | List peopleList = new ArrayList<>();
11 | for (int i = 1; i <= n; i++) {
12 | String personalInformation = scanner.nextLine(); //"Peter 12".split(" ") -> ["Peter", "12"]
13 | String name = personalInformation.split("\\s+")[0];
14 | int age = Integer.parseInt(personalInformation.split("\\s+")[1]);
15 | Person person = new Person(name, age);
16 | peopleList.add(person);
17 | }
18 | //филтрирай списъка -> само хората над 30
19 | peopleList = peopleList.stream().filter(person -> person.getAge() > 30).collect(Collectors.toList());
20 |
21 | //сортирам списъка по име на хората
22 | peopleList.sort(Comparator.comparing(person -> person.getName()));
23 | //отпечатваме списъка
24 | for (Person person : peopleList) {
25 | //име - възраст
26 | //обект под формата на текст
27 | System.out.println(person.toString());
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/01. Opinion Poll/Person.java:
--------------------------------------------------------------------------------
1 | package OpinionPoll_01;
2 |
3 | public class Person {
4 | //характеристики - име, възраст
5 | private String name;
6 | private int age;
7 |
8 | //конструктор
9 | public Person(String name, int age) {
10 | this.name = name;
11 | this.age = age;
12 | }
13 |
14 | //getter -> върне стойността на полето name
15 | public String getName() {
16 | return name;
17 | }
18 |
19 | //getter -> връща стойността на полето age
20 | public int getAge() {
21 | return age;
22 | }
23 |
24 | //toString
25 | @Override
26 | public String toString() {
27 | //връща обектът под формата на текст
28 | //обект = тескт "{name} - {age}"
29 | return name + " - " + age;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/02. Company Roster/Department.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | public class Department {
5 | private String name;
6 | private List employees;
7 |
8 | public Department(String name) {
9 | this.name = name;
10 | this.employees = new ArrayList<>();
11 | }
12 |
13 | public double getAverageSalary() {
14 | /*double sumSalary = 0;
15 | for (Employee employee : employees) {
16 | sumSalary += employee.getSalary();
17 | }
18 | return sumSalary / employees.size();*/
19 | return this.employees
20 | .stream()
21 | .mapToDouble(e -> e.getSalary())
22 | .average()
23 | .orElse(0.0);
24 | }
25 |
26 | public List getEmployees() {
27 | return this.employees;
28 | }
29 |
30 | public String getName() {
31 | return this.name;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/02. Company Roster/Employee.java:
--------------------------------------------------------------------------------
1 | public class Employee {
2 | //name, salary, position, department, email, age
3 |
4 | //mandatory
5 | private String name;
6 | private double salary;
7 | private String position;
8 | private String department;
9 | //optional
10 | private String email;
11 | private int age;
12 |
13 |
14 | //начин 1: name, salary, position, department
15 | public Employee(String name, double salary, String position, String department) {
16 | this.name = name;
17 | this.salary = salary;
18 | this.position = position;
19 | this.department = department;
20 | this.email = "n/a";
21 | this.age = -1;
22 | }
23 |
24 | //начин 2: name, salary, position, department, email, age
25 | public Employee(String name, double salary, String position, String department, String email, int age) {
26 | this(name, salary, position, department);
27 | this.email = email;
28 | this.age = age;
29 | }
30 |
31 | //начин 3: name, salary, position, department, email
32 | public Employee(String name, double salary, String position, String department, String email) {
33 | this(name, salary, position, department);
34 | this.email = email;
35 | }
36 | //начин 4: name, salary, position, department, age
37 | public Employee(String name, double salary, String position, String department, int age) {
38 | this(name, salary, position, department);
39 | this.age = age;
40 | }
41 |
42 | public double getSalary() {
43 | return this.salary;
44 | }
45 |
46 | @Override
47 | public String toString() {
48 | //"Peter 120.00 peter@abv.bg 28"
49 | return String.format("%s %.2f %s %d", name, salary, email, age);
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/02. Company Roster/Main.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class Main {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 | int n = Integer.parseInt(scanner.nextLine());
7 | HashMap departments = new HashMap<>();
8 | for (int i = 0; i < n; i++) {
9 | String employeeData = scanner.nextLine();
10 | String[] parameters = employeeData.split(" ");
11 | //вианги имаме name, salary, position, department
12 | String name = parameters[0];
13 | double salary = Double.parseDouble(parameters[1]);
14 | String position = parameters[2];
15 | String department = parameters[3];
16 | Employee employee = null;
17 | //6 параметъра -> name, salary, position, department, email, age
18 | if(parameters.length == 6) {
19 | String email = parameters[4];
20 | int age = Integer.parseInt(parameters[5]);
21 | employee = new Employee(name, salary, position, department, email, age);
22 | }
23 | //5 параметъра -> name, salary, position, department, email / age
24 | else if (parameters.length == 5) {
25 | String parameterForth = parameters[4];
26 | if(parameterForth.contains("@")) {
27 | String email = parameterForth;
28 | employee = new Employee(name, salary, position, department, email);
29 | } else {
30 | int age = Integer.parseInt(parameterForth);
31 | employee = new Employee(name, salary, position, department, age);
32 | }
33 | }
34 | //4 параметъра -> name, salary, position, department
35 | else if (parameters.length == 4) {
36 | employee = new Employee(name, salary, position, department);
37 | }
38 |
39 | // обект Employee
40 |
41 |
42 | //име на отдел -> отедел
43 |
44 | //проверка дали го няма
45 | if(!departments.containsKey(department)) {
46 | departments.put(department, new Department(department));
47 | }
48 |
49 | //добавим служителя в списъка със служителите на отдела
50 | departments.get(department).getEmployees().add(employee);
51 |
52 | }
53 |
54 | //отдел -> Отдел (име, списък със служители)
55 | Department maxAverageSalaryDepartment = departments.entrySet()
56 | .stream()
57 | .max(Comparator.comparingDouble(entry -> entry.getValue().getAverageSalary()))
58 | .get()
59 | .getValue();
60 |
61 | System.out.println("Highest Average Salary: " + maxAverageSalaryDepartment.getName());
62 | maxAverageSalaryDepartment.getEmployees()
63 | .stream()
64 | .sorted((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary()))
65 | .forEach(employee -> System.out.println(employee.toString()));
66 |
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/03. Speed Racing/Car.java:
--------------------------------------------------------------------------------
1 | package ObjectsAndClasses.SpeedRacing;
2 |
3 | public class Car {
4 | //полета -> характеристики
5 | private String model;
6 | private double fuelAmount;
7 | private double consumptionFuelPerKm;
8 | private int distanceTraveled;
9 |
10 |
11 | //методи -> действия
12 | //getters -> осигуряват достъп до полетата
13 | //конструктор -> метод, чрез който ние създаваме обекти от класа
14 | public Car(String model, double fuelAmount, double consumptionFuelPerKm) {
15 | //нов празен обект
16 | this.model = model;
17 | this.fuelAmount = fuelAmount;
18 | this.consumptionFuelPerKm = consumptionFuelPerKm;
19 | this.distanceTraveled = 0;
20 | }
21 |
22 | public boolean drive(int kmDrive) {
23 | // 1. нужно количечство гориво, за да преминем дадените км (kmDrive)
24 | double needFuel = kmDrive * this.consumptionFuelPerKm;
25 | if (needFuel <= this.fuelAmount) {
26 | //можем да изминем разстоянието
27 | this.fuelAmount -= needFuel;
28 | this.distanceTraveled += kmDrive;
29 | return true;
30 | }
31 | return false;
32 | }
33 |
34 | @Override
35 | public String toString() {
36 | //дава обекта под формата на текст -> "{Model} {fuelAmount} {distanceTraveled}"
37 | return String.format("%s %.2f %d",this.model, this.fuelAmount, this.distanceTraveled);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/03. Speed Racing/Main.java:
--------------------------------------------------------------------------------
1 | package ObjectsAndClasses.SpeedRacing;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.Map;
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 countCars = Integer.parseInt(scanner.nextLine());
11 | Map cars = new LinkedHashMap<>();
12 | //запис: модел на колата -> кола (всички характеристики)
13 | //List listOfCars = new ArrayList();
14 | for (int i = 1; i <= countCars; i++) {
15 | String[] data = scanner.nextLine().split("\\s+");
16 | //"{Model} {FuelAmount} {FuelCostFor1km}".split(" ") -> ["{Model}", "{FuelAmount}", "{FuelCostFor1km}"]
17 | String model = data[0];
18 | double fuelAmount = Double.parseDouble(data[1]);
19 | double consumption = Double.parseDouble(data[2]);
20 |
21 | Car car = new Car(model, fuelAmount, consumption);
22 | //listOfCars.add(car);
23 | cars.put(model, car);
24 | }
25 |
26 | String command = scanner.nextLine();
27 | while (!command.equals("End")) {
28 | //command = "Drive {CarModel} {amountOfKm}".split(" ") -> ["Drive", "{CarModel}", "{amountOfKm}"]
29 | String carModelToDrive = command.split("\\s+")[1];
30 | int kmToDrive = Integer.parseInt(command.split("\\s+")[2]);
31 |
32 | //взимам коя кола ще карам
33 | Car carToDrive = cars.get(carModelToDrive);
34 |
35 | //drive -> false -> горивото не ни стига, за да изминем разстоянието
36 | //drive -> true -> горивото е стигнало и ние сме изминали разстоянието
37 | if (!carToDrive.drive(kmToDrive)) {
38 | System.out.println("Insufficient fuel for the drive");
39 | }
40 | command = scanner.nextLine();
41 | }
42 |
43 | for (Car car : cars.values()) {
44 | //"{Model} {fuelAmount} {distanceTraveled}"
45 | System.out.println(car.toString());
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/04. Raw Data/Car.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.rawData;
2 |
3 | import java.util.List;
4 |
5 | public class Car {
6 | // model, engine, cargo, and a collection of exactly 4 tires.
7 | private String model;
8 | private Engine engine;
9 | private Cargo cargo;
10 | private List tires;
11 |
12 | public Car(String model, Engine engine, Cargo cargo, List tires) {
13 | this.model = model;
14 | this.engine = engine;
15 | this.cargo = cargo;
16 | this.tires = tires;
17 | }
18 |
19 |
20 | public void extract(String command) {
21 | switch (command) {
22 | case "fragile":
23 | for (Tire tire : tires) {
24 | double pressure = tire.getPressure();
25 | if (pressure < 1) {
26 | System.out.println(model);
27 | break;
28 | }
29 | }
30 | break;
31 | case "flamable":
32 | if (engine.getEnginePower() > 250) {
33 | System.out.println(model);
34 |
35 | }
36 | break;
37 |
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/04. Raw Data/Cargo.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.rawData;
2 |
3 | public class Cargo {
4 | private int cargoWeight;
5 | private String cargoType;
6 |
7 | public Cargo(int cargoWeight, String cargoType) {
8 | this.cargoWeight = cargoWeight;
9 | this.cargoType = cargoType;
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/04. Raw Data/Engine.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.rawData;
2 |
3 | public class Engine {
4 | private int engineSpeed;
5 | private int enginePower;
6 |
7 | public Engine(int engineSpeed, int enginePower) {
8 | this.engineSpeed = engineSpeed;
9 | this.enginePower = enginePower;
10 | }
11 |
12 | public int getEnginePower() {
13 | return enginePower;
14 | }
15 |
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/04. Raw Data/Main.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.rawData;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
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 | int rows = Integer.parseInt(scanner.nextLine());
12 |
13 | HashMap> carsByCargoType = new HashMap<>();
14 |
15 | while (rows-- > 0) {
16 | String[] input = scanner.nextLine().split(" ");
17 | String model = input[0];
18 | int engineSpeed = Integer.parseInt(input[1]);
19 | int enginePower = Integer.parseInt(input[2]);
20 | int cargoWeight = Integer.parseInt(input[3]);
21 | String cargoType = input[4];
22 | Engine engine = new Engine(engineSpeed, enginePower);
23 | Cargo cargo = new Cargo(cargoWeight, cargoType);
24 | List tireList = new ArrayList<>();
25 | for (int tireItems = 5; tireItems <= 12; tireItems += 2) {
26 | Tire currentTire = new Tire(Double.parseDouble(input[tireItems]), Integer.parseInt(input[tireItems + 1]));
27 | tireList.add(currentTire);
28 | }
29 | Car currentCar = new Car(model, engine, cargo, tireList);
30 | carsByCargoType.putIfAbsent(cargoType, new ArrayList<>());
31 | carsByCargoType.get(cargoType).add(currentCar);
32 | }
33 |
34 | String command = scanner.nextLine();
35 |
36 | carsByCargoType.get(command).forEach(car -> car.extract(command));
37 |
38 |
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/04. Raw Data/Tire.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.rawData;
2 |
3 | public class Tire {
4 | private double pressure;
5 | private int age;
6 |
7 | public Tire(double pressure, int age) {
8 | this.pressure = pressure;
9 | this.age = age;
10 | }
11 |
12 | public double getPressure() {
13 | return pressure;
14 | }
15 |
16 | public void setPressure(double pressure) {
17 | this.pressure = pressure;
18 | }
19 |
20 | public int getAge() {
21 | return age;
22 | }
23 |
24 | public void setAge(int age) {
25 | this.age = age;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/05. Car Salesman/Car.java:
--------------------------------------------------------------------------------
1 | package ObjectsAndClasses.CarsSalesman;
2 |
3 | public class Car {
4 | //ХАРАКТЕРИСТИКИ
5 | private String model;
6 | private Engine engine;
7 | private int weight;
8 | private String color;
9 |
10 | //КОНСТРУКТОР
11 |
12 | public Car(String model, Engine engine, int weight, String color) {
13 | this.model = model;
14 | this.engine = engine;
15 | this.weight = weight;
16 | this.color = color;
17 | }
18 |
19 | @Override
20 | public String toString() {
21 | StringBuilder sb = new StringBuilder(); //""
22 |
23 | sb.append(this.model).append(":").append(System.lineSeparator()); //модел на колата
24 | sb.append(this.engine.getModel()).append(":").append(System.lineSeparator()); //модел на двигателя на колата
25 | sb.append("Power: ").append(this.engine.getPower()).append(System.lineSeparator());
26 |
27 | //Displacement: {EngineDisplacement}
28 | sb.append("Displacement: ");
29 | //нямаме = 0; имаме = цяло число
30 | if (this.engine.getDisplacement() == 0) {
31 | sb.append("n/a").append(System.lineSeparator());
32 | } else {
33 | sb.append(this.engine.getDisplacement()).append(System.lineSeparator());
34 | }
35 |
36 | //Efficiency: {EngineEfficiency}
37 | sb.append("Efficiency: ");
38 | //нямаме = null; имаме = текст
39 | if (this.engine.getEfficiency() == null) {
40 | sb.append("n/a").append(System.lineSeparator());
41 | } else {
42 | sb.append(this.engine.getEfficiency()).append(System.lineSeparator());
43 | }
44 |
45 | //Weight: {CarWeight}
46 | sb.append("Weight: ");
47 | //нямаме = 0; имаме = цяло число
48 | if (this.weight == 0) {
49 | sb.append("n/a").append(System.lineSeparator());
50 | } else {
51 | sb.append(this.weight).append(System.lineSeparator());
52 | }
53 |
54 | //Color: {CarColor}"
55 | sb.append("Color: ");
56 | //нямаме = null; имаме = текст
57 | if (this.color == null) {
58 | sb.append("n/a").append(System.lineSeparator());
59 | } else {
60 | sb.append(this.color).append(System.lineSeparator());
61 | }
62 |
63 | return sb.toString();
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/05. Car Salesman/Engine.java:
--------------------------------------------------------------------------------
1 | package ObjectsAndClasses.CarsSalesman;
2 |
3 | public class Engine {
4 | //ДВИГАТЕЛ
5 | //ХАРАКТЕРИСТИКИ
6 | private String model;
7 | private int power; //мощност
8 | private int displacement; //работен обем
9 | private String efficiency; //ефективност
10 |
11 | //КОНСТРУКТОР -> ALT + INSERT
12 | public Engine(String model, int power, int displacement, String efficiency) {
13 | //нов празен обект
14 | this.model = model;
15 | this.power = power;
16 | this.displacement = displacement;
17 | this.efficiency = efficiency;
18 | }
19 |
20 | public String getModel() {
21 | return model;
22 | }
23 |
24 | public int getPower() {
25 | return power;
26 | }
27 |
28 | public int getDisplacement() {
29 | return displacement;
30 | }
31 |
32 | public String getEfficiency() {
33 | return efficiency;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/05. Car Salesman/Main.java:
--------------------------------------------------------------------------------
1 | package ObjectsAndClasses.CarsSalesman;
2 |
3 | import java.sql.SQLOutput;
4 | import java.util.ArrayList;
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 | //ДВИГАТЕЛИ
13 | List engines = new ArrayList<>();
14 | int enginesCount = Integer.parseInt(scanner.nextLine());
15 | for (int engineCount = 1; engineCount <= enginesCount ; engineCount++) {
16 | //"{Model} {Power} {Displacement} {Efficiency}".split(" ")
17 | //1. ["model", "power", "displacement", "efficiency"]
18 | //2. ["model", "power", "efficiency"]
19 | //3. ["model", "power", "displacement"]
20 | //required: model, power
21 | //optional: displacement, efficiency
22 | String [] engineData = scanner.nextLine().split("\\s+");
23 | //required
24 | String model = engineData[0];
25 | int power = Integer.parseInt(engineData[1]);
26 | //optional
27 | int displacement = 0;
28 | String efficiency = null;
29 |
30 | //проверка дали са ми въведени displacement и efficiency
31 | if (engineData.length == 4) {
32 | //["model", "power", "displacement", "efficiency"]
33 | //displacement и efficiency са въведени
34 | displacement = Integer.parseInt(engineData[2]);
35 | efficiency = engineData[3];
36 | } else if (engineData.length == 3){
37 | //["model", "power", "displacement"] -> ["model", "432", "54"]
38 | //["model", "power", "efficiency"] -> ["model", "432", "b"]
39 | if (Character.isDigit(engineData[2].charAt(0))) {
40 | displacement = Integer.parseInt(engineData[2]);
41 | } else {
42 | efficiency = engineData[2];
43 | }
44 |
45 | }
46 |
47 | //model, power, displacement, efficiency
48 | Engine engine = new Engine(model, power, displacement, efficiency);
49 | //добавям двигателя в списъка
50 | engines.add(engine);
51 | }
52 |
53 | //КОЛИ
54 | int carsCount = Integer.parseInt(scanner.nextLine());
55 | for (int carCount = 1; carCount <= carsCount; carCount++) {
56 | //"{Model} {Engine} {Weight} {Color}"
57 | String[] carData = scanner.nextLine().split("\\s+");
58 | //1. ["{Model}", "{Engine Model}", "{Weight}", "{Color}"]
59 | //2. ["{Model}", "{Engine Model}", "{Weight}"]
60 | //3. ["{Model}", "{Engine Model}", "{Color}"]
61 | //required
62 | String carModel = carData[0];
63 | String engineModel = carData[1]; //модел на двигателя
64 | //optional
65 | int weight = 0;
66 | String color = null;
67 |
68 | //проверка какво ни е въведено
69 | if (carData.length == 4) {
70 | //1. ["{Model}", "{Engine Model}", "{Weight}", "{Color}"]
71 | weight = Integer.parseInt(carData[2]);
72 | color = carData[3];
73 | } else if (carData.length == 3) {
74 | //2. ["{Model}", "{Engine Model}", "5464"]
75 | //3. ["{Model}", "{Engine Model}", "red"]
76 | if (Character.isDigit(carData[2].charAt(0))) {
77 | //2. ["{Model}", "{Engine Model}", "5464"] -> има въведено тегло
78 | weight = Integer.parseInt(carData[2]);
79 | } else {
80 | //3. ["{Model}", "{Engine Model}", "red"] -> имаме въведен цвят
81 | color = carData[2];
82 | }
83 | }
84 |
85 | //намеря кой е двигателя от въведените
86 | //списък с налични двигатели -> намеря двигателя
87 | Engine carEngine = null; //двигателя на колата
88 | for (Engine engine : engines) {
89 | if (engineModel.equals(engine.getModel())) {
90 | carEngine = engine;
91 | break;
92 | }
93 | }
94 |
95 | Car car = new Car(carModel, carEngine, weight, color);
96 | System.out.print(car.toString());
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/06. Pokemon Trainer/Main.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.pokemonTrainer;
2 |
3 | import java.util.*;
4 | import java.util.stream.Collectors;
5 |
6 | public class Main {
7 |
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | String inputLine = scanner.nextLine();
11 | Map> pokemonByTrainers = new LinkedHashMap<>();
12 |
13 | while (!inputLine.equals("Tournament")) {
14 | String[] data = inputLine.split("\\s+");
15 | //"{TrainerName} {PokemonName} {PokemonElement} {PokemonHealth}"
16 | Pokemon pokemon = new Pokemon(data[1], data[2], Integer.parseInt(data[3]));
17 | pokemonByTrainers.putIfAbsent(data[0], new ArrayList<>());
18 | pokemonByTrainers.get(data[0]).add(pokemon);
19 |
20 | inputLine = scanner.nextLine();
21 | }
22 | List trainerList = pokemonByTrainers.entrySet()
23 | .stream()
24 | .map(t -> new Trainer(t.getKey(), t.getValue()))
25 | .collect(Collectors.toList());
26 |
27 |
28 | String command = scanner.nextLine();
29 | while (!command.equals("End")) {
30 |
31 |
32 | for (Trainer trainer : trainerList) {
33 | trainer.commandExecuting(command);
34 | }
35 | command = scanner.nextLine();
36 | }
37 |
38 | trainerList.stream()
39 | .sorted(Comparator.comparingInt(Trainer::getNumberOfBadges).reversed())
40 | .forEach(System.out::println);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/06. Pokemon Trainer/Pokemon.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.pokemonTrainer;
2 |
3 | public class Pokemon {
4 | private String name;
5 | private String element;
6 | private int health;
7 |
8 | public Pokemon(String name, String element, int health) {
9 | this.name = name;
10 | this.element = element;
11 | this.health = health;
12 | }
13 |
14 | public String getName() {
15 | return name;
16 | }
17 |
18 | public void setName(String name) {
19 | this.name = name;
20 | }
21 |
22 | public String getElement() {
23 | return element;
24 | }
25 |
26 |
27 | public int getHealth() {
28 | return health;
29 | }
30 |
31 | public void setHealth(int health) {
32 | this.health = health;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/06. Pokemon Trainer/Trainer.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.pokemonTrainer;
2 |
3 | import java.util.List;
4 |
5 |
6 | public class Trainer {
7 |
8 | private String name;
9 | private int numberOfBadges;
10 | private List collectionOfPokemon;
11 |
12 | public Trainer(String name, List collectionOfPokemon) {
13 | this.name = name;
14 | this.numberOfBadges = 0;
15 | this.collectionOfPokemon = collectionOfPokemon;
16 | }
17 |
18 | public int getNumberOfBadges() {
19 | return numberOfBadges;
20 | }
21 |
22 | public void commandExecuting(String command) {
23 |
24 | if (isExist(command)) {
25 | numberOfBadges += 1;
26 | } else {
27 |
28 | for (int i = 0; i < collectionOfPokemon.size(); i++) {
29 | collectionOfPokemon.get(i).setHealth(collectionOfPokemon.get(i).getHealth() - 10);
30 | if (collectionOfPokemon.get(i).getHealth() <= 0) {
31 | collectionOfPokemon.remove(i);
32 | i--;
33 | }
34 | }
35 | }
36 | }
37 |
38 | private boolean isExist(String command) {
39 | for (Pokemon pokemon : collectionOfPokemon) {
40 | if (pokemon.getElement().equals(command)) {
41 | return true;
42 | }
43 | }
44 | return false;
45 | }
46 |
47 | @Override
48 | public String toString() {
49 | return name + " " + numberOfBadges + " " + collectionOfPokemon.size();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/07. Google/Car.java:
--------------------------------------------------------------------------------
1 | package Google_07;
2 |
3 | public class Car {
4 | //характеристики
5 | private String carModel;
6 | private int carSpeed;
7 |
8 |
9 | public Car(String carModel, int carSpeed) {
10 | this.carModel = carModel;
11 | this.carSpeed = carSpeed;
12 | }
13 |
14 | @Override
15 | public String toString() {
16 | return carModel + " " + carSpeed;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/07. Google/Child.java:
--------------------------------------------------------------------------------
1 | package Google_07;
2 |
3 | public class Child {
4 | private String childName;
5 | private String childBirthday;
6 |
7 | public Child(String childName, String childBirthday) {
8 | this.childName = childName;
9 | this.childBirthday = childBirthday;
10 | }
11 |
12 | @Override
13 | public String toString() {
14 | return childName + " " + childBirthday;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/07. Google/Company.java:
--------------------------------------------------------------------------------
1 | package Google_07;
2 |
3 | public class Company {
4 | private String companyName;
5 | private String department;
6 | private double salary;
7 |
8 | public Company(String companyName, String department, double salary) {
9 | this.companyName = companyName;
10 | this.department = department;
11 | this.salary = salary;
12 | }
13 |
14 | @Override
15 | public String toString() {
16 | return companyName + " " + department + " " + String.format("%.2f", salary);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/07. Google/Main.java:
--------------------------------------------------------------------------------
1 | package Google_07;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
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 information = scanner.nextLine();
11 | //име на човека -> данни
12 | Map peopleData = new HashMap<>();
13 | while (!information.equals("End")) {
14 | //• "{Name} company {companyName} {department} {salary}"
15 | //• "{Name} pokemon {pokemonName} {pokemonType}"
16 | //• "{Name} parents {parentName} {parentBirthday}"
17 | //• "{Name} children {childName} {childBirthday}"
18 | //• "{Name} car {carModel} {carSpeed}"
19 | String [] parameters = information.split("\\s+");
20 | String personName = parameters[0];
21 | //проверка има ли такъв човек в списъка
22 | if (!peopleData.containsKey(personName)) {
23 | peopleData.put(personName, new Person());
24 | }
25 | String typeCommand = parameters[1];//"company", "pokemon", "parents", "children", "car"
26 | switch (typeCommand) {
27 | case "company":
28 | String companyName = parameters[2];
29 | String department = parameters[3];
30 | double salary = Double.parseDouble(parameters[4]);
31 | Company company = new Company(companyName, department, salary);
32 | peopleData.get(personName).setCompany(company);
33 | break;
34 | case "pokemon":
35 | String pokemonName = parameters[2];
36 | String pokemonType = parameters[3];
37 | Pokemon pokemon = new Pokemon(pokemonName, pokemonType);
38 | peopleData.get(personName).getPokemons().add(pokemon);
39 | break;
40 | case "parents":
41 | String parentName = parameters[2];
42 | String parentBirthday = parameters[3];
43 | Parent parent = new Parent(parentName, parentBirthday);
44 | peopleData.get(personName).getParents().add(parent);
45 | break;
46 | case "children":
47 | String childName = parameters[2];
48 | String childBirthday = parameters[3];
49 | Child child = new Child(childName, childBirthday);
50 | peopleData.get(personName).getChildren().add(child);
51 | break;
52 | case "car":
53 | String carModel = parameters[2];
54 | int carSpeed = Integer.parseInt(parameters[3]);
55 | Car car = new Car(carModel, carSpeed);
56 | peopleData.get(personName).setCar(car);
57 | break;
58 | }
59 |
60 | information = scanner.nextLine();
61 | }
62 |
63 | String searchedPerson = scanner.nextLine();
64 | System.out.println(searchedPerson);
65 |
66 | //данните на човек
67 | Person personalData = peopleData.get(searchedPerson);
68 | System.out.println(personalData);
69 |
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/07. Google/Parent.java:
--------------------------------------------------------------------------------
1 | package Google_07;
2 |
3 | public class Parent {
4 | private String parentName;
5 | private String parentBirthday;
6 |
7 | public Parent(String parentName, String parentBirthday) {
8 | this.parentName = parentName;
9 | this.parentBirthday = parentBirthday;
10 | }
11 |
12 | @Override
13 | public String toString() {
14 | return parentName + " " + parentBirthday;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/07. Google/Person.java:
--------------------------------------------------------------------------------
1 | package Google_07;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Calendar;
5 | import java.util.List;
6 | import java.util.ListIterator;
7 |
8 | public class Person {
9 | //1 компания
10 | private Company company;
11 | //1 кола
12 | private Car car;
13 | //списък с родители
14 | private List parents;
15 | //списък с деца
16 | private List children;
17 | //списък с покемони
18 | private List pokemons;
19 |
20 | public Person () {
21 | //company = null
22 | //car = null
23 | //parents = празен списък
24 | this.parents = new ArrayList<>();
25 | //children = празен списък
26 | this.children = new ArrayList<>();
27 | //pokemons = празен списък
28 | this.pokemons = new ArrayList<>();
29 | }
30 | public Person(Company company, Car car, List parents, List children, List pokemons) {
31 | this.company = company;
32 | this.car = car;
33 | this.parents = parents;
34 | this.children = children;
35 | this.pokemons = pokemons;
36 | }
37 |
38 | //setter
39 | public void setCompany(Company company) {
40 | this.company = company;
41 | }
42 |
43 | //getter for pokemons
44 | public List getPokemons() {
45 | return this.pokemons;
46 | }
47 |
48 | public List getParents() {
49 | return this.parents;
50 | }
51 |
52 | public List getChildren() {
53 | return this.children;
54 | }
55 |
56 | public void setCar(Car car) {
57 | this.car = car;
58 | }
59 |
60 | @Override
61 | public String toString() {
62 | StringBuilder builder = new StringBuilder();
63 | //Company:
64 | //Car:
65 | //Trabant 30
66 | //Pokemon:
67 | //Electrode Electricity
68 | //Parents:
69 | //Children:
70 | builder.append("Company:").append("\n");
71 | if (company != null) {
72 | builder.append(company).append("\n");
73 | }
74 | builder.append("Car:").append("\n");
75 | if (car != null) {
76 | builder.append(car).append("\n");
77 | }
78 |
79 | builder.append("Pokemon:").append("\n");
80 | for (Pokemon pokemon : pokemons) {
81 | builder.append(pokemon).append("\n");
82 | }
83 |
84 | builder.append("Parents:").append("\n");
85 | for (Parent parent : parents) {
86 | builder.append(parent).append("\n");
87 | }
88 |
89 | builder.append("Children:").append("\n");
90 | for (Child child : children) {
91 | builder.append(child).append("\n");
92 | }
93 |
94 | return builder.toString();
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/07. Google/Pokemon.java:
--------------------------------------------------------------------------------
1 | package Google_07;
2 |
3 | public class Pokemon {
4 | private String pokemonName;
5 | private String pokemonType;
6 |
7 | public Pokemon(String pokemonName, String pokemonType) {
8 | this.pokemonName = pokemonName;
9 | this.pokemonType = pokemonType;
10 | }
11 |
12 | @Override
13 | public String toString() {
14 | return pokemonName + " " + pokemonType;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/08. Family Tree/Main.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.familyTree;
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 | String input = scanner.nextLine();
9 | String info = input;
10 | input = scanner.nextLine();
11 | LinkedHashMap> childrenByParents = new LinkedHashMap<>();
12 | List personList = new ArrayList<>();
13 | Set inputSet = new LinkedHashSet<>();
14 |
15 | while (!input.equals("End")) {
16 |
17 | if (input.contains(" - ")) {
18 | String parentData = input.split(" - ")[0];
19 | String childData = input.split(" - ")[1];
20 | childrenByParents.putIfAbsent(parentData, new ArrayList<>());
21 | childrenByParents.get(parentData).add(childData);
22 | inputSet.add(parentData);
23 | inputSet.add(childData);
24 | } else {
25 | String[] data = input.split("\\s+");
26 | String name = data[0] + " " + data[1];
27 | String birthday = data[data.length - 1];
28 | Person person = new Person(name, birthday);
29 | personList.add(person);
30 | }
31 | input = scanner.nextLine();
32 | }
33 |
34 | for (String inputInfo : inputSet) {
35 | Person currentPerson = getPersonInfo(inputInfo, personList);
36 |
37 | for (Map.Entry> entry : childrenByParents.entrySet()) {
38 | Person parent = getPersonInfo(entry.getKey(), personList);
39 |
40 | for (String childInfo : entry.getValue()) {
41 | Person child = getPersonInfo(childInfo, personList);
42 |
43 | if (currentPerson == child) {
44 | currentPerson.addToParentList(parent);
45 | } else if (currentPerson == parent) {
46 | currentPerson.addToChildrenList(child);
47 | }
48 | }
49 | }
50 |
51 | }
52 |
53 | System.out.println(getPersonInfo(info, personList).toString());
54 | }
55 |
56 | private static Person getPersonInfo(String info, List personList) {
57 | Person currentPerson = null;
58 | for (Person person : personList) {
59 | if (person.getName().equals(info) || person.getBirthday().equals(info)) {
60 | currentPerson = person;
61 | }
62 | }
63 | return currentPerson;
64 | }
65 |
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/08. Family Tree/Person.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.familyTree;
2 |
3 |
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | public class Person {
8 | private String name;
9 | private String birthday;
10 | private List parentsList;
11 | private List childrenList;
12 |
13 |
14 | public Person(String name, String birthday) {
15 | this.name = name;
16 | this.birthday = birthday;
17 | this.parentsList = new ArrayList<>();
18 | this.childrenList = new ArrayList<>();
19 | }
20 |
21 | public String getName() {
22 | return name;
23 | }
24 |
25 | public String getBirthday() {
26 | return birthday;
27 | }
28 |
29 | public void addToParentList(Person person) {
30 | if (isNew(person, parentsList)) {
31 | this.parentsList.add(person);
32 | }
33 | }
34 |
35 | public void addToChildrenList(Person person) {
36 | if (isNew(person, childrenList)) {
37 | this.childrenList.add(person);
38 | }
39 | }
40 |
41 | public boolean isNew(Person person, List personList) {
42 | for (Person p : personList) {
43 | if (p.equals(person)) {
44 | return false;
45 | }
46 | }
47 | return true;
48 | }
49 |
50 |
51 |
52 | public String getOutputForList(List list) {
53 | StringBuilder output = new StringBuilder();
54 |
55 | if (!list.isEmpty()) {
56 | for (Person p : list) {
57 | output.append(String.format("%s %s%n", p.getName(), p.getBirthday()));
58 | }
59 | }
60 | return output.toString();
61 | }
62 |
63 | @Override
64 | public String toString() {
65 | return String.format("%s %s%nParents:%n%sChildren:%n%s", name, String.join("/", birthday), getOutputForList(parentsList), getOutputForList(childrenList));
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/09. Cat Lady/Cat.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.catLady;
2 |
3 | public class Cat {
4 | private String name;
5 |
6 | public Cat(String name) {
7 | this.name = name;
8 | }
9 |
10 | public String getName() {
11 | return name;
12 | }
13 |
14 | public void setName(String name) {
15 | this.name = name;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/09. Cat Lady/Cymric.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.catLady;
2 |
3 | public class Cymric extends Cat{
4 | private double furLength;
5 |
6 | public Cymric(String name, double furLength) {
7 | super(name);
8 | this.furLength = furLength;
9 | }
10 |
11 | @Override
12 | public String toString() {
13 | return String.format("Cymric %s %.2f",getName(),furLength);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/09. Cat Lady/Main.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.catLady;
2 |
3 | import java.util.*;
4 |
5 | public class Main {
6 |
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | String input = scanner.nextLine();
10 | Map catMap = new HashMap<>();
11 |
12 | while (!input.equals("End")) {
13 | String[] data = input.split("\\s+");
14 | String breed = data[0];
15 | Cat cat = null;
16 |
17 | switch (breed) {
18 | case "Siamese":
19 | cat = new Siamese(data[1], Double.parseDouble(data[2]));
20 | break;
21 | case "Cymric":
22 | cat = new Cymric(data[1], Double.parseDouble(data[2]));
23 | break;
24 | case "StreetExtraordinaire":
25 | cat = new StreetExtraordinaire(data[1], Double.parseDouble(data[2]));
26 | break;
27 | default:
28 | throw new RuntimeException("Unknown breed!");
29 | }
30 | catMap.put(data[1], cat);
31 | input = scanner.nextLine();
32 | }
33 | String name = scanner.nextLine();
34 | if (catMap.containsKey(name)) {
35 | System.out.println(catMap.get(name).toString());
36 | }
37 | }
38 |
39 | }
40 |
41 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/09. Cat Lady/Siamese.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.catLady;
2 |
3 | public class Siamese extends Cat {
4 | private double earSize;
5 |
6 | public Siamese(String name, double earSize) {
7 | super(name);
8 | this.earSize=earSize;
9 | }
10 |
11 | @Override
12 | public String toString() {
13 | return String.format("Siamese %s %.2f", getName(), earSize);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Defining Classes - Exercise/Solutions/09. Cat Lady/StreetExtraordinaire.java:
--------------------------------------------------------------------------------
1 | package definingClassesExercise.catLady;
2 |
3 | public class StreetExtraordinaire extends Cat{
4 | private double decibelsOfMeows;
5 |
6 | public StreetExtraordinaire(String name, double decibelsOfMeows) {
7 | super(name);
8 | this.decibelsOfMeows = decibelsOfMeows;
9 | }
10 |
11 | @Override
12 | public String toString() {
13 | return String.format("StreetExtraordinaire %s %.2f", getName(), decibelsOfMeows);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Demo/Demo_FunctionalProgramming.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Demo_FunctionalProgramming {
6 | public static void main(String[] args) {
7 | //Function<приема, връща> -> apply
8 | //Consumer<приема> -> void -> accept
9 | //Supplier<връща> -> get
10 | //Predicate<приема> -> връща true / false -> test
11 | //BiFunction<приема1, приема2, връща> -> apply
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Demo/StickyFingers_02.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.Scanner;
4 |
5 | public class StickyFingers_02 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int size = Integer.parseInt(scanner.nextLine()); //брой редове = брой колони
9 | String [] directions = scanner.nextLine().split(",");
10 | //"up,right,down,down,left".split(",") -> ["up", "right", "down", "down", "left"]
11 |
12 | //1. приготвяме полето (матрица)
13 | String [][] matrix = new String[size][size];
14 | fillMatrix(matrix, scanner);
15 |
16 | //2. намираме от къде започва да се движи крадецът
17 | int rowThief = -1; //текущ ред на крадец
18 | int colThief = -1; //текущ колона на крадец
19 |
20 | for (int row = 0; row < size; row++) {
21 | for (int col = 0; col < size; col++) {
22 | if (matrix[row][col].equals("D")) {
23 | rowThief = row;
24 | colThief = col;
25 | break;
26 | }
27 | }
28 | }
29 |
30 | int totalStolenMoney = 0; //общо откраднати пари
31 | //3. изпълняваме посоките
32 | for (String direction : directions) {
33 | //direction = left/right/up/down
34 | switch(direction) {
35 | case "left":
36 | if (colThief - 1 < 0) {
37 | //излизам от матрицата
38 | System.out.println("You cannot leave the town, there is police outside!");
39 | } else {
40 | //мога да се придвижа
41 | matrix[rowThief][colThief] = "+";
42 | //премествам
43 | colThief--;
44 | }
45 | break;
46 | case "right":
47 | if (colThief + 1 >= size) {
48 | //излизам от матрицата
49 | System.out.println("You cannot leave the town, there is police outside!");
50 | } else {
51 | //мога да се придвижа
52 | matrix[rowThief][colThief] = "+";
53 | //премествам
54 | colThief++;
55 | }
56 | break;
57 | case "up":
58 | if (rowThief - 1 < 0) {
59 | //излизам от матрицата
60 | System.out.println("You cannot leave the town, there is police outside!");
61 | } else {
62 | //мога да се придвижа
63 | matrix[rowThief][colThief] = "+";
64 | //премествам
65 | rowThief--;
66 | }
67 | break;
68 | case "down":
69 | if (rowThief + 1 >= size) {
70 | //излизам от матрицата
71 | System.out.println("You cannot leave the town, there is police outside!");
72 | } else {
73 | //мога да се придвижа
74 | matrix[rowThief][colThief] = "+";
75 | //преместваме
76 | rowThief++;
77 | }
78 | break;
79 | }
80 | //знам къде се е преместил крадецът
81 | //ред: rowThief, колона: colThief
82 |
83 | String currentPosition = matrix[rowThief][colThief]; //на какво е стъпил моя крадец
84 | if (currentPosition.equals("$")) {
85 | //стигнали сме къща -> ограбваме
86 | int stolenMoney = rowThief * colThief; //колко пари са откраднати от тази къща
87 | System.out.printf("You successfully stole %d$.%n", stolenMoney);
88 | totalStolenMoney += stolenMoney;
89 | matrix[rowThief][colThief] = "D";
90 | } else if (currentPosition.equals("P")) {
91 | //стигнали полиция -> хващат ни и прекратяваме
92 | System.out.printf("You got caught with %d$, and you are going to jail.%n", totalStolenMoney);
93 | matrix[rowThief][colThief] = "#";
94 | printMatrix(matrix);
95 | return;
96 | } else if (currentPosition.equals("+")) {
97 | matrix[rowThief][colThief] = "D";
98 | }
99 |
100 | }
101 | //минаваме през всички посоки и не сме хванати
102 | System.out.printf("Your last theft has finished successfully with %d$ in your pocket.%n", totalStolenMoney);
103 | printMatrix(matrix);
104 | }
105 |
106 | private static void fillMatrix(String[][] matrix, Scanner scanner) {
107 | for (int row = 0; row < matrix.length ; row++) {
108 | //scanner.nextLine() -> "1 2 3"
109 | //scanner.nextLine().split(" ") -> ["1", "2", "3"]
110 | matrix[row] = scanner.nextLine().split("\\s+");
111 | }
112 | }
113 |
114 | private static void printMatrix(String[][] matrix) {
115 | for (int row = 0; row < matrix.length; row++) {
116 | for (int col = 0; col < matrix.length; col++) {
117 | System.out.print(matrix[row][col] + " ");
118 | }
119 | System.out.println(); //свали курсора на следващия ред
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/AppliedArithmetics_04.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.function.Consumer;
7 | import java.util.function.Function;
8 | import java.util.stream.Collectors;
9 |
10 | public class AppliedArithmetics_04 {
11 | public static void main(String[] args) {
12 | Scanner scanner = new Scanner(System.in);
13 | //Function<приема, връща> -> apply
14 | //Consumer<приема> -> void -> accept
15 | //Supplier<връща> -> get
16 | //Predicate<приема> -> връща true / false -> test
17 | //BiFunction<приема1, приема2, връща> -> apply
18 |
19 | List numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
20 | .map(Integer::parseInt).collect(Collectors.toList());
21 |
22 | String command = scanner.nextLine();
23 | //add -> добавяме 1 към всеки елемент на списъка: приема списък -> връщаме списък с модифицирани елементи
24 | Function, List> addCommand = list -> list.stream().map(number -> number += 1).collect(Collectors.toList());
25 |
26 | //multiply -> умножаваме всеки един от елементите по 2: приема списък -> връщаме списък с модифицирани елементи
27 | Function, List> multiplyCommand = list -> list.stream().map(number -> number *= 2).collect(Collectors.toList());
28 |
29 | //subtract -> изважда 1 от всеки елемент на списъка: приема списък -> връщаме списък с модифицирани елементи
30 | Function, List> subtractCommand = list -> list.stream().map(number -> number -= 1).collect(Collectors.toList());
31 |
32 | //print -> принтира всички елементи на нов ред: приема списък -> печатаме всеки елемент
33 | Consumer> printCommand = list -> list.forEach(number -> System.out.print(number + " "));
34 |
35 | while (!command.equals("end")) {
36 | //command = "add", "multiply", "subtract", "print"
37 | switch (command) {
38 | case "add":
39 | numbers = addCommand.apply(numbers);
40 | break;
41 | case "multiply":
42 | numbers = multiplyCommand.apply(numbers);
43 | break;
44 | case "subtract":
45 | numbers = subtractCommand.apply(numbers);
46 | break;
47 | case "print":
48 | printCommand.accept(numbers);
49 | System.out.println();
50 | break;
51 | }
52 | command = scanner.nextLine();
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/ConsumerPrint_01.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.Scanner;
4 | import java.util.function.Consumer;
5 |
6 | public class ConsumerPrint_01 {
7 | public static void main(String[] args) {
8 | //Function<приема, връща> -> apply
9 | //Consumer<приема> -> void -> accept
10 | //Supplier<връща> -> get
11 | //Predicate<приема> -> връща true / false -> test
12 | //BiFunction<приема1, приема2, връща> -> apply
13 | Scanner scanner = new Scanner(System.in);
14 | String input = scanner.nextLine(); //"Peter George Alex"
15 | String[] names = input.split("\\s+"); //["Peter", "George", "Alex"]
16 |
17 | //начин 1: без functional programming
18 | /*for (String name : names) {
19 | System.out.println(name);
20 | }*/
21 |
22 | //начин 2:
23 | //име -> печатам
24 | /*Consumer printName = name -> System.out.println(name);
25 | //printName приема String name и я отпечатва
26 |
27 | for (String name : names) {
28 | printName.accept(name);
29 | }*/
30 |
31 | //начин 3:
32 | //масив с имена -> печатам всяко едно име
33 | Consumer printArray = array -> {
34 | for (String name : array) {
35 | System.out.println(name);
36 | }
37 | };
38 | //printArray приема масив от текстове и го отпечатва
39 | printArray.accept(names);
40 |
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/CustomComparator_08.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.Arrays;
4 | import java.util.Comparator;
5 | import java.util.List;
6 | import java.util.Scanner;
7 | import java.util.stream.Collectors;
8 |
9 | public class CustomComparator_08 {
10 | public static void main(String[] args) {
11 | //Function<приема, връща> -> apply
12 | //Consumer<приема> -> void -> accept
13 | //Supplier<връща> -> get
14 | //Predicate<приема> -> false / true -> test
15 | //BiFunction<приема1, приема2, връща> -> apply
16 | Scanner scanner = new Scanner(System.in);
17 | List numbers = Arrays.stream(scanner.nextLine().split("\\s+")).map(Integer::parseInt).collect(Collectors.toList());
18 |
19 |
20 | //comparator -> function приема 2 елемента и връща цяло число (0, 1, -1)
21 | //0 -> първия елемент == втория елемент
22 | //1 -> първия елемент > втория елемент
23 | //-1 -> първия елемент < втория елемент
24 |
25 | //sorted (0) -> не разменя двата елемента
26 | //sorted(1) -> разменя елементите
27 | //sorted(-1) -> не разменя елементите
28 |
29 | //2 0 3 5 4
30 | //comparator (2, 0) -> 1 отива sorted -> разменя 2 и 0 -> 0 2 3 5 4
31 | //comparator (2, 3) -> -1 отива в sorted -> не разменя -> 0 2 3 5 4
32 | //comparator (3, 5) -> -1 отива в sorted -> не разменя -> 0 2 3 5 4
33 | //comparator (5, 4) -> 1 отива sorted -> разменя 5 и 4 -> 0 2 3 4 5
34 | //ляво -> четно, дясно -> нечетно
35 | Comparator comparator = ((first, second) -> {
36 | //първо четно, второ нечетно -> не разменяме
37 | if (first % 2 == 0 && second % 2 != 0) {
38 | return -1;
39 | }
40 | //първо нечетно, второ четно -> размяна
41 | else if (first % 2 != 0 && second % 2 == 0) {
42 | return 1;
43 | }
44 | //първо четно, второто четно
45 | //първи нечетно, второто нечетно
46 | else {
47 | return first.compareTo(second);
48 | //first == second -> 0 -> няма размяна
49 | //first < second -> -1 -> няма размяна
50 | //first > second -> 1 -> има размяна
51 | }
52 |
53 | });
54 |
55 | numbers.stream().sorted(comparator).forEach(number -> System.out.print(number + " "));
56 |
57 | //1 2 3 4 5 6
58 | //1 и 2 -> comparator 1 -> sorted(1) -> размяна -> 2 1 3 4 5 6
59 | //1 и 3 -> comparator -1 -> sorted(-1) -> няма размяна -> 2 1 3 4 5 6
60 | //3 и 4 -> comparator 1 -> sorted (1) -> размяна -> 2 1 4 3 5 6
61 |
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/CustomMinFunction_03.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
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.function.Consumer;
8 | import java.util.function.Function;
9 | import java.util.stream.Collectors;
10 |
11 | public class CustomMinFunction_03 {
12 | public static void main(String[] args) {
13 | Scanner scanner = new Scanner(System.in);
14 | //Function<приема, връща> -> apply
15 | //Consumer<приема> -> void -> accept
16 | //Supplier<връща> -> get
17 | //Predicate<приема> -> връща true / false -> test
18 | //BiFunction<приема1, приема2, връща> -> apply
19 |
20 | List numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
21 | .map(Integer::parseInt).collect(Collectors.toList());
22 |
23 | //начин 1: без функционално програмиране
24 | //System.out.println(Collections.min(numbers));
25 |
26 | //начин 2:
27 | //лист -> отпечатаме минималното число
28 | /*Consumer> printMinNumber = list -> System.out.println(Collections.min(list));
29 | //printMinNumber приема лист и отпечатва минималния елемент в листа
30 | printMinNumber.accept(numbers);*/
31 |
32 | //начин 3:
33 | //лист -> връща минималния елемент в списъка
34 | Function, Integer> getMinNumber = list -> Collections.min(list);
35 | //getMinNumber приема лист и да връща стойност (цяло число), която е минималния елемент
36 | int minElement = getMinNumber.apply(numbers);
37 | System.out.println(minElement);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/FindSmallestElement_07.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
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.function.Function;
8 | import java.util.stream.Collectors;
9 |
10 | public class FindSmallestElement_07 {
11 | public static void main(String[] args) {
12 | Scanner scanner = new Scanner(System.in);
13 | //Function<приема, връща> -> apply
14 | //Consumer<приема> -> void -> accept
15 | //Supplier<връща> -> get
16 | //Predicate<приема> -> връща true / false -> test
17 | //BiFunction<приема1, приема2, връща> -> apply
18 |
19 | List numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
20 | .map(Integer::parseInt).collect(Collectors.toList());
21 |
22 | //lastIndexOf -> връща последния индекс, на който срещаме дадения елемент
23 | //indexOf -> връща първия индекс, на който срещаме дадения елемент
24 |
25 |
26 | //начин 1:
27 | //лист -> отпечатвам най-десния (последния) индекс на най-малкото число
28 | /*Consumer> printLastIndexOfMinElement = list -> {
29 | int minElement = Collections.min(list);
30 | System.out.println(list.lastIndexOf(minElement));
31 | };
32 | printLastIndexOfMinElement.accept(numbers);*/
33 |
34 | //начин 2:
35 | //лист -> връщам последния индекс, на който срещаме мининмалния елемент
36 | Function, Integer> getLastIndexOfMinElement = list -> list.lastIndexOf(Collections.min(list));
37 | int lastIndex = getLastIndexOfMinElement.apply(numbers);
38 | System.out.println(lastIndex);
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/KnightsHonor_02.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 | import java.util.function.Consumer;
6 |
7 | public class KnightsHonor_02 {
8 | public static void main(String[] args) {
9 | //Function<приема, връща> -> apply
10 | //Consumer<приема> -> void -> accept
11 | //Supplier<връща> -> get
12 | //Predicate<приема> -> връща true / false -> test
13 | //BiFunction<приема1, приема2, връща> -> apply
14 | Scanner scanner = new Scanner(System.in);
15 | String input = scanner.nextLine(); //"Peter George Alex"
16 | String[] names = input.split("\\s+"); //["Peter", "George", "Alex"]
17 |
18 | //име -> отпечатам "Sir " + име
19 | Consumer printName = name -> System.out.println("Sir " + name);
20 | Arrays.stream(names).forEach(printName);
21 |
22 | /*for (String name : names) {
23 | printName.accept(name);
24 | }*/
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/ListPredicates_09.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.function.BiFunction;
7 | import java.util.stream.Collectors;
8 |
9 | public class ListPredicates_09 {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 | //Function<приема, връща> -> apply
13 | //Consumer<приема> -> void -> accept
14 | //Supplier<връща> -> get
15 | //Predicate<приема> -> връща true / false -> test
16 | //BiFunction<приема1, приема2, връща> -> apply
17 |
18 | int n = Integer.parseInt(scanner.nextLine());
19 | List numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
20 | .map(Integer::parseInt).collect(Collectors.toList());
21 |
22 | //отпечатвам всички числа от 1 до n, ако се дели на всички числа в списъка
23 |
24 | //приемам: число, списък за проверка
25 | //връщам: true / false
26 | //true -> ако числото се дели на всички числа в списъка
27 | //false -> ако числото не се дели на всички числа в списъка
28 | BiFunction, Boolean> isDivisible = ((number, list) -> {
29 | for (int numInList : list) {
30 | if (number % numInList != 0) {
31 | return false;
32 | }
33 | }
34 | //преминали през всички числа в списъка и всички делят number
35 | return true;
36 | });
37 |
38 | for (int number = 1; number <= n; number++) {
39 | if (isDivisible.apply(number, numbers)) {
40 | System.out.print(number + " ");
41 | }
42 | }
43 |
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/PredicateForNames_06.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 | import java.util.function.Predicate;
6 |
7 | public class PredicateForNames_06 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | //Function<приема, връща> -> apply
11 | //Consumer<приема> -> void -> accept
12 | //Supplier<връща> -> get
13 | //Predicate<приема> -> връща true / false -> test
14 | //BiFunction<приема1, приема2, връща> -> apply
15 |
16 | int n = Integer.parseInt(scanner.nextLine()); //дължина за сравнение
17 | String[] names = scanner.nextLine().split("\\s+");
18 |
19 | //име -> true (дължина <= n) / false (дължина > n)
20 | Predicate checkValidLength = name -> name.length() <= n;
21 | //останат само имената, които отговарят на условието
22 | Arrays.stream(names).filter(checkValidLength) //филтрираме
23 | .forEach(System.out::println); //отпечатваме останалите елементи
24 | //обхождат се всички елементи по отделно
25 | //true -> оставя елемента в списъка
26 | //false -> премахва от списъка
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/PredicateParty_10.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.Scanner;
6 | import java.util.function.Predicate;
7 | import java.util.stream.Collectors;
8 |
9 | public class PredicateParty_10 {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 |
13 | ArrayList guests = Arrays.stream(scanner.nextLine().split("\\s+"))
14 | .collect(Collectors.toCollection(ArrayList::new));
15 |
16 | String line = scanner.nextLine();
17 |
18 |
19 |
20 | while (!line.equals("Party!")){
21 |
22 | Predicate predicate = null;
23 |
24 | String criteria = line.split("\\s+")[2];
25 |
26 | if(line.contains("Length")){
27 | predicate = x -> x.length() == Integer.parseInt(criteria);
28 | }else if(line.contains("StartsWith")){
29 | predicate = x -> x.startsWith(criteria);
30 | }else{
31 | predicate = x -> x.endsWith(criteria);
32 | }
33 |
34 | if(line.contains("Remove")){
35 | ArrayList toRemove = new ArrayList<>();
36 | for (String guest : guests) {
37 | if(predicate.test(guest)){
38 | toRemove.add(guest);
39 | }
40 | }
41 |
42 | guests.removeAll(toRemove);
43 | }else{
44 | ArrayList toAdd = new ArrayList<>();
45 | for (String guest : guests) {
46 | if(predicate.test(guest)){
47 | toAdd.add(guest);
48 | }
49 | }
50 | guests.addAll(toAdd);
51 | }
52 |
53 | line = scanner.nextLine();
54 | }
55 |
56 | if(guests.isEmpty()){
57 | System.out.println("Nobody is going to the party!");
58 | }else{
59 | System.out.println(guests.stream().sorted().collect(Collectors.toCollection(ArrayList::new)).toString().replaceAll("([\\[\\]])", "") + " are going to the party!");
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/ReverseAndExclude_05.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
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.function.Predicate;
8 | import java.util.stream.Collectors;
9 |
10 | public class ReverseAndExclude_05 {
11 | public static void main(String[] args) {
12 | Scanner scanner = new Scanner(System.in);
13 | //Function<приема, връща> -> apply
14 | //Consumer<приема> -> void -> accept
15 | //Supplier<връща> -> get
16 | //Predicate<приема> -> връща true / false -> test
17 | //BiFunction<приема1, приема2, връща> -> apply
18 |
19 | List numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
20 | .map(Integer::parseInt).collect(Collectors.toList());
21 |
22 | int n = Integer.parseInt(scanner.nextLine());
23 |
24 | //1. reverse on list
25 | Collections.reverse(numbers);
26 | //{1, 2, 3, 4, 5, 6}.reverse() -> {6, 5, 4, 3, 2, 1}
27 |
28 | //2. премахваме всички елементи, които се делят на n
29 | //число -> дели ли се или не се дели на n (true / false)
30 | Predicate checkDivision = number -> number % n == 0;
31 | //връща true -> n е делител на числото
32 | //връща false -> n не е делител на числото
33 | numbers.removeIf(checkDivision);
34 | //премахни елементите, за които checkDivision връща резултат true
35 |
36 | //3. отпечатваме крайния списък
37 | numbers.forEach(number -> System.out.print(number + " "));
38 |
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Solutions/ThePartyReservationFilterModule_11.java:
--------------------------------------------------------------------------------
1 | package FunctionalProgramming;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.HashMap;
6 | import java.util.Scanner;
7 | import java.util.function.Predicate;
8 | import java.util.stream.Collectors;
9 |
10 | public class ThePartyReservationFilterModule_11 {
11 | public static void main(String[] args) {
12 | Scanner scanner = new Scanner(System.in);
13 |
14 | ArrayList guests = Arrays.stream(scanner.nextLine().split("\\s+"))
15 | .collect(Collectors.toCollection(ArrayList::new));
16 |
17 | String line = scanner.nextLine();
18 |
19 | HashMap predicates = new HashMap<>();
20 |
21 | while (!line.equals("Print")){
22 |
23 | String[] tokens = line.substring(line.indexOf(";") + 1).split("([ ;]+)");
24 | int index = 2;
25 | if(tokens.length == 2){
26 | index = 1;
27 | }
28 | String name = tokens[0] + tokens[index];
29 |
30 | if(line.contains("Add")){
31 | Predicate predicate = null;
32 | switch (tokens[0]){
33 | case "Starts":
34 | predicate = s -> s.startsWith(tokens[2]);
35 | predicates.putIfAbsent(name, predicate);
36 | break;
37 | case "Ends":
38 | predicate = s -> s.endsWith(tokens[2]);
39 | predicates.putIfAbsent(name, predicate);
40 | break;
41 | case "Length":
42 | predicate = s -> s.length() == Integer.parseInt(tokens[2]);
43 | predicates.putIfAbsent(name, predicate);
44 | break;
45 | case "Contains":
46 | predicate = s -> s.contains(tokens[1]);
47 | predicates.putIfAbsent(name, predicate);
48 | break;
49 | }
50 | }else{
51 | predicates.remove(name);
52 | }
53 | line = scanner.nextLine();
54 | }
55 |
56 | for (String guest : guests) {
57 | boolean isGoing = true;
58 |
59 | for (String entry : predicates.keySet()) {
60 | if(predicates.get(entry).test(guest)){
61 | isGoing = false;
62 | break;
63 | }
64 | }
65 |
66 | if(isGoing){
67 | System.out.print(guest + " ");
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Theory/FunctionalProgramming_Exercise_Theory.txt:
--------------------------------------------------------------------------------
1 | Function<приема, връща> -> apply
2 | Consumer<приема> -> void -> accept
3 | Supplier<връща> -> get
4 | Predicate<приема> -> връща true / false -> test
5 | BiFunction<приема1, приема2, връща> -> apply
--------------------------------------------------------------------------------
/Functional Porgramming - Exercise/Videos/FunctionalProgramming_Videos.txt:
--------------------------------------------------------------------------------
1 | 08. Custom Comparator -> https://pastebin.com/GNegBdyt
2 | Видео: https://youtu.be/b82pQ08w7wg?t=7583
3 |
4 | 02. Throne Conquering -> https://pastebin.com/tNbTKSpK
5 | видео: https://youtu.be/Tx2xO5zTqNk?t=8330
6 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Demo/RallyRacing_02.java:
--------------------------------------------------------------------------------
1 | package assArrays;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | public class RallyRacing_02 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | int n = Integer.parseInt(scanner.nextLine()); //брой редове = брой колони
11 | String carNumber = scanner.nextLine(); //номер
12 | int km = 0; // изминати километри от колата
13 |
14 | String [][] trace = new String [n][n];
15 | fillMatrix(trace, scanner);
16 |
17 | int currentRow = 0; //ред, на който се намира колата
18 | int currentCol = 0; //колона, на която се намира колата
19 |
20 | //намираме тунелите -> 2 тунела
21 | //тунел 1 -> ред, колона
22 | //тунел 2 -> ред, колона
23 | //лист с 4 елемента ->
24 | // 1ви елемент (ред на тунел1), 2ри елемент (колона на тунел1)
25 | // 3ти елемент (ред на тунел2), 4ти елемент (колона на тунел2)
26 | List tunnelsCoordinates = new ArrayList<>();
27 | findTunnels(trace, tunnelsCoordinates);
28 |
29 | //започваме движения
30 | String direction = scanner.nextLine();
31 | while (!direction.equals("End")) {
32 |
33 | switch(direction) {
34 | case "left":
35 | currentCol--;
36 | break;
37 | case "right":
38 | currentCol++;
39 | break;
40 | case "up":
41 | currentRow--;
42 | break;
43 | case "down":
44 | currentRow++;
45 | break;
46 | }
47 | //currentRow, currentCol -> къде се намира колата след преместване
48 | //там, където е преместена какво има?
49 | String movedPlace = trace[currentRow][currentCol]; //място по трасето, на което сме се преместили
50 |
51 | if (movedPlace.equals(".")) {
52 | km += 10;
53 | } else if (movedPlace.equals("F")) {
54 | System.out.printf("Racing car %s finished the stage!%n", carNumber);
55 | km += 10;
56 | break;
57 | } else if (movedPlace.equals("T")) {
58 | //стигаме до тунел -> отиваме до другия тунел
59 | //координатите на колата = кординатите на втория тунел
60 | //tunnelCoordinates -> лист с 4 елемента ->
61 | // 1ви елемент (ред на тунел1), 2ри елемент (колона на тунел1)
62 | // 3ти елемент (ред на тунел2), 4ти елемент (колона на тунел2)
63 | currentRow = tunnelsCoordinates.get(2);
64 | currentCol = tunnelsCoordinates.get(3);
65 | km += 30;
66 | //заместваме тунелите с точка, защото вече сме преминали
67 | trace[tunnelsCoordinates.get(0)][tunnelsCoordinates.get(1)] = "."; //замествам първия тунел с .
68 | trace[tunnelsCoordinates.get(2)][tunnelsCoordinates.get(3)] = "."; //замествам втория тунел с .
69 | }
70 |
71 | direction = scanner.nextLine();
72 | }
73 |
74 | if (direction.equals("End")) {
75 | System.out.printf("Racing car %s DNF.%n", carNumber);
76 | }
77 |
78 | System.out.printf("Distance covered %d km.%n", km);
79 |
80 | //там където е колата да слагаме C
81 | trace[currentRow][currentCol] = "C";
82 |
83 | //принтираме финалното трасе
84 | printMatrix(trace);
85 | }
86 |
87 | private static void findTunnels(String[][] trace, List tunnelsCoordinates) {
88 | for (int row = 0; row < trace.length; row++) {
89 | for (int col = 0; col < trace.length; col++) {
90 | String currentElement = trace[row][col];
91 | if (currentElement.equals("T")) {
92 | tunnelsCoordinates.add(row);
93 | tunnelsCoordinates.add(col);
94 | }
95 | }
96 | }
97 | }
98 | private static void printMatrix(String[][] matrix) {
99 | for (int row = 0; row < matrix.length; row++) {
100 | for (int col = 0; col < matrix.length; col++) {
101 | System.out.print(matrix[row][col]);
102 | }
103 | System.out.println(); //свали курсора на следващия ред
104 | }
105 | }
106 |
107 | private static void fillMatrix(String[][] matrix, Scanner scanner) {
108 | for (int row = 0; row < matrix.length ; row++) {
109 | matrix[row] = scanner.nextLine().split("\\s+");
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/Crossfire_07.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 | import java.util.Scanner;
7 |
8 | public class Crossfire_07 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 | //вход
12 | int[] dimensions = Arrays.stream(scanner.nextLine().split("\\s+")).mapToInt(Integer::parseInt).toArray();
13 | int rows = dimensions[0];
14 | int cols = dimensions[1];
15 |
16 |
17 | List> matrix = new ArrayList<>();
18 | fillMatrix(matrix, rows, cols);
19 |
20 | String command = scanner.nextLine();
21 | while (!command.equals("Nuke it from orbit")) {
22 | String[] tokens = command.split("\\s+"); // 3 4 1
23 | int row = Integer.parseInt(tokens[0]);
24 | int col = Integer.parseInt(tokens[1]); //индексът на елемента в листа
25 | int radius = Integer.parseInt(tokens[2]);
26 |
27 | //destroy up, down
28 | for (int currentRow = row - radius; currentRow <= row + radius ; currentRow++) {
29 | if(isInMatrix(currentRow, col, matrix)) { //валидираме реда от който ще вземем
30 | matrix.get(currentRow).remove(col);
31 | }
32 | }
33 |
34 | //destroy left. right
35 | for (int currentColumn = col + radius; currentColumn >- col - radius; currentColumn--) {
36 | if(isInMatrix(row, currentColumn, matrix)) { //валидираме колоната от който ще вземем
37 | matrix.get(row).remove(currentColumn);
38 | }
39 | }
40 |
41 | matrix.removeIf(List::isEmpty);
42 |
43 |
44 | command = scanner.nextLine();
45 |
46 | }
47 |
48 | printMatrix(matrix);
49 | }
50 |
51 | private static boolean isInMatrix(int row, int col, List> matrix) {
52 | return row >= 0 && row < matrix.size() && col >= 0 && col < matrix.get(row).size();
53 | }
54 |
55 |
56 | //fill matrix
57 | private static void fillMatrix(List> matrix, int rows, int cols) {
58 | int number = 1;
59 | for (int row = 0; row < rows; row++) {
60 | matrix.add(new ArrayList<>());
61 | for (int col = 0; col < cols; col++) {
62 | matrix.get(row).add(number++);
63 | }
64 | }
65 | }
66 |
67 | //print matrix
68 | public static void printMatrix(List> matrix) {
69 | for (List row : matrix) {
70 | for (int element : row ) {
71 | System.out.print(element + " ");
72 | }
73 | System.out.println();
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/DiagonalDifference_03.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class DiagonalDifference_03 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | int n = Integer.parseInt(scanner.nextLine()); //бр. редове = бр. колони
10 | int [][] matrix = new int [n][n];
11 |
12 | //1. напълваме матрицата
13 | fillMatrix(matrix, scanner);
14 | //2. сума на числата на главния диагонал
15 | int sumPrimary = getSumElementsOnPrimaryDiagonal(matrix);
16 | //3. сума на числата на второстепенния диагонал
17 | int sumSecondary = getSumElementsOnSecondaryDiagonal(matrix);
18 | //4. принтираме абс. стойност на разликата
19 | System.out.println(Math.abs(sumPrimary - sumSecondary));
20 | }
21 |
22 | private static int getSumElementsOnSecondaryDiagonal(int [][] matrix) {
23 | int sum = 0; //сума на числата от второстепенния диагонал
24 | //всички елементи в матрицата -> сумирам тези, които са на второстепенния диагонал
25 | for (int row = 0; row < matrix.length; row++) {
26 | for (int col = 0; col < matrix.length; col++) {
27 | int currentElement = matrix[row][col]; //текущия елемент
28 | if (col == matrix.length - row - 1) {
29 | //елементът е на второстепенния диагонал
30 | sum += currentElement;
31 | }
32 | }
33 | }
34 | return sum;
35 | }
36 |
37 | private static int getSumElementsOnPrimaryDiagonal(int [][] matrix) {
38 | int sum = 0; //сума на числата от главния диагонал
39 | //всички елементи в матрицата -> сумирам тези, които са на главния диагонал (кол = ред)
40 | for (int row = 0; row < matrix.length; row++) {
41 | for (int col = 0; col < matrix.length; col++) {
42 | int currentElement = matrix[row][col]; //текущия елемент
43 | if (row == col) {
44 | //елементът е на главния диагонал
45 | sum += currentElement;
46 | }
47 | }
48 | }
49 | return sum;
50 | }
51 |
52 | private static void fillMatrix(int[][] matrix, Scanner scanner) {
53 | for (int row = 0; row < matrix.length ; row++) {
54 | for (int col = 0; col < matrix.length; col++) {
55 | matrix[row][col] = scanner.nextInt();
56 | }
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/FillTheMatrix_01.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class FillTheMatrix_01 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | //1. входни данни
9 | //"3, A".split(", ") -> ["3", "A"]
10 | String input = scanner.nextLine();
11 | int n = Integer.parseInt(input.split(", ")[0]); //бр.редове = бр. колони
12 | String pattern = input.split(", ")[1];//шаблон за попълване -> "A" или "B"
13 |
14 | int [][] matrix = new int [n][n];
15 |
16 | if (pattern.equals("A")) {
17 | //pattern А -> по колони
18 | fillMatrixPatternA(matrix);
19 | } else if (pattern.equals("B")) {
20 | //pattern B -> по колони
21 | //четна (2-ра, 4-та, 6-та, 8-та, ...) -> редове от последен към първи
22 | //нечетна (1-ва, 3-та, 5-та, ...) -> редове от първия към последния
23 | fillMatrixPatternB(matrix);
24 | }
25 |
26 | printMatrix(matrix);
27 | }
28 |
29 | private static void printMatrix(int[][] matrix) {
30 | for (int row = 0; row < matrix.length; row++) {
31 | for (int col = 0; col < matrix.length; col++) {
32 | System.out.print(matrix[row][col] + " ");
33 | }
34 | System.out.println(); //свали курсора на следващия ред
35 | }
36 | }
37 |
38 | private static void fillMatrixPatternB(int[][] matrix) {
39 | int startNumber = 1; //числа за попълване на матрицата
40 | for (int col = 0; col < matrix.length; col++) {
41 | //col + 1 -> пореден номер на колоната
42 | if ((col + 1) % 2 == 0) {
43 | //поредния номер на колоната е четен (2-ра, 4-та, 6-та, 8-та, ...) -> редове от последен към първи
44 | //2-ра -> индекс 1
45 | //4-та ->
46 | for (int row = matrix.length - 1; row >= 0 ; row--) {
47 | matrix[row][col] = startNumber;
48 | startNumber++;
49 | }
50 | } else {
51 | //поредния номер на колоната е нечетен (1-ва, 3-та, 5-та, ...) -> редове от първия към последния
52 | for (int row = 0; row <= matrix.length - 1; row++) {
53 | matrix[row][col] = startNumber;
54 | startNumber++;
55 | }
56 | }
57 | }
58 | }
59 |
60 | private static void fillMatrixPatternA(int [][] matrix) {
61 | int startNumber = 1;
62 | //бр. редове = бр. колони -> matrix.length
63 | for (int col = 0; col < matrix.length; col++) {
64 | for (int row = 0; row < matrix.length; row++) {
65 | matrix[row][col] = startNumber;
66 | startNumber++;
67 | }
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/MatrixOfPalindromes_02.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class MatrixOfPalindromes_02 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int rows = scanner.nextInt();
9 | int cols = scanner.nextInt();
10 |
11 | String[][] matrix = new String[rows][cols];
12 |
13 | char startLetter = 'a';
14 | for (int row = 0; row < rows ; row++) {
15 | for (int col = 0; col < cols ; col++) {
16 | //(a -> b -> c)(startLetter + 1)()
17 | String palindrome = "" + startLetter + (char)(startLetter + col) + startLetter;
18 | matrix[row][col] = palindrome;
19 | }
20 | startLetter = (char)(startLetter + 1);
21 | }
22 |
23 | printMatrix(matrix, rows, cols);
24 | }
25 |
26 | private static void printMatrix(String[][] matrix, int rows, int cols) {
27 | for (int row = 0; row < rows; row++) {
28 | for (int col = 0; col < cols; col++) {
29 | System.out.print(matrix[row][col] + " ");
30 | }
31 | System.out.println();
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/MatrixShuffling_05.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class MatrixShuffling_05 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | String dimensionsInput = scanner.nextLine(); //"3 4".split(" ") -> ["3", "4"]
10 | int rows = Integer.parseInt(dimensionsInput.split("\\s+")[0]);
11 | int cols = Integer.parseInt(dimensionsInput.split("\\s+")[1]);
12 |
13 | String [][] matrix = new String[rows][cols];
14 |
15 | //1. попълваме матрицата с данни от конзолата
16 | fillMatrix(matrix, scanner);
17 |
18 | String command = scanner.nextLine();
19 | while (!command.equals("END")) {
20 | //валидираме команда
21 | //валидна
22 | if (validateCommand(command, rows, cols)) {
23 | String [] commandParts = command.split("\\s+");
24 | //command = "swap 1 2 2 3"
25 | //"swap 1 2 2 3".split(" ") -> ["swap", "1", "2", "2", "3"]
26 |
27 | //място, от което взимам първия елемент
28 | int row1 = Integer.parseInt(commandParts[1]); //ред, от който трябва да взема първия елемент
29 | int col1 = Integer.parseInt(commandParts[2]); //колона, от коята трябва да взема първия елемент
30 |
31 | //място, от което взимам втория елемент
32 | int row2 = Integer.parseInt(commandParts[3]); //ред, от който трябва да взема втория елемент
33 | int col2 = Integer.parseInt(commandParts[4]); //колона, от коята трябва да взема втория елемент
34 |
35 | String firstElement = matrix[row1][col1];
36 | String secondElement = matrix[row2][col2];
37 |
38 | matrix[row1][col1] = secondElement;
39 | matrix[row2][col2] = firstElement;
40 |
41 | printMatrix(matrix);
42 |
43 | }
44 | //невалидна
45 | else {
46 | System.out.println("Invalid input!");
47 | }
48 | command = scanner.nextLine();
49 | }
50 | }
51 |
52 | private static void fillMatrix(String[][] matrix, Scanner scanner) {
53 | for (int row = 0; row < matrix.length ; row++) {
54 | //scanner.nextLine() -> "1 2 3"
55 | //scanner.nextLine().split(" ") -> ["1", "2", "3"]
56 | matrix[row] = scanner.nextLine().split("\\s+");
57 | }
58 | }
59 |
60 | private static boolean validateCommand (String command, int rows, int cols) {
61 | //true -> ако командата е валидна
62 | //false -> ако командата не е валидна
63 | //command = "swap row1 col1 row2 col2"
64 | String [] commandParts = command.split("\\s+");
65 | //"swap 1 3 4 6".split(" ") -> ["swap", "1", "3", "4", "6"]
66 |
67 | //1. брой на параметрите / части на командата -> 5
68 | if (commandParts.length != 5) {
69 | return false;
70 | }
71 |
72 | //2. започва swap
73 | if (!commandParts[0].equals("swap")) {
74 | return false;
75 | }
76 |
77 | //3. дали редовете и колоните дадени в командата ги има в матрицата
78 | int row1 = Integer.parseInt(commandParts[1]); // >= 0 && < бр. редове
79 | int col1 = Integer.parseInt(commandParts[2]); // >= 0 && < бр. колони
80 | int row2 = Integer.parseInt(commandParts[3]); // >= 0 && < бр. редове
81 | int col2 = Integer.parseInt(commandParts[4]); // >= 0 && < бр. колони
82 |
83 | if (row1 < 0 || row1 >= rows || row2 < 0 || row2 >= rows || col1 < 0 || col1 >= cols || col2 < 0 || col2 >= cols) {
84 | return false;
85 | }
86 |
87 | //командата е валидна по всички параметри
88 | return true;
89 | }
90 |
91 | private static void printMatrix(String[][] matrix) {
92 | for (int row = 0; row < matrix.length; row++) {
93 | for (int col = 0; col < matrix[0].length; col++) {
94 | System.out.print(matrix[row][col] + " ");
95 | }
96 | System.out.println(); //свали курсора на следващия ред
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/MaximalSum_04.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class MaximalSum_04 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | int [] numbers = Arrays.stream(scanner.nextLine().split("\\s+")).mapToInt(Integer :: parseInt).toArray();
10 | int rows = numbers[0];
11 | int cols = numbers [1];
12 |
13 | int [][] matrix = new int [rows][rows];
14 |
15 | fillMatrixType1(scanner, matrix, rows, cols);
16 |
17 | int maxSum = Integer.MIN_VALUE;
18 | int startRow = 0;
19 | int startCol = 0;
20 | for (int row = 0; row < rows - 2 ; row++) {
21 | for (int col = 0; col < cols - 2 ; col++) {
22 | int sum = matrix[row][col] + matrix[row][col + 1] + matrix[row][col + 2]
23 | + matrix[row + 1][col] + matrix[row + 1][col + 1] + matrix[row + 1][col + 2]
24 | + matrix[row + 2][col] + matrix[row + 2][col + 1] + matrix[row + 2][col + 2];
25 |
26 | if(sum > maxSum) {
27 | maxSum = sum;
28 | startRow = row;
29 | startCol = col;
30 | }
31 | }
32 |
33 | }
34 |
35 | System.out.println("Sum = " + maxSum);
36 | for (int row = startRow; row <= startRow + 2; row++) {
37 | for (int col = startCol; col <= startCol + 2 ; col++) {
38 | System.out.print(matrix[row][col] + " ");
39 | }
40 | System.out.println();
41 | }
42 |
43 |
44 | }
45 |
46 | private static void printMatrix(String[][] matrix) {
47 | for (int row = 0; row < matrix.length ; row++) {
48 | for (int col = 0; col < matrix[row].length; col++) {
49 | System.out.print(matrix[row][col] + " ");
50 | }
51 | System.out.println();
52 | }
53 | }
54 |
55 | public static void fillMatrixType1(Scanner scanner, int[][] matrix, int rows, int cols) {
56 | for (int row = 0; row < rows; row++) {
57 | matrix[row] = Arrays.stream(scanner.nextLine().split("\\s+"))
58 | .mapToInt(Integer::parseInt).toArray();
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/ParkingSystem_09.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class ParkingSystem_09 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | int[] arrDim = Arrays.stream(scanner.nextLine().split("\\s+")).mapToInt(Integer::parseInt).toArray();
10 | boolean[][] isOccupied = new boolean[arrDim[0]][arrDim[1]];
11 | for (int i = 0; i < isOccupied.length; i++) {
12 | isOccupied[i][0] = true;
13 | }
14 |
15 | String input;
16 | while (!"stop".equals(input = scanner.nextLine())) {
17 | String[] tokens = input.split("\\s+");
18 | int entryRow = Integer.parseInt(tokens[0]);
19 | int desiredRow = Integer.parseInt(tokens[1]);
20 | int desiredCol = Integer.parseInt(tokens[2]);
21 | boolean hasFoundPlace = false;
22 | int traveledDistance = 1;
23 | traveledDistance += Math.abs(desiredRow - entryRow);
24 |
25 | if (!isOccupied[desiredRow][desiredCol]) {
26 | traveledDistance += desiredCol;
27 | isOccupied[desiredRow][desiredCol] = true;
28 | hasFoundPlace = true;
29 | } else {
30 | for (int offset = 1; offset < isOccupied[desiredRow].length && !hasFoundPlace; offset++) {
31 | if (desiredCol - offset > 0 && !isOccupied[desiredRow][desiredCol - offset]){
32 | isOccupied[desiredRow][desiredCol - offset] = true;
33 | hasFoundPlace = true;
34 | traveledDistance += desiredCol - offset;
35 | }
36 |
37 | if (!hasFoundPlace && desiredCol + offset < isOccupied[desiredRow].length
38 | && !isOccupied[desiredRow][desiredCol + offset]){
39 | isOccupied[desiredRow][desiredCol + offset] = true;
40 | hasFoundPlace = true;
41 | traveledDistance += offset + desiredCol;
42 | }
43 | }
44 | }
45 | if (hasFoundPlace){
46 | System.out.println(traveledDistance);
47 | } else {
48 | System.out.printf("Row %d full%n", desiredRow);
49 | }
50 | }
51 | }
52 | }
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/RadioactiveMutantVampireBunnies_10.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class RadioactiveMutantVampireBunnies_10 {
7 | public static void main(String[] args) {
8 | Scanner scan = new Scanner(System.in);
9 |
10 | int[] dimensions = Arrays.stream(scan.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
11 | int rows = dimensions[0];
12 | int cols = dimensions[1];
13 |
14 | String[][] matrix = new String[rows][cols];
15 |
16 | int playerRow = 0;
17 | int playerCol = 0;
18 |
19 | for (int row = 0; row < rows; row++) {
20 | String[] data = scan.nextLine().split("");
21 | for (int col = 0; col < cols; col++) {
22 | if (data[col].equals("P")) {
23 | playerRow = row;
24 | playerCol = col;
25 | matrix[row][col] = data[col];
26 | } else {
27 | matrix[row][col] = data[col];
28 | }
29 | }
30 | }
31 | String[] commands = scan.nextLine().split("");
32 | boolean isDead = false;
33 | boolean hasWon = false;
34 |
35 |
36 | for (int i = 0; i < commands.length; i++) {
37 | String cmd = commands[i];
38 |
39 | // move player
40 | if (cmd.equals("U")) {
41 | if (playerRow - 1 < 0) { // wins
42 | hasWon = true;
43 | matrix[playerRow][playerCol] = ".";
44 | } else {
45 | if (matrix[playerRow - 1][playerCol].equals(".")) { //moves
46 | matrix[playerRow - 1][playerCol] = "P";
47 | matrix[playerRow][playerCol] = ".";
48 | playerRow--;
49 | } else { // dies
50 | isDead = true;
51 | matrix[playerRow][playerCol] = ".";
52 | playerRow--;
53 | }
54 | }
55 | } else if (cmd.equals("D")) {
56 | if (playerRow + 1 == rows) { //wins
57 | hasWon = true;
58 | matrix[playerRow][playerCol] = ".";
59 | } else {
60 | if (matrix[playerRow + 1][playerCol].equals(".")) { //moves
61 | matrix[playerRow + 1][playerCol] = "P";
62 | matrix[playerRow][playerCol] = ".";
63 | playerRow++;
64 | } else { // dies
65 | isDead = true;
66 | matrix[playerRow][playerCol] = ".";
67 | playerRow++;
68 | }
69 | }
70 |
71 | } else if (cmd.equals("L")) {
72 | if (playerCol - 1 < 0) { //wins
73 | hasWon = true;
74 | matrix[playerRow][playerCol] = ".";
75 | } else {
76 | if (matrix[playerRow][playerCol - 1].equals(".")) { //moves
77 | matrix[playerRow][playerCol - 1] = "P";
78 | matrix[playerRow][playerCol] = ".";
79 | playerCol--;
80 | } else { // dies
81 | isDead = true;
82 | matrix[playerRow][playerCol] = ".";
83 | playerCol--;
84 | }
85 | }
86 |
87 | } else if (cmd.equals("R")) {
88 | if (playerCol + 1 == cols) { //wins
89 | hasWon = true;
90 | matrix[playerRow][playerCol] = ".";
91 | } else {
92 | if (matrix[playerRow][playerCol + 1].equals(".")) { //moves
93 | matrix[playerRow][playerCol + 1] = "P";
94 | matrix[playerRow][playerCol] = ".";
95 | playerCol++;
96 | } else { // dies
97 | isDead = true;
98 | matrix[playerRow][playerCol] = ".";
99 | playerCol++;
100 | }
101 | }
102 | }
103 |
104 |
105 | //bunnies multiply
106 | for (int row = 0; row < matrix.length; row++) {
107 | for (int col = 0; col < matrix[row].length; col++) {
108 | if(matrix[row][col].equals("B")){
109 | //UP
110 | if(row-1 >= 0){
111 | if (matrix[row-1][col].equals("P")){
112 | isDead = true;
113 | matrix[row-1][col] = "Bn";
114 | } else if (matrix[row-1][col].equals(".")){
115 | matrix[row-1][col] = "Bn";
116 | }
117 | }
118 | //DOWN
119 | if (row+1 < matrix.length){
120 | if(matrix[row+1][col].equals("P")){
121 | isDead = true;
122 | matrix[row+1][col] = "Bn";
123 | } else if (matrix[row+1][col].equals(".")){
124 | matrix[row+1][col] = "Bn";
125 | }
126 | }
127 | //LEFT
128 | if (col -1 >= 0){
129 | if (matrix[row][col-1].equals("P")){
130 | isDead = true;
131 | matrix[row][col-1] = "Bn";
132 | } else if (matrix[row][col-1].equals(".")) {
133 | matrix[row][col-1] = "Bn";
134 | }
135 | }
136 | //RIGHT
137 | if (col +1 < matrix[row].length){
138 | if(matrix[row][col+1].equals("P")){
139 | isDead = true;
140 | matrix[row][col+1] = "Bn";
141 | } else if (matrix[row][col+1].equals(".")) {
142 | matrix[row][col+1] = "Bn";
143 | }
144 | }
145 | }
146 | }
147 | }
148 |
149 | matrix = growTheBunnies(matrix);
150 |
151 | if(isDead){
152 | printMatrix(matrix);
153 | System.out.printf("dead: %d %d", playerRow, playerCol);
154 | break;
155 | } else if (hasWon){
156 | printMatrix(matrix);
157 | System.out.printf("won: %d %d",playerRow,playerCol);
158 | break;
159 | }
160 | }
161 | }
162 |
163 | private static String[][] growTheBunnies(String[][] matrix) {
164 |
165 | for (int r = 0; r < matrix.length; r++) {
166 | for (int c = 0; c < matrix[r].length; c++) {
167 | if(matrix[r][c].equals("Bn")){
168 | matrix[r][c] = "B";
169 | }
170 | }
171 | }
172 | return matrix;
173 | }
174 |
175 | private static void printMatrix(String[][] matrix) {
176 | for (int i = 0; i < matrix.length; i++) {
177 | for (int j = 0; j < matrix[i].length; j++) {
178 | System.out.print(matrix[i][j]);
179 | }
180 | System.out.println();
181 | }
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/ReverseMatrixDiagonals_11.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.io.IOException;
4 | import java.util.Arrays;
5 | import java.util.Scanner;
6 |
7 | public class ReverseMatrixDiagonals_11 {
8 | public static void main(String[] args) throws IOException {
9 | Scanner scanner = new Scanner(System.in);
10 |
11 | int[] dimensions = Arrays.stream(scanner.nextLine().split("\\s+"))
12 | .mapToInt(Integer::parseInt)
13 | .toArray();
14 |
15 | int rows = dimensions[0], cols = dimensions[1];
16 |
17 | int[][] matrix = new int[rows][cols];
18 |
19 | for (int i = 0; i < rows; i++) {
20 | matrix[i] = Arrays.stream(scanner.nextLine().split("\\s+"))
21 | .mapToInt(Integer::parseInt)
22 | .toArray();
23 | }
24 | int row = rows - 1;
25 | int col = cols - 1;
26 |
27 | while (row != -1){
28 | int r = row;
29 | int c = col;
30 | while (c < cols && r >= 0){
31 | System.out.print(matrix[r--][c++] + " ");
32 | }
33 | System.out.println();
34 | col--;
35 | if(col == -1){
36 | col = 0;
37 | row--;
38 | }
39 | }
40 | }
41 |
42 | private static boolean isInbounds(int row, int col, int [][] matrix) {
43 | return row < 0 || col < 0 || row > matrix.length - 1 || col > matrix[0].length - 1;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/StringMatrixRotation_06.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.Scanner;
6 |
7 | public class StringMatrixRotation_06 {
8 | public static void main(String[] args) {
9 |
10 | Scanner scanner = new Scanner(System.in);
11 | String rotation = scanner.nextLine();
12 | int angleRotation = Integer.parseInt(rotation.split("[()]+")[1]) % 360;
13 |
14 |
15 | ArrayList linesForMatrix = new ArrayList<>();
16 | int maxLength = 0;
17 | while (true) {
18 | String line = scanner.nextLine();
19 | if(line.equals("END")){
20 | break;
21 | }
22 | linesForMatrix.add(line);
23 | if(line.length() > maxLength){
24 | maxLength = line.length();
25 | }
26 | }
27 |
28 | int rows = linesForMatrix.size();
29 | int cols = maxLength;
30 |
31 | char [][] matrix = new char[rows][cols];
32 |
33 | for (int row = 0; row < rows ; row++) {
34 | for (int col = 0; col < cols ; col++) {
35 | if (col < linesForMatrix.get(row).length()) {
36 | matrix[row][col] = linesForMatrix.get(row).charAt(col);
37 | } else {
38 | matrix[row][col] = ' ';
39 | }
40 | }
41 | }
42 |
43 | rotate(angleRotation, rows, cols, matrix);
44 |
45 |
46 | }
47 |
48 | private static void rotate(int angleRotation, int rows, int cols, char[][] matrix) {
49 | if (angleRotation == 90) {
50 | for (int col = 0; col < cols ; col++) {
51 | for (int row = rows - 1; row >= 0 ; row--) {
52 | System.out.print(matrix[row][col]);
53 | }
54 | System.out.println();
55 | }
56 |
57 | } else if (angleRotation == 180) {
58 | for (int row = rows - 1; row >= 0 ; row--) {
59 | for (int col = cols - 1; col >= 0 ; col--) {
60 | System.out.print(matrix[row][col]);
61 | }
62 | System.out.println();
63 | }
64 | } else if (angleRotation == 270) {
65 | for (int col = cols - 1; col >= 0 ; col--) {
66 | for (int row = 0; row < rows ; row++) {
67 | System.out.print(matrix[row][col]);
68 |
69 | }
70 | System.out.println();
71 | }
72 | } else {
73 | for (int row = 0; row < rows ; row++) {
74 | for (int col = 0; col < cols ; col++) {
75 | System.out.print(matrix[row][col]);
76 | }
77 | System.out.println();
78 | }
79 | }
80 | }
81 |
82 | private static void printMatrix(char[][] matrix) {
83 | for (int row = 0; row < matrix.length ; row++) {
84 | for (int col = 0; col < matrix[row].length; col++) {
85 | System.out.print(matrix[row][col] + " ");
86 | }
87 | System.out.println();
88 | }
89 | }
90 |
91 | public static void fillMatrixType1(Scanner scanner, int[][] matrix, int rows, int cols) {
92 | for (int row = 0; row < rows; row++) {
93 | matrix[row] = Arrays.stream(scanner.nextLine().split("\\s+"))
94 | .mapToInt(Integer::parseInt).toArray();
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Solutions/TheHeiganDance_08.java:
--------------------------------------------------------------------------------
1 | package MultidimensionalArrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class TheHeiganDance_08 {
6 | public static void main(String[] args) {
7 | Scanner scan = new Scanner(System.in);
8 |
9 | int playerRow = 7;
10 | int playerCol = 7;
11 |
12 | int playerHP = 18500;
13 | double heiganHP = 3000000;
14 | double playerDamage = Double.parseDouble(scan.nextLine());
15 | String lastSpell = "";
16 | while (true) {
17 | if (playerHP >= 0) {
18 | heiganHP -= playerDamage;
19 | }
20 | if (lastSpell.equals("Cloud")) {
21 | playerHP -= 3500;
22 | }
23 | if (heiganHP <= 0 || playerHP <= 0) {
24 | break;
25 | }
26 | String[] input = scan.nextLine().split(" ");
27 | String currentSpell = input[0];
28 | int targetRow = Integer.parseInt(input[1]);
29 | int targetCol = Integer.parseInt(input[2]);
30 | if (isInDamageArea(targetRow, targetCol, playerRow, playerCol)) {
31 | if (!isInDamageArea(targetRow, targetCol, playerRow - 1, playerCol) && !isWall(playerRow - 1)) {
32 | playerRow--;
33 | lastSpell = "";
34 | } else if (!isInDamageArea(targetRow, targetCol, playerRow, playerCol + 1) && !isWall(playerCol + 1)) {
35 | playerCol++;
36 | lastSpell = "";
37 | } else if (!isInDamageArea(targetRow, targetCol, playerRow + 1, playerCol) && !isWall(playerRow + 1)) {
38 | playerRow++;
39 | lastSpell = "";
40 | } else if (!isInDamageArea(targetRow, targetCol, playerRow, playerCol - 1) && !isWall(playerCol - 1)) {
41 | playerCol--;
42 | lastSpell = "";
43 | } else {
44 | if (currentSpell.equals("Cloud")) {
45 | playerHP -= 3500;
46 | lastSpell = "Cloud";
47 | } else if (currentSpell.equals("Eruption")) {
48 | playerHP -= 6000;
49 | lastSpell = "Eruption";
50 | }
51 | }
52 | }
53 | }
54 | lastSpell = lastSpell.equals("Cloud") ? "Plague Cloud" : "Eruption";
55 | String heiganState = heiganHP <= 0 ? "Heigan: Defeated!" : String.format("Heigan: %.2f", heiganHP);
56 | String playerState = playerHP <= 0 ? String.format("Player: Killed by %s", lastSpell) :
57 | String.format("Player: %d", playerHP);
58 | String playerEndCoordinates = String.format("Final position: %d, %d", playerRow, playerCol);
59 |
60 | System.out.println(heiganState);
61 | System.out.println(playerState);
62 | System.out.println(playerEndCoordinates);
63 | }
64 |
65 | private static boolean isWall(int moveCell) {
66 | return moveCell < 0 || moveCell >= 15;
67 | }
68 |
69 | private static boolean isInDamageArea(int targetRow, int targetCol, int moveRow, int moveCol) {
70 | return ((targetRow - 1 <= moveRow && moveRow <= targetRow + 1)
71 | && (targetCol - 1 <= moveCol && moveCol <= targetCol + 1));
72 | }
73 | }
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Theory/MultidimensionalArrays_Theory.txt:
--------------------------------------------------------------------------------
1 | Матрици - теория
2 |
3 | 1. съхраняваме данни в матрица
4 | private static void fillMatrix(int[][] matrix, Scanner scanner) {
5 | for (int row = 0; row < matrix.length ; row++) {
6 | for (int col = 0; col < matrix.length; col++) {
7 | matrix[row][col] = scanner.nextInt();
8 | }
9 | }
10 | }
11 |
12 | private static void fillMatrix(double[][] matrix, Scanner scanner) {
13 | for (int row = 0; row < matrix.length ; row++) {
14 | for (int col = 0; col < matrix.length; col++) {
15 | matrix[row][col] = scanner.nextDouble();
16 | }
17 | }
18 | }
19 |
20 | private static void fillMatrix(String[][] matrix, Scanner scanner) {
21 | for (int row = 0; row < matrix.length ; row++) {
22 | //scanner.nextLine() -> "1 2 3"
23 | //scanner.nextLine().split(" ") -> ["1", "2", "3"]
24 | matrix[row] = scanner.nextLine().split("\\s+");
25 | }
26 | }
27 | 2. извеждане на данни от матрица
28 | private static void printMatrix(int[][] matrix) {
29 | for (int row = 0; row < matrix.length; row++) {
30 | for (int col = 0; col < matrix.length; col++) {
31 | System.out.print(matrix[row][col] + " ");
32 | }
33 | System.out.println(); //свали курсора на следващия ред
34 | }
35 | }
36 |
37 | 3. диагонали в квадратна матрица
38 | - главен диагонал -> индекс на ред = индекс на колона
39 | - второстепенния диагонал -> индекс на колона = размер на матрица - индекс на ред - 1
40 |
41 | 4. валидираме индекси
42 |
43 | при правоъгълна матрица:
44 | - брой редове -> matrix.lenght
45 | - брой на колони -> matrix[0].lenght
46 |
47 | при квадратна матрица:
48 | - брой редове -> matrix.lenght
49 | - брой на колони -> matrix.lenght
50 |
51 | - валиден ред: ред >= 0 и ред < брой на редове
52 | - невалиден ред: ред < 0 или ред >= брой на редове
53 |
54 | - валидна колона: колона >= 0 и колона < брой на колони
55 | - валидна колона: колона < 0 или колона >= брой на колона
56 |
57 | 5. движения в матрица
58 | - ляво с 1 позиция -> колона - 1
59 | - дясно с 1 позиция -> колона + 1
60 | - надолу с 1 позиция -> ред + 1
61 | - нагоре с 1 позиция -> ред - 1
--------------------------------------------------------------------------------
/Multidimensional Arrays - Exercise/Videos/MultidimensionalArrays_Videos.txt:
--------------------------------------------------------------------------------
1 | Multidimensional Arrays - Exercise - Videos
2 | 04. Maximal Sum
3 | видео: https://youtu.be/d7xzSoeQnUQ?t=6549
4 | решение: https://pastebin.com/1jCzr9XG
5 |
6 | 02. Formula One
7 | Линк към задачата: https://judge.softuni.org/Contests/Practice/Index/3018#1
8 | Решение: https://pastebin.com/RDwSX6fC
9 | Видео: https://youtu.be/ToZNX6FLWwg?t=11605
10 |
11 | 07. Crossfire (с лист от листове) -> https://pastebin.com/dAGyPkt8
12 | видео: https://youtu.be/D2Zfs38iDZE?t=8803
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Demo/Demo_Sort.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.Collections;
4 | import java.util.HashMap;
5 | import java.util.LinkedHashMap;
6 | import java.util.Map;
7 |
8 |
9 | import static java.util.Map.Entry.comparingByKey;
10 | import static java.util.Map.Entry.comparingByValue;
11 | import static java.util.stream.Collectors.toMap;
12 |
13 | public class Demo_Sort {
14 | public static void main(String[] args) {
15 | //човек -> сума за плащане
16 | Map people = new HashMap<>();
17 |
18 | //1. sorted by keys in ascending order (нарастващ) -> а към z
19 | people.entrySet().stream().sorted(comparingByKey());
20 |
21 | //2. sorted by keys in descending order (намаляващ) -> z към а
22 | people.entrySet().stream().sorted(Collections.reverseOrder(comparingByKey()));
23 |
24 | //3. sorted by value in ascending order -> от най-малка към най-голяма сума
25 | people.entrySet().stream().sorted(comparingByValue());
26 |
27 | //3. sorted by value in descending order -> от най-голяма към най-малка сума
28 | people.entrySet().stream().sorted(Collections.reverseOrder(comparingByValue()));
29 |
30 | //съхраняваме в нов мап вече сортирания
31 | Map sortedMap = people.entrySet().stream()
32 | .sorted(comparingByKey())
33 | .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
34 |
35 | //съхраняваме в същия мап вече сортирания
36 | people = people.entrySet().stream()
37 | .sorted(comparingByKey())
38 | .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Demo/Demo_Sort_By_List_Count.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.HashMap;
4 | import java.util.List;
5 | import java.util.Map;
6 | import java.util.Scanner;
7 |
8 | public class Demo_Sort_By_List_Count {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 | //ученик -> брой на оценки
12 | Map> studentsGrade = new HashMap<>();
13 |
14 | //Първи случай -> descending order на брой оценки
15 | //първи запис: ученик с най-голям брой оценки
16 | //Пешо: {5.4, 3.5, 3.6}
17 | //Иван: {5.5, 4.8, 3.4, 3.5, 2.4}
18 | //Петя: {4.6, 3.4}
19 | //след сортировка: Иван -> Пешо -> Петя
20 | studentsGrade.entrySet().stream()
21 | .sorted((s1, s2) -> s2.getValue().size() - s1.getValue().size());
22 |
23 |
24 | // Втори случай -> ascending order спрямо бройна оценките
25 | // първи запис: ученик с най-малък брой оценки
26 | // Пешо: {5.4, 3.5, 3.6}
27 | // Иван: {5.5, 4.8, 3.4, 3.5, 2.4}
28 | // Петя: {4.6, 3.4}
29 | // след сортировка: Петя -> Пешо -> Иван
30 | studentsGrade.entrySet().stream()
31 | .sorted((s1, s2) -> s1.getValue().size() - s2.getValue().size());
32 |
33 | //sorted -> размества записи на базата на цяло число, което се получава при сравнение
34 | //sorted -> > 0 -> разменя записите
35 | //sorted -> <= 0 -> не разменя записите
36 |
37 | //СТЪПКИ НА СОРТИРОВКАТА
38 | // Пешо: {5.4, 3.5, 3.6}
39 | // Иван: {5.5, 4.8, 3.4, 3.5, 2.4}
40 | // Петя: {4.6, 3.4}
41 |
42 | //1. s1 = Пешо(key): {5.4, 3.5, 3.6}(value) s2 = Иван(key): {5.5, 4.8, 3.4, 3.5, 2.4}(value)
43 | //Пешо -> Иван -> Петя
44 |
45 | //2. s1 = Иван(key): {5.5, 4.8, 3.4, 3.5, 2.4}(value) s2 = Петя(key): {4.6, 3.4}(value)
46 | //Пешо -> Петя -> Иван
47 |
48 | //3. s1 = Пешо(key): {5.4, 3.5, 3.6}(value) s2 = Петя(key): {4.6, 3.4}(value)
49 | //Петя -> Пешо -> Иван
50 |
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/CountSymbols_04.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.*;
4 |
5 | public class CountSymbols_04 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | String text = scanner.nextLine();
9 | TreeMap symbolsCount = new TreeMap<>();
10 | //символ -> бр. срещанията
11 |
12 | for (int index = 0; index < text.length(); index++) {
13 | char currentSymbol = text.charAt(index);
14 | //символът вече да съм го срещала
15 | if (symbolsCount.containsKey(currentSymbol)) {
16 | int currentCount = symbolsCount.get(currentSymbol);
17 | symbolsCount.put(currentSymbol, currentCount + 1);
18 | }//символът да не съм го срещала
19 | else {
20 | symbolsCount.put(currentSymbol, 1);
21 | }
22 | }
23 | //символ: бр.срещания time/s
24 | symbolsCount.entrySet().forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue() + " time/s"));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/DragonArmy_13.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.text.DecimalFormat;
4 | import java.util.*;
5 | import java.util.stream.Collector;
6 | import java.util.stream.Collectors;
7 |
8 | public class DragonArmy_13 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 |
12 | int n = Integer.parseInt(scanner.nextLine());
13 |
14 | LinkedHashMap>> dragons = new LinkedHashMap<>();
15 |
16 | while (n-- > 0){
17 | String[] tokens = scanner.nextLine().split("\\s+");
18 |
19 | //{type} {name} {damage} {health} {armor}
20 | String type = tokens[0];
21 | String name = tokens[1];
22 | double damage = tokens[2].equals("null") ? 45 : Integer.parseInt(tokens[2]);
23 | double health = tokens[3].equals("null") ? 250 : Integer.parseInt(tokens[3]);
24 | double armor = tokens[4].equals("null") ? 10 : Integer.parseInt(tokens[4]);
25 |
26 | if(!dragons.containsKey(type)){
27 | dragons.put(type, new TreeMap<>(){{
28 | put(name, new ArrayList<>(){{
29 | add(damage);
30 | add(health);
31 | add(armor);
32 | }});
33 | }});
34 | }else{
35 | if(!dragons.get(type).containsKey(name)){
36 | dragons.get(type).put(name, new ArrayList<>(){{
37 | add(damage);
38 | add(health);
39 | add(armor);
40 | }});
41 | }else {
42 | dragons.get(type).get(name).add(0, damage);
43 | dragons.get(type).get(name).add(1, health);
44 | dragons.get(type).get(name).add(2, armor);
45 | }
46 | }
47 | }
48 |
49 | for (String type : dragons.keySet()) {
50 | double damageSum = 0;
51 | double healthSum = 0;
52 | double armorSum = 0;
53 |
54 | StringBuilder builder = new StringBuilder();
55 |
56 | for (String name : dragons.get(type).keySet()) {
57 | double tempDamage = dragons.get(type).get(name).get(0);
58 | double tempHealth = dragons.get(type).get(name).get(1);
59 | double tempArmor = dragons.get(type).get(name).get(2);
60 |
61 | builder.append(String.format("-%s -> damage: %.0f, health: %.0f, armor: %.0f%n", name, tempDamage, tempHealth, tempArmor));
62 |
63 | damageSum += tempDamage;
64 | healthSum += tempHealth;
65 | armorSum += tempArmor;
66 | }
67 | damageSum /= dragons.get(type).keySet().size();
68 | healthSum /= dragons.get(type).keySet().size();
69 | armorSum /= dragons.get(type).keySet().size();
70 |
71 | System.out.println(String.format("%s::(%.2f/%.2f/%.2f)", type, damageSum, healthSum, armorSum));
72 | System.out.print(builder.toString());
73 |
74 |
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/FixEmails_06.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.Map;
5 | import java.util.Scanner;
6 |
7 | public class FixEmails_06 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | String name = scanner.nextLine(); //име на човек
11 |
12 | //име на човек -> email на човек
13 | Map emailsData = new LinkedHashMap<>();
14 |
15 | //1. съхраняваме данните за хората и техните имейли
16 | while (!name.equals("stop")) {
17 | String email = scanner.nextLine(); //email на човек
18 | emailsData.put(name, email);
19 | name = scanner.nextLine();
20 | }
21 |
22 | //2. премахвам всички записи, на които value (email) завършва на uk, us, com
23 | //removeIf -> премахва всички записи, които отговарят на условието
24 | emailsData.entrySet().removeIf(entry ->
25 | entry.getValue().endsWith("uk")
26 | || entry.getValue().endsWith("us")
27 | || entry.getValue().endsWith("com"));
28 | //запис: име(key) -> имейл(value)
29 | emailsData.entrySet().forEach(entry -> System.out.println(entry.getKey() + " -> " + entry.getValue()));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/HandsOfCards_07.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.*;
4 |
5 | public class HandsOfCards_07 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | String input = scanner.nextLine();
9 |
10 | //име на играча -> списък с карти (картите не трябва да се повтарям)
11 | Map> players = new LinkedHashMap<>();
12 |
13 | while (!input.equals("JOKER")) {
14 | //input = "{personName}: {PT, PT, PT,… PT}".split(": ") -> ["{playerName}", "{cards}"]
15 | String playerName = input.split(":\\s+")[0]; //"Peter"
16 | String cards = input.split(":\\s+")[1]; //"2C, 4H, 9H, AS, QS"
17 | String [] cardsArr = cards.split(", "); //["2C", "4H", "9H", "AS", QS]
18 | //1. съхраняваме картите в set
19 | Set cardsSet = new HashSet<>(); //картите на играча
20 | cardsSet.addAll(Arrays.asList(cardsArr));
21 |
22 | //2. добавяне в мап
23 | //ако не сме го записали
24 | if (!players.containsKey(playerName)) {
25 | players.put(playerName, cardsSet);
26 | }
27 | //ако сме го записали
28 | else {
29 | //взимаме до момента картите му и към тях добавяме новите
30 | Set currentCards = players.get(playerName);
31 | //към текущите карти добавям новите изтеглени
32 | currentCards.addAll(cardsSet);
33 | players.put(playerName, currentCards);
34 | }
35 | input = scanner.nextLine();
36 | }
37 |
38 | //запис: име на играч -> списък с картите
39 | players.entrySet().forEach(entry -> {
40 | String name = entry.getKey();
41 | Set cards = entry.getValue();
42 | int points = getCardsPoints(cards);
43 | System.out.printf("%s: %d%n", name, points);
44 | });
45 | }
46 |
47 | private static int getCardsPoints(Set cards) {
48 | //всяка един символ -> стойност
49 | Map symbolsValues = getSymbolsValues();
50 | int sumPoints = 0;
51 | //списък с карти: "2C", "4H", "9H", "AS", "QS"
52 | //всяка една карта -> намираме точките за картата -> доабвяме точките на картата към сумата от всички точки
53 | for (String card : cards) {
54 | //card = "2C" -> "[сила][тип]"
55 | //сила: 2 (2), 3(3), 4(4), 5(5), 6 (6), 7 (7), 8 (8), 9(9), 10(10), J(11), D(12), K(13), A(14)
56 | //тип: S(4), H(3), D(2), C(1)
57 | //точки = сила * тип
58 |
59 | int points = 0;
60 | if (card.startsWith("10")) {
61 | //картата е "10C"
62 | //сила = 10
63 | char type = card.charAt(2);
64 | points = 10 * symbolsValues.get(type);
65 | } else {
66 | //"4H"
67 | char power = card.charAt(0); //4
68 | char type = card.charAt(1); //H
69 | points = symbolsValues.get(power) * symbolsValues.get(type);
70 | }
71 |
72 | sumPoints += points;
73 | }
74 | //знаем сумата от точките за всички карти
75 | return sumPoints;
76 | }
77 |
78 | private static Map getSymbolsValues() {
79 | Map characterValues = new HashMap<>();
80 | characterValues.put('2', 2);
81 | characterValues.put('3', 3);
82 | characterValues.put('4', 4);
83 | characterValues.put('5', 5);
84 | characterValues.put('6', 6);
85 | characterValues.put('7', 7);
86 | characterValues.put('8', 8);
87 | characterValues.put('9', 9);
88 | characterValues.put('J', 11);
89 | characterValues.put('Q', 12);
90 | characterValues.put('K', 13);
91 | characterValues.put('A', 14);
92 | characterValues.put('S', 4);
93 | characterValues.put('H', 3);
94 | characterValues.put('D', 2);
95 | characterValues.put('C', 1);
96 | return characterValues;
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/LegendaryFarming_11.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.Comparator;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 | import java.util.Scanner;
7 |
8 | public class LegendaryFarming_11 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 | HashMap legendaryMat = new HashMap<>();
12 | HashMap junkMat = new HashMap<>();
13 |
14 | legendaryMat.put("shards", 0);
15 | legendaryMat.put("fragments", 0);
16 | legendaryMat.put("motes", 0);
17 |
18 | boolean isCollected = false;
19 | while (!isCollected) {
20 | String[] tokens = scanner.nextLine().toLowerCase().split("\\s+");
21 | for (int i = 0; i < tokens.length && !isCollected; i += 2) {
22 | String mat = tokens[i + 1];
23 | int amount = Integer.parseInt(tokens[i]);
24 |
25 | if ("shards".equals(mat) || "fragments".equals(mat) || "motes".equals(mat)) {
26 | amount += legendaryMat.get(mat);
27 | if (amount >= 250) {
28 | amount -= 250;
29 | isCollected = true;
30 | switch (mat) {
31 | case "shards":
32 | System.out.println("Shadowmourne obtained!");
33 | break;
34 | case "fragments":
35 | System.out.println("Valanyr obtained!");
36 | break;
37 | case "motes":
38 | System.out.println("Dragonwrath obtained!");
39 | break;
40 | }
41 | }
42 | legendaryMat.put(mat, amount);
43 | } else {
44 | if (junkMat.containsKey(mat)) {
45 | junkMat.put(mat, junkMat.get(mat) + amount);
46 | } else {
47 | junkMat.put(mat, amount);
48 | }
49 | }
50 | }
51 | }
52 |
53 | legendaryMat.entrySet().stream().sorted((e1, e2) -> {
54 | if (e2.getValue().compareTo(e1.getValue()) == 0){
55 | return e1.getKey().compareTo(e2.getKey());
56 | }
57 | return e2.getValue().compareTo(e1.getValue());
58 | })
59 | .forEach(e -> System.out.printf("%s: %d%n", e.getKey(), e.getValue()));
60 |
61 | junkMat.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
62 | .forEach(e -> System.out.printf("%s: %d%n", e.getKey(), e.getValue()));
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/LoggsAggregator_10.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import javax.swing.table.TableRowSorter;
4 | import java.text.DecimalFormat;
5 | import java.util.*;
6 | import java.util.stream.Collector;
7 | import java.util.stream.Collectors;
8 |
9 | public class LoggsAggregator_10 {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 |
13 | int n = Integer.parseInt(scanner.nextLine());
14 |
15 | TreeMap usersWithTime = new TreeMap<>();
16 | TreeMap> addresses = new TreeMap<>();
17 |
18 | while (n-- > 0) {
19 | String[] tokens = scanner.nextLine().split("\\s+");
20 |
21 | String ip = tokens[0];
22 | String name = tokens[1];
23 | int time = Integer.parseInt(tokens[2]);
24 |
25 | if(!usersWithTime.containsKey(name)){
26 | usersWithTime.put(name, time);
27 | addresses.put(name, new TreeSet<>(){{add(ip);}});
28 | }else{
29 | usersWithTime.put(name, usersWithTime.get(name) + time);
30 | addresses.get(name).add(ip);
31 | }
32 | }
33 |
34 | usersWithTime.forEach((key, value) ->{
35 |
36 | System.out.println(String.format("%s: %d %s", key, value, addresses.get(key).toString()));
37 |
38 | });
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/PeriodicTable_03.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.*;
4 |
5 | public class PeriodicTable_03 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | Set uniqueElements = new TreeSet<>();
9 | int n = Integer.parseInt(scanner.nextLine()); //брой на редовете с химични елементи
10 |
11 | for (int row = 1; row <= n; row++) {
12 | String []chemicalElements = scanner.nextLine().split("\\s+"); // "Mo O Ce".split("\\s+") -> ["Mo", "O", "Ce"]
13 | //начин 1:
14 | /*for (String el : chemicalElements) {
15 | uniqueElements.add(el);
16 | }*/
17 |
18 | //начин 2:
19 | //Collections.addAll(Arrays.asList(chemicalElements), uniqueElements);
20 |
21 | //начин 3:
22 | uniqueElements.addAll(Arrays.asList(chemicalElements));
23 | }
24 |
25 | //сет с всички хим. елементи по 1 път
26 | uniqueElements.forEach(el -> System.out.print(el + " "));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/Phonebook_05.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Scanner;
6 |
7 | public class Phonebook_05 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | //име на човек -> телефонен номер
11 | Map phonebook = new HashMap<>();
12 | String data = scanner.nextLine();
13 |
14 | //1. запълване на phonebook
15 | while (!data.equals("search")) {
16 | //data = "John-0888080808".split("-") -> ["John", "0888080808"]
17 | String name = data.split("-")[0];
18 | String phoneNumber = data.split("-")[1];
19 | phonebook.put(name, phoneNumber);
20 | data = scanner.nextLine();
21 | }
22 |
23 | //2. търсене в phonebook
24 | String name = scanner.nextLine();
25 | while (!name.equals("stop")) {
26 | //ако името го има в phonebook (име -> номер): "{name} -> {number}"
27 | if (phonebook.containsKey(name)) {
28 | System.out.println(name + " -> " + phonebook.get(name));
29 | }
30 | //ако името го няма в phonebook: "Contact {name} does not exist."
31 | else {
32 | System.out.printf("Contact %s does not exist.%n", name);
33 | }
34 |
35 | name = scanner.nextLine();
36 | }
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/PopulationCounter_09.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.*;
4 | import java.util.concurrent.atomic.AtomicReference;
5 |
6 | public class PopulationCounter_09 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | String input = scanner.nextLine();
11 |
12 | LinkedHashMap> populationByCountries = new LinkedHashMap<>();
13 |
14 | while (!input.equals("report")){
15 |
16 | String[] tokens = input.split("\\|");
17 |
18 | String city = tokens[0];
19 | String country = tokens[1];
20 | Long population = Long.parseLong(tokens[2]);
21 |
22 | if(!populationByCountries.containsKey(country)){
23 | populationByCountries.put(country, new LinkedHashMap<>(){{
24 | put(city, population);
25 | }});
26 | }else{
27 | populationByCountries.get(country).put(city, population);
28 | }
29 |
30 | input = scanner.nextLine();
31 | }
32 |
33 | populationByCountries.entrySet().stream().sorted((e1, e2) -> {
34 | Long totalPopulationFirst = populationByCountries.get(e1.getKey()).entrySet().stream().mapToLong(Map.Entry::getValue).sum();
35 | Long totalPopulationSecond = populationByCountries.get(e2.getKey()).entrySet().stream().mapToLong(Map.Entry::getValue).sum();
36 | return Long.compare(totalPopulationSecond, totalPopulationFirst);
37 | }).forEach(entry -> {
38 | System.out.print(entry.getKey() + " ");
39 |
40 | StringBuilder builder = new StringBuilder();
41 |
42 | AtomicReference totalPopulation = new AtomicReference<>((long) 0);
43 |
44 | populationByCountries.get(entry.getKey()).entrySet().stream().sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
45 | .forEach(e -> {
46 | builder.append(String.format("=>%s: %d%n", e.getKey(), e.getValue()));
47 | totalPopulation.updateAndGet(v -> v + e.getValue());
48 | });
49 |
50 | System.out.println(String.format("(total population: %s)", totalPopulation.toString()));
51 | System.out.print(builder.toString());
52 | });
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/SerbeanUnleashed_12.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.*;
4 |
5 | public class SerbeanUnleashed_12 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner (System.in);
8 |
9 | LinkedHashMap> concerts = new LinkedHashMap<>();
10 |
11 | String input = scanner.nextLine();
12 |
13 | while(!input.equals("End")) {
14 | //Lepa Brena @Sunny Beach 25 3500
15 | if(!input.contains("@") || input.charAt(input.indexOf("@") - 1) != ' '){
16 | input = scanner.nextLine();
17 | continue;
18 | }
19 |
20 | String singer = input.substring(0, input.indexOf("@") - 1);
21 | int firstIndexOfNumber = 0;
22 | //@Sunny Beach 25
23 | for (int i = input.indexOf("@"); i < input.length(); i++) {
24 | char currentSymbol = input.charAt(i);
25 | if(Character.isDigit(currentSymbol) && input.charAt(i - 1) == ' '){
26 | firstIndexOfNumber = i;
27 | break;
28 | }
29 | }
30 |
31 | if(firstIndexOfNumber == 0) {
32 | input = scanner.nextLine();
33 | continue;
34 | }
35 |
36 | String venue = input.substring(input.indexOf("@") + 1, firstIndexOfNumber - 1);
37 | String numbers = input.substring(firstIndexOfNumber);//"25 3000"
38 | String [] numbersArray = numbers.split("\\s+");
39 | if(numbersArray.length != 2) {
40 | input = scanner.nextLine();
41 | continue;
42 | }
43 | int price = Integer.parseInt(numbersArray[0]);
44 | int capacity = Integer.parseInt(numbersArray[1]);
45 |
46 | //venue -> {singer -> price}
47 |
48 | if (!concerts.containsKey(venue)) {
49 | LinkedHashMap singers = new LinkedHashMap<>();
50 | singers.put(singer, price * capacity);
51 | concerts.put(venue, singers);
52 | } else {
53 | LinkedHashMap currentSingers = concerts.get(venue);
54 | if (currentSingers.containsKey(singer)) {
55 | currentSingers.put(singer, currentSingers.get(singer) + price * capacity);
56 | } else {
57 | currentSingers.put(singer, price * capacity);
58 | }
59 |
60 | concerts.put(venue, currentSingers);
61 | }
62 | input = scanner.nextLine();
63 | }
64 |
65 | for (String venue : concerts.keySet()) {
66 | System.out.println(venue);
67 |
68 | LinkedHashMap singers = concerts.get(venue);
69 | singers.entrySet().stream().sorted((singer1, singer2) -> singer2.getValue().compareTo(singer1.getValue()))
70 | .forEach(singer -> System.out.println(String.format("# %s -> %d", singer.getKey(), singer.getValue())));
71 |
72 | }
73 | }
74 |
75 |
76 |
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/SetsOfElements_02.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.LinkedHashSet;
4 | import java.util.Scanner;
5 | import java.util.Set;
6 |
7 | public class SetsOfElements_02 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | String input = scanner.nextLine(); //"4 3"
11 | int sizeOfFirstSet = Integer.parseInt(input.split("\\s+")[0]); //брой елементи в първия сет
12 | int sizeOfSecondSet = Integer.parseInt(input.split("\\s+")[1]); //брой елементи във втория сет
13 |
14 | Set firstSet = new LinkedHashSet<>(); //първия сет
15 | Set secondSet = new LinkedHashSet<>(); //втори сет
16 |
17 | //1. напълня първия сет
18 | for (int number = 1; number <= sizeOfFirstSet; number++) {
19 | int value = Integer.parseInt(scanner.nextLine());
20 | firstSet.add(value);
21 | }
22 |
23 | //2. напълня втория сет
24 | for (int number = 1; number <= sizeOfSecondSet; number++) {
25 | int value = Integer.parseInt(scanner.nextLine());
26 | secondSet.add(value);
27 | }
28 |
29 | //set 1 => {1, 3, 5, 7}
30 | //set 2 => {3, 4, 5}
31 | //общите елементи за двата сета -> {3, 5}
32 |
33 | //начин 1:
34 | /*Set duplicateElements = new LinkedHashSet<>(); //повтарящите се елементи
35 | for (int number : firstSet) {
36 | if (secondSet.contains(number)) {
37 | duplicateElements.add(number);
38 | //или
39 | System.out.print(number + " ");
40 |
41 | }
42 | }
43 | //duplicateElements -> всички елементи, които ги има и в двата сета
44 | duplicateElements.forEach(el -> System.out.print(el + " "));*/
45 |
46 | //начин 2:
47 | firstSet.retainAll(secondSet);
48 | //retainAll -> премахва всички елементи от firstSet, които ги няма във втория
49 | //set 1 => {3, 5}
50 | //set 2 => {3, 4, 5}
51 | //firstSet -> остават само елементите, които ги има във втория
52 | firstSet.forEach(number -> System.out.print(number + " "));
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/UniqueUsernames_01.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.LinkedHashSet;
4 | import java.util.Scanner;
5 | import java.util.Set;
6 |
7 | public class UniqueUsernames_01 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | int n = Integer.parseInt(scanner.nextLine()); //брой на думите
11 | Set words = new LinkedHashSet<>(); //запазваме реда на добавяне
12 |
13 | for (int countWords = 0; countWords < n; countWords++) {
14 | String word = scanner.nextLine();
15 | words.add(word);
16 | }
17 |
18 | words.forEach(System.out::println);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Solutions/UserLogs_08.java:
--------------------------------------------------------------------------------
1 | package SetasAndMaps;
2 |
3 | import java.util.*;
4 |
5 | public class UserLogs_08 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | //username -> списък с всички ip-a
9 | //всяко ip -> брой на срещанията
10 |
11 | TreeMap> data = new TreeMap<>();
12 |
13 | String input = scanner.nextLine();
14 |
15 | while (!input.equals("end")) {
16 | //input = "IP={IP.Address} message={A&sample&message} user={username}"
17 | //input.split() -> ["IP={IP.Address}", "message={A&sample&message}", "user={username}"]
18 | //input.split()[0] -> "IP={IP.Address}".split("=") -> ["IP", "{ip addres}"]
19 | //input.split()[1] -> "message={A&sample&message}".split("=") -> ["message", "{message}"]
20 | //input.split()[2] -> "user={username}".split("=") -> ["user", "{username}"]
21 | String ip = input.split("\\s+")[0].split("=")[1];
22 | String username = input.split("\\s+")[2].split("=")[1];
23 |
24 | //нямаме такъв username
25 | if (!data.containsKey(username)) {
26 | //username -> празен мап за ip-тата
27 | data.put(username, new LinkedHashMap<>());
28 | }
29 |
30 | //имаме такъв username -> мап с ip-та
31 | //data: username (key) -> данни за ip (value)
32 | Map currentIps = data.get(username); // ip-тата на съответния username
33 | //въведеното ip да не е срещано
34 | if (!currentIps.containsKey(ip)) {
35 | currentIps.put(ip, 1);
36 | } else {
37 | currentIps.put(ip, currentIps.get(ip) + 1);
38 | }
39 | input = scanner.nextLine();
40 | }
41 |
42 | for (String username : data.keySet()) {
43 | //data.keySet() -> списък с всички usernames
44 | System.out.println(username + ": ");
45 |
46 | //ip-тата на username
47 | Map currentIps = data.get(username); //map с ip-ата на дадения username
48 |
49 | int countIps = currentIps.size(); //брой на ip-тата = брой на записите в мап
50 | //currentIps: ip (key) -> count(value)
51 | for (String ip : currentIps.keySet()) {
52 | if (countIps == 1) {
53 | //Последното ip за отпечатване
54 | System.out.println(ip + " => " + currentIps.get(ip) + ".");
55 | } else {
56 | //не ми е последното ip
57 | System.out.print(ip + " => " + currentIps.get(ip) + ", ");
58 | }
59 | countIps--;
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Theory/SetsAndMapsAdvanced_Theory.txt:
--------------------------------------------------------------------------------
1 | Set
2 | - структура от данни, в която съхраняваме уникални елементи
3 | - видове:
4 | 1. HashSet - нямаме специфична подредба на елементи
5 | 2. LinkedHashSet - редът на добавяне на елементите се запазва
6 | 3. TreeSet - елементите се сортират в ascending order
7 |
8 | Map
9 | - съвкупност от записи
10 | - запис: ключ -> стойност
11 | - всички ключове са уникални
12 | - видове:
13 | 1. HashMap - нямаме специфична подредба на записи
14 | 2. LinkedHashMap - редът на добавяне на записи се запазва
15 | 3. TreeMap - записи се сортират в ascending order спрямо техния ключ
16 |
--------------------------------------------------------------------------------
/Sets and Maps Advanced - Exercise/Videos/SetsAndMaps_Videos.txt:
--------------------------------------------------------------------------------
1 | 12. Сръбско Unleashed -> https://pastebin.com/HgdgUFCy
2 | видео: https://youtu.be/zz0oeaI4ayA?t=8365
3 |
4 | 07. Hands of Cards -> https://pastebin.com/xPkWvqDS
5 | видео: https://youtu.be/sFfxvhLYcy0?t=5697
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Demo/Demo_Fibonacci.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class Demo_Fibonacci {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 | //ЧИСЛА / РЕДИЦА НА ФИБОНАЧИ = 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ....
7 | //F1 = F2 = 1
8 | //F3 = F1 + F2
9 | //F4 = F2 + F3
10 | //F5 = F3 + F4
11 | //F6 = F4 + F5
12 | //F48 = F46 + F47
13 | //F49 = F48 + F47
14 | //F50 = F48 + F49
15 | //Fn = ?
16 | int n = Integer.parseInt(scanner.nextLine()); //за кое поред число искам да намеря Fn?
17 | System.out.println(fib(n));
18 | }
19 | public static long fib (int n) {
20 | //n = 1 -> F1 = 1
21 | //n = 2 -> F2 = 1
22 | if (n <= 2) {
23 | return 1;
24 | }
25 |
26 | //n = 20
27 | //F20 = ? = F19 + F18
28 | return fib(n - 1) + fib (n - 2);
29 | }
30 | }
31 |
32 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Demo/Demo_Recursion_Factorial.java:
--------------------------------------------------------------------------------
1 | public class Demo_Recursion_Factorial {
2 | public static void main(String[] args) {
3 | System.out.println(fact(6));
4 |
5 | }
6 | public static int fact (int n) {
7 | //!!! дъно !!!
8 | if (n == 0) {
9 | return 1;
10 | } else {
11 | return fact(n - 1) * n;
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/BalancesParenthesses_05.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Scanner;
5 |
6 | public class BalancesParenthesses_05 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | String input = scanner.nextLine(); //"{[()]}".toCharArray() -> ['{', '[', '(' ...]
10 |
11 | ArrayDeque openBracketsStack = new ArrayDeque<>(); //стек с отворени скоби
12 | boolean areBalanced = false; //дали скобите са балансирани
13 | //true -> скобите са балансирани
14 | //false -> скобите не са балансирани
15 |
16 | for (char bracket : input.toCharArray()) {
17 | //скоба
18 | //отворена -> (, [, { -> stack
19 | if (bracket == '(' || bracket == '[' || bracket == '{') {
20 | openBracketsStack.push(bracket);
21 | }
22 | //затворена -> ), ], }
23 | else if (bracket == ')' || bracket == ']' || bracket == '}') {
24 | //затворената скоба съвапада с последната добавена отворена
25 |
26 | //!!!! проверка дали има елементи на мястото, от което ще премахваме / взимаме !!!!!
27 | if (openBracketsStack.isEmpty()) {
28 | areBalanced = false;
29 | break;
30 | }
31 | char lastOpenBracket = openBracketsStack.pop();
32 |
33 | //проверка дали има баланс между текущата затворена и последната отворена
34 | //1. ( и )
35 | if (lastOpenBracket == '(' && bracket == ')') {
36 | //баланс
37 | areBalanced = true;
38 | }
39 | //2. [ и ]
40 | else if (lastOpenBracket == '[' && bracket == ']') {
41 | //баланс
42 | areBalanced = true;
43 | }
44 | //3. { и }
45 | else if (lastOpenBracket == '{' && bracket == '}') {
46 | //баланс
47 | areBalanced = true;
48 | } else {
49 | //нямаме баланс
50 | areBalanced = false;
51 | break;
52 | }
53 | }
54 | }
55 |
56 | //преминали през всички скоби или сме намерили небалансирани скоби
57 | //ако има баланс -> YES
58 | if (areBalanced) {
59 | System.out.println("YES");
60 | }
61 | //ако няма баланс -> NO
62 | else {
63 | System.out.println("NO");
64 | }
65 |
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/BasicQueueOperations_04.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Collections;
5 | import java.util.Scanner;
6 |
7 | public class BasicQueueOperations_04 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | int n = scanner.nextInt(); //брой на елементите, които трябва да добавя -> add
11 | int s = scanner.nextInt(); //брой на елементите, които тярбва да махна
12 | int x = scanner.nextInt(); //число, което проверявам дали го има
13 |
14 | //нов опашка
15 | ArrayDeque queue = new ArrayDeque<>();
16 |
17 | //ДОБАВЯНЕ (add) -> n на брой пъти
18 | for (int count = 1; count <= n; count++) {
19 | //add
20 | queue.offer(scanner.nextInt());
21 | }
22 |
23 | //ПРЕМАХВАНЕ (poll) -> s на брой пъти
24 | for (int count = 1; count <= s; count++) {
25 | queue.poll();
26 | }
27 |
28 | //ПРОВЕРКА ЗА НАЛИЧИЕ НА ЧИСЛОТО X В СТЕКА
29 | //ИМА
30 | if (queue.contains(x)) {
31 | System.out.println("true");
32 | } else {
33 | //НЯМА -> принтираме най-малкия елемент в стека
34 | if (queue.isEmpty()) {
35 | //празен стек
36 | System.out.println(0);
37 | } else {
38 | //имаме елементи
39 | System.out.println(Collections.min(queue));
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/BasicStackOperations_02.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Collections;
5 | import java.util.Scanner;
6 |
7 | public class BasicStackOperations_02 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | //"5 2 13"
11 |
12 | //1 начин
13 | int n = scanner.nextInt(); //брой на елементите, които трябва да добавя -> push
14 | int s = scanner.nextInt(); //брой на елементите, които тярбва да махна -> pop
15 | int x = scanner.nextInt(); //число, което проверявам дали го има
16 |
17 | //2 начин
18 | //scanner.nextLine() -> "5 2 13".split(" ") -> ["5", "2", "13"]
19 |
20 | //нов стек
21 | ArrayDeque stack = new ArrayDeque<>();
22 |
23 | //ДОБАВЯНЕ (push) -> n на брой пъти
24 | for (int count = 1; count <= n; count++) {
25 | stack.push(scanner.nextInt());
26 | }
27 |
28 | //ПРЕМАХВАНЕ (pop) -> s на брой пъти
29 | for (int count = 1; count <= s; count++) {
30 | stack.pop();
31 | }
32 |
33 | //ПРОВЕРКА ЗА НАЛИЧИЕ НА ЧИСЛОТО X В СТЕКА
34 | //ИМА
35 | if (stack.contains(x)) {
36 | System.out.println("true");
37 | } else {
38 | //НЯМА -> принтираме най-малкия елемент в стека
39 | if (stack.isEmpty()) {
40 | //празен стек
41 | System.out.println(0);
42 | } else {
43 | //имаме елементи
44 | System.out.println(Collections.min(stack));
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/InfixToPostfix_08.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Scanner;
5 |
6 | public class InfixToPostfix_08 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | String[] input = scanner.nextLine().split("\\s+");
10 | ArrayDeque operators = new ArrayDeque<>();
11 |
12 | for (int i = 0; i < input.length; i++) {
13 | String currentOperator = input[i];
14 | switch (currentOperator) {
15 | case "+":
16 | case "-":
17 | case "*":
18 | case "/":
19 | case "^":
20 | case "(":
21 | if (operators.isEmpty() || hasLowerPrecedence(operators.peek(), currentOperator)) {
22 | operators.push(currentOperator);
23 | } else {
24 | while (!hasLowerPrecedence(operators.peek(), currentOperator)) {
25 | System.out.print(operators.pop() + " ");
26 | if (operators.isEmpty()) {
27 | break;
28 | }
29 | }
30 |
31 | operators.push(currentOperator);
32 | }
33 | break;
34 | case ")":
35 | while (!operators.peek().equals("(")) {
36 | System.out.print(operators.pop() + " ");
37 | }
38 | operators.pop();
39 | break;
40 | default:
41 | System.out.print(currentOperator + " ");
42 | }
43 | }
44 |
45 | while (!operators.isEmpty()) {
46 | System.out.print(operators.pop() + " ");
47 | }
48 | }
49 |
50 | private static boolean hasLowerPrecedence(String current, String next) {
51 | int currentOperatorPrecedence = precedence(current);
52 | int nextOperatorPrecedence = precedence(next);
53 | if (currentOperatorPrecedence < nextOperatorPrecedence) {
54 | return true;
55 | } else if (currentOperatorPrecedence == nextOperatorPrecedence) {
56 | if (currentOperatorPrecedence == 3 || currentOperatorPrecedence == 4) {
57 | return true;
58 | } else {
59 | return false;
60 | }
61 | } else {
62 | if (currentOperatorPrecedence == 4) {
63 | return true;
64 | } else {
65 | return false;
66 | }
67 | }
68 | }
69 |
70 | private static int precedence(String operator) {
71 | int precedence = 0;
72 | if (operator.equals("+") || operator.equals("-")) {
73 | precedence = 1;
74 | } else if (operator.equals("*") || operator.equals("/")) {
75 | precedence = 2;
76 | } else if (operator.equals("^")) {
77 | precedence = 3;
78 | } else if (operator.equals("(")) {
79 | precedence = 4;
80 | }
81 |
82 | return precedence;
83 | }
84 | }
85 |
86 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/MaximumElement_03.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Collections;
5 | import java.util.Scanner;
6 |
7 | public class MaximumElement_03 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | ArrayDeque stack = new ArrayDeque<>();
11 | int n = Integer.parseInt(scanner.nextLine());
12 |
13 | for (int count = 1; count <= n; count++) {
14 | String command = scanner.nextLine();
15 | //"1 X" -> push x to stack
16 | //"2" -> pop of stack
17 | //"3" -> print max element only if stack is not empty
18 | if (command.equals("2")) {
19 | stack.pop();
20 | } else if (command.equals("3")) {
21 | //проверка дали имаме елементи
22 | if (stack.size() > 0) {
23 | System.out.println(Collections.max(stack));
24 | }
25 | } else {
26 | //command = "1 97" .split -> ["1", "97"]
27 | int x = Integer.parseInt(command.split("\\s+")[1]);
28 | stack.push(x);
29 | }
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/PoisonousPlants_09.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Arrays;
5 | import java.util.Scanner;
6 |
7 | public class PoisonousPlants_09 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | int n = Integer.parseInt(scanner.nextLine());
11 | int[] plants = Arrays.stream(scanner.nextLine().split(" "))
12 | .mapToInt(Integer::parseInt)
13 | .toArray();
14 |
15 |
16 | ArrayDeque prevPlants = new ArrayDeque<>();
17 | int[] days = new int[plants.length];
18 | prevPlants.push(0);
19 | for (int x = 1; x < plants.length; x++) {
20 | int maxDays = 0;
21 | while (prevPlants.size() > 0 && plants[prevPlants.peek()] >= plants[x]) {
22 |
23 | maxDays = Integer.max(days[prevPlants.pop()], maxDays);
24 | }
25 |
26 | if (prevPlants.size() > 0) {
27 | days[x] = maxDays + 1;
28 | }
29 |
30 | prevPlants.push(x);
31 | }
32 |
33 | System.out.printf("%d", Arrays.stream(days).max().getAsInt());
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/RecursiveFibonacci_06.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.Scanner;
4 |
5 | public class RecursiveFibonacci_06 {
6 | public static long [] memoryForFib;
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | int n = Integer.parseInt(scanner.nextLine());
11 | memoryForFib = new long [n + 1];
12 | System.out.println(fib(n));
13 |
14 | }
15 |
16 | public static long fib (int n) {
17 | if (n <= 1) {
18 | return 1;
19 | }
20 |
21 | if (memoryForFib[n] != 0) {
22 | //имаме го изчислено
23 | return memoryForFib[n];
24 | }
25 |
26 | return memoryForFib[n] = fib(n - 1) + fib (n - 2);
27 |
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/ReverseNumbersWithStack_01.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Scanner;
5 |
6 | public class ReverseNumbersWithStack_01 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | //"1 2 3 4 5"
10 | //1. всички числа да ги сложим в стек
11 | //2. повтаряме: вадим число от стека -> докато стека е пълен
12 | // спираме: стекът стане празен -> stack.isEmpty()
13 | String input = scanner.nextLine(); //"1 2 3 4 5"
14 | String[] inputNumbers = input.split("\\s+"); //["1", "2", "3", "4", "5"]
15 |
16 | ArrayDeque stack = new ArrayDeque<>();
17 | for (String number : inputNumbers) {
18 | stack.push(number);
19 | }
20 |
21 | while (!stack.isEmpty()) {
22 | System.out.print(stack.pop() + " ");
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/Robotics_10.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.LinkedHashMap;
5 | import java.util.Map;
6 | import java.util.Scanner;
7 |
8 | public class Robotics_10 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 | String[] inputRobot = scanner.nextLine().split(";"); //всички роботи с времената
12 | LinkedHashMap robots = getLinkedHashMap(inputRobot);
13 | String time = scanner.nextLine(); //час:минути:секунди
14 | int hours = Integer.parseInt(time.split(":")[0]);
15 | int minutes = Integer.parseInt(time.split(":")[1]);
16 | int seconds = Integer.parseInt(time.split(":")[2]);
17 |
18 | long totalTimeInSeconds = hours * 3600 + minutes * 60 + seconds;
19 |
20 | ArrayDeque products = new ArrayDeque<>();
21 | int [] workingTime = new int[robots.size()];
22 |
23 | String product = scanner.nextLine();
24 | while (!product.equals("End")) {
25 | products.offer(product);
26 | product = scanner.nextLine();
27 | }
28 |
29 | while(!products.isEmpty()){
30 | String currentProduct = products.poll();
31 | //увеличим текущото време
32 | totalTimeInSeconds++;
33 | boolean isAssigned = false;
34 | //намаляме работното време с 1 секунда
35 | for (int robot = 0; robot < workingTime.length; robot++) {
36 | if(workingTime[robot] > 0) {
37 | --workingTime[robot];
38 | }
39 | }
40 | //обхождане на работното време
41 | for (int i = 0; i < workingTime.length; i++) {
42 | if(workingTime[i] == 0) {
43 | //свободен -> кой е робота -> времето
44 | int count = 0;
45 | for (Map.Entry robot : robots.entrySet()){
46 | if (count == i) {
47 | workingTime[i] = robot.getValue();
48 | //totalSeconds -> hours, minute, seconds
49 | long takenHour = totalTimeInSeconds / 3600 % 24;
50 | long takenMinute = totalTimeInSeconds % 3600 / 60;
51 | long takenSeconds = totalTimeInSeconds % 60;
52 | System.out.printf("%s - %s [%02d:%02d:%02d]%n", robot.getKey(), currentProduct, takenHour, takenMinute, takenSeconds);
53 | isAssigned = true;
54 | break;
55 | }
56 | count++;
57 | }
58 | break;
59 | }
60 | }
61 | //проверили всички роботи
62 | if(!isAssigned) {
63 | products.offer(currentProduct);
64 | }
65 |
66 | }
67 |
68 |
69 |
70 | }
71 |
72 | private static LinkedHashMap getLinkedHashMap(String[] inputRobot) {
73 | LinkedHashMap robots = new LinkedHashMap<>();
74 | for (int i = 0; i < inputRobot.length ; i++) {
75 | //name-time -> ["ROB", "15"]
76 | String name = inputRobot[i].split("-")[0];
77 | int time = Integer.parseInt(inputRobot[i].split("-")[1]);
78 | robots.put(name, time);
79 | }
80 | return robots;
81 | }
82 |
83 | }
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Solutions/SimpleTextEditor_07.java:
--------------------------------------------------------------------------------
1 | package stacksAndQueues;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Scanner;
5 |
6 | public class SimpleTextEditor_07 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | int n = Integer.parseInt(scanner.nextLine()); //брой команди
10 | StringBuilder currentText = new StringBuilder();
11 | ArrayDeque textStack = new ArrayDeque<>();
12 |
13 | for (int commandNumber = 1; commandNumber <= n; commandNumber++) {
14 | String command = scanner.nextLine(); //текст на команда
15 | if (command.startsWith("1")) {
16 | //преди модификация съхраняваме текущото състояние преди промяната
17 | textStack.push(currentText.toString());
18 | //command = "1 {string}".split(" ") -> ["1", "{string}"]
19 | String textToAppend = command.split("\\s+")[1];
20 | currentText.append(textToAppend);
21 | } else if (command.startsWith("2")) {
22 | //преди модификация съхраняваме текущото състояние преди промяната
23 | textStack.push(currentText.toString());
24 | //command = "2 5".split(" ") -> ["2", "5"]
25 | int count = Integer.parseInt(command.split("\\s+")[1]);
26 | //изтрием последните count на брой символа
27 | //"Desislava" -> count = 2 -> "Desisla"
28 | //"table" -> count = 3 -> "ta"
29 | int startIndexForDelete = currentText.length() - count;
30 | currentText.delete(startIndexForDelete, currentText.length());
31 | } else if (command.startsWith("3")) {
32 | //command = "3 7".split(" ") -> ["3", "7"]
33 | int position = Integer.parseInt(command.split("\\s+")[1]); //мястото на буквата в думата
34 | System.out.println(currentText.charAt(position - 1));
35 | } else if (command.equals("4")) {
36 | //command = "4"
37 | //!!!!!!!!
38 | if (!textStack.isEmpty()) {
39 | String last = textStack.pop();
40 | currentText = new StringBuilder(last);
41 | }
42 | }
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Theory/StacksAndQueue_Theory.txt:
--------------------------------------------------------------------------------
1 | STACK (LIFO) -> купчина от книги
2 | добавяне -> push
3 | премахване -> pop
4 | преглед -> peek
5 |
6 | QUEUE (FIFO) -> опашка в магазин
7 | добавяне -> offer (add)
8 | премахване -> poll (remove)
9 | преглед -> peek
10 |
11 |
12 | List / Array -> искаме да имаме пряк достъп до всички елементи
13 | list = {1, 5, 6, 7, 8} -> list.get(5)
14 | array = [2, 4, 5, 6, 8] -> array[3]
15 |
16 | Stack / Queue -> искаме да имаме достъп до първия / последния
17 | Stack -> последния добавен елемент
18 | Queue -> първия добавен елемент
19 |
20 |
21 | При избор на структутра от данни, в която ще съхранявам:
22 | 1. Кои елементи ще достъпвам?
23 | - всички -> list / array
24 | - първи / последния -> stack / queue
25 |
26 | 2. Ако ще използвам list или array?
27 | - list -> ако искаме да модифицираме елементите
28 | - array -> ако искаме само да съхраняваме, без много модификации
29 |
30 | 3. Ако ще използвам stack или queue?
31 | - stack -> ако искаме достъп до последния елемент
32 | - queue -> ако искаме достъп до първия елемент
--------------------------------------------------------------------------------
/Stacks And Queues - Exercise/Videos/StacksAndQueues_Videos.txt:
--------------------------------------------------------------------------------
1 | 06. Recursive Fibonacci -> https://pastebin.com/E58jfqgB
2 | видео: https://www.youtube.com/watch?v=z3wWIVUwNAo&t=10300s
3 |
4 | 10. Robotics (решение с Map) -> https://pastebin.com/r2yYHatm
5 | 10. Robotics (решение с масив) -> https://pastebin.com/h7FivYpT
6 | видео: https://www.youtube.com/watch?v=XK-rdc4oCl8&t=3345s
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Demo/Demo.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.Scanner;
3 |
4 | public class Demo {
5 | public static void main(String[] args) throws IOException {
6 | //WRITERS -> ПИШЕМ ВЪВ ФАЙЛОВЕТЕ
7 | String pathToFile = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\JavaAdvanced_Jan_2023\\src\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\demoFileWriter.txt";
8 | String pathToFile2 = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\JavaAdvanced_Jan_2023\\src\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\demoBufferedWriter.txt";
9 | //1. FileWriter
10 | File file = new File(pathToFile);
11 | FileWriter fileWriter = new FileWriter(file);
12 | fileWriter.write("This is a demo of file writer.");
13 | fileWriter.close();
14 |
15 | //2. BufferedWriter -> по-бърз от FileWriter
16 | File fileForBuffered = new File(pathToFile2);
17 | FileWriter fileWriter2 = new FileWriter(fileForBuffered);
18 | BufferedWriter bfWriter = new BufferedWriter(fileWriter2);
19 | bfWriter.write("This is a demo of buffered writer.");
20 | bfWriter.close();
21 |
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Demo/NavyBattle_02.java:
--------------------------------------------------------------------------------
1 | package StreamsFileasAndDirectories;
2 |
3 | import java.util.Scanner;
4 |
5 | public class NavyBattle_02 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int n = Integer.parseInt(scanner.nextLine()); //размер на бойното поле
9 | //n -> бр. редове = бр. колони
10 |
11 | String[][] matrix = new String[n][n]; //бойно поле
12 |
13 | //1. пълним матрицата (бойно поле)
14 | fillMatrix(matrix, scanner);
15 |
16 | //2. къде се намира подводницата на бойното поле -> старт
17 | int submarineRow = -1; //текущ ред на подводницата
18 | int submarineCol = -1; //текущата колона на подводницата
19 | int countHits = 0; //брой на пътите, в които е уцелена подводницата
20 | int countCruiser = 0; //брой на потопени круизни кораби
21 |
22 | for (int row = 0; row < n; row++) {
23 | for (int col = 0; col < n; col++) {
24 | if (matrix[row][col].equals("S")) {
25 | submarineRow = row;
26 | submarineCol = col;
27 | break;
28 | }
29 | }
30 | }
31 |
32 | String command = scanner.nextLine();
33 | while (true) {
34 |
35 | //започваме движението
36 | matrix[submarineRow][submarineCol] = "-";
37 | //премествам самата подводница
38 | if (command.equals("up")) {
39 | submarineRow--;
40 | } else if (command.equals("down")) {
41 | submarineRow++;
42 | } else if (command.equals("left")) {
43 | submarineCol--;
44 | } else if (command.equals("right")) {
45 | submarineCol++;
46 | }
47 | //имаме новата позиция на подводницата -> matrix[submarineRow, submarineCol]
48 | String submarinePosition = matrix[submarineRow][submarineCol]; //на какво място се е преместила подводницата
49 |
50 | if (submarinePosition.equals("-")) {
51 | matrix[submarineRow][submarineCol] = "S";
52 | } else if (submarinePosition.equals("*")) {
53 | matrix[submarineRow][submarineCol] = "S";
54 | //мина, която ни разрушава частично
55 | countHits++;
56 | if (countHits == 3) {
57 | //подовдницата е унищожена -> губя
58 | System.out.printf("Mission failed, U-9 disappeared! Last known coordinates [%d, %d]!%n",submarineRow, submarineCol);
59 | break;
60 | }
61 | } else if (submarinePosition.equals("C")) {
62 | matrix[submarineRow][submarineCol] = "S";
63 | countCruiser++; //потапяме круизен кораб
64 | if (countCruiser == 3) {
65 | //печеля
66 | System.out.println("Mission accomplished, U-9 has destroyed all battle cruisers of the enemy!");
67 | break;
68 | }
69 | }
70 |
71 | command = scanner.nextLine();
72 | }
73 |
74 | //приключва битката -> принтираме бойното поле
75 | printMatrix(matrix);
76 |
77 | }
78 |
79 | private static void fillMatrix(String[][] matrix, Scanner scanner) {
80 | for (int row = 0; row < matrix.length; row++) {
81 | //scanner.nextLine() -> "--*--"
82 | //scanner.nextLine().split("") -> ["-", "-", "*", "-", "-"]
83 | matrix[row] = scanner.nextLine().split("");
84 | }
85 | }
86 |
87 | private static void printMatrix(String[][] matrix) {
88 | for (int row = 0; row < matrix.length; row++) {
89 | for (int col = 0; col < matrix.length; col++) {
90 | System.out.print(matrix[row][col]);
91 | }
92 | System.out.println(); //свали курсора на следващия ред
93 | }
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Solutions/AllCapitals_03.java:
--------------------------------------------------------------------------------
1 | package StreamsFileasAndDirectories;
2 |
3 | import java.io.*;
4 | import java.nio.file.Files;
5 | import java.nio.file.Path;
6 | import java.util.List;
7 |
8 | public class AllCapitals_03 {
9 | public static void main(String[] args) throws IOException {
10 | //1. взимаме всички редове от файл input.txt
11 | //2. обхождаме всеки един ред -> правим всички букви главни -> записваме реда с главаните букви в нов файл
12 | String pathToFile = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\JavaAdvanced_Jan_2023\\src\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\input.txt";
13 |
14 | BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
15 | //начин 1:
16 | /*List allLines = Files.readAllLines(Path.of(pathToFile));
17 | for (String line : allLines) {
18 | writer.write(line.toUpperCase());
19 | writer.newLine();
20 | }
21 | writer.close();*/
22 |
23 | //начин 2:
24 | BufferedReader reader = new BufferedReader(new FileReader(pathToFile));
25 | String line = reader.readLine();
26 | //line == null -> нямаме такъв ред
27 | while (line != null) {
28 | writer.write(line.toUpperCase());
29 | writer.newLine();
30 |
31 | line = reader.readLine();
32 | }
33 |
34 | writer.close();
35 |
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Solutions/CountCharacterTypes_04.java:
--------------------------------------------------------------------------------
1 | package StreamsFileasAndDirectories;
2 |
3 | import java.io.BufferedWriter;
4 | import java.io.FileWriter;
5 | import java.io.IOException;
6 | import java.nio.file.Files;
7 | import java.nio.file.Path;
8 | import java.util.HashSet;
9 | import java.util.List;
10 | import java.util.Set;
11 |
12 | public class CountCharacterTypes_04 {
13 | public static void main(String[] args) throws IOException {
14 | //гласни: a, e, i, o, u
15 | //пунктуационни знаци: ! , . ?
16 | //съгласни: всичко останало
17 | int vowelsCount = 0; //броя на гласните букви
18 | int punctCount = 0; //броя на пунктуационните знаци
19 | int consonantsCount = 0; //броя на съгласните букви
20 |
21 | Set vowels = getVowels(); //всички възможни главни букви
22 | Set punctuationalMarks = getPuntMarks(); //всички възможни пунктуационни знаци
23 |
24 | String path = "C:\\Users\\I353529\\Desktop\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\input.txt";
25 | List allLines = Files.readAllLines(Path.of(path));
26 |
27 | for (String line : allLines) {
28 | //"On January 1 , 1533 , "
29 | for (int index = 0; index < line.length(); index++) {
30 | char currentSymbol = line.charAt(index);
31 | if (currentSymbol == ' ') {
32 | continue;
33 | }
34 | //проверка на символа
35 | if (vowels.contains(currentSymbol)) { //гласна буква
36 | vowelsCount++;
37 | } else if (punctuationalMarks.contains(currentSymbol)) { //пунктуационен знак
38 | punctCount++;
39 | } else { //съгласна буква
40 | consonantsCount++;
41 | }
42 | }
43 | }
44 | //знаем броят на символите във всяка категория
45 | BufferedWriter writer = new BufferedWriter(new FileWriter("output_task_4.txt"));
46 | writer.write("Vowels: " + vowelsCount);
47 | writer.newLine();
48 | writer.write("Consonants: " + consonantsCount);
49 | writer.newLine();
50 | writer.write("Punctuation: " + punctCount);
51 | writer.close();
52 |
53 | }
54 |
55 | private static Set getPuntMarks() {
56 | Set marks = new HashSet<>();
57 | marks.add('!');
58 | marks.add('?');
59 | marks.add('.');
60 | marks.add(',');
61 | return marks;
62 | }
63 |
64 | private static Set getVowels() {
65 | Set vowels = new HashSet<>();
66 | vowels.add('a');
67 | vowels.add('e');
68 | vowels.add('i');
69 | vowels.add('o');
70 | vowels.add('u');
71 | return vowels;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Solutions/GetFolderSize_08.java:
--------------------------------------------------------------------------------
1 | package StreamsFileasAndDirectories;
2 |
3 | import java.io.File;
4 |
5 | public class GetFolderSize_08 {
6 | public static void main(String[] args) {
7 | String pathFolder = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\JavaAdvanced_Jan_2023\\src\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\Exercises Resources";
8 | File folder = new File(pathFolder);
9 |
10 | File[] allFilesInFolder = folder.listFiles(); //масив с всички файлове в папката
11 |
12 | int folderSize = 0; //размер на папката
13 | if (allFilesInFolder != null) {
14 | for (File file : allFilesInFolder) {
15 | folderSize += file.length();
16 | }
17 | }
18 |
19 |
20 | System.out.println("Folder size: " + folderSize);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Solutions/LineNumbers_05.java:
--------------------------------------------------------------------------------
1 | package StreamsFileasAndDirectories;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 | import java.nio.file.Files;
6 | import java.nio.file.Path;
7 | import java.util.List;
8 |
9 | public class LineNumbers_05 {
10 | public static void main(String[] args) throws IOException {
11 | //1. прочитам всички редове от файл inputLineNumbers.txt
12 | //2. обхождаме всеки ред -> записваме в нов файл с пореден номер отпред
13 | String path = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\JavaAdvanced_Jan_2023\\src\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\inputLineNumbers.txt";
14 | List allLines = Files.readAllLines(Path.of(path));
15 |
16 | PrintWriter writer = new PrintWriter("output_line_numbers.txt");
17 | int lineNumber = 1;
18 | for (String line : allLines) {
19 | writer.println(lineNumber + ". " + line);
20 | lineNumber++;
21 | }
22 |
23 | writer.close(); //спирам да пиша във файла и файлът се затваря
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Solutions/MergeTwoFiles_07.java:
--------------------------------------------------------------------------------
1 | package StreamsFileasAndDirectories;
2 |
3 | import java.io.FileNotFoundException;
4 | import java.io.IOException;
5 | import java.io.PrintWriter;
6 | import java.nio.file.Files;
7 | import java.nio.file.Path;
8 | import java.util.List;
9 |
10 | public class MergeTwoFiles_07 {
11 | public static void main(String[] args) throws IOException {
12 | //1. четем всички редове от файл 1
13 | String pathFileOne = "C:\\Users\\I353529\\Desktop\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\inputOne.txt";
14 | //2. четем всички редове от файл 2
15 | String pathFileTwo = "C:\\Users\\I353529\\Desktop\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\inputTwo.txt";
16 | //3. записваме всички редове във файл 3
17 | PrintWriter writer = new PrintWriter("outputMerge.txt");
18 |
19 | List allLinesFileOne = Files.readAllLines(Path.of(pathFileOne)); //всички редове от файл 1
20 | allLinesFileOne.forEach(line -> writer.println(line));
21 | List allLinesFileTwo = Files.readAllLines(Path.of(pathFileTwo)); //всички редове от файл 2
22 | allLinesFileTwo.forEach(line -> writer.println(line));
23 |
24 | writer.close();
25 |
26 |
27 | }
28 | }
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Solutions/SumBytes_02.java:
--------------------------------------------------------------------------------
1 | package StreamsFileasAndDirectories;
2 |
3 | import javax.swing.plaf.basic.BasicColorChooserUI;
4 | import java.io.IOException;
5 | import java.nio.file.Files;
6 | import java.nio.file.Path;
7 | import java.util.List;
8 |
9 | public class SumBytes_02 {
10 | public static void main(String[] args) throws IOException {
11 | //1. всички редове от файл input.txt
12 | //2. принтираме сумата от ascii кодовете на символите на всички редове
13 |
14 | String pathToFile = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\JavaAdvanced_Jan_2023\\src\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\input.txt";
15 | long sum = 0; //сума от аски кодовете на всички символи
16 |
17 | //начин 1:
18 | /*List allLines = Files.readAllLines(Path.of(pathToFile)); //лист с всички редове (текст)
19 |
20 | for (String line : allLines) {
21 | for (char symbol : line.toCharArray()) {
22 | sum += symbol;
23 | }
24 | }
25 | System.out.println(sum);*/
26 |
27 | //начин 2:
28 | //byte -> -127 до 128
29 | //sbyte -> 0 до 256
30 | byte [] allBytes = Files.readAllBytes(Path.of(pathToFile));
31 | //масив от аски кодовете на всички символи (включително нов ред и carriage return) във файл
32 | // ascii = 10 -> символ за нов ред
33 | // ascii = 13 -> символ, обозначаващ начало на нов ред
34 | for (byte ascii : allBytes) {
35 | if (ascii != 13 && ascii != 10) {
36 | sum += ascii;
37 | }
38 | }
39 | System.out.println(sum);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Solutions/SumLines_01.java:
--------------------------------------------------------------------------------
1 | package StreamsFileasAndDirectories;
2 |
3 | import java.io.IOException;
4 | import java.nio.file.Files;
5 | import java.nio.file.Path;
6 | import java.util.List;
7 |
8 | public class SumLines_01 {
9 | public static void main(String[] args) throws IOException {
10 | //1. всички редове от файл input.txt
11 | //2. за всеки ред -> намирам суамта от аscii -> принтираме сумата
12 |
13 | String pathToFile = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\JavaAdvanced_Jan_2023\\src\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\input.txt";
14 | List allLines = Files.readAllLines(Path.of(pathToFile));
15 |
16 | //начин 1:
17 | /* for (String line : allLines) {
18 | //line = "Michael Angelo, "
19 | int sum = 0; //сума от кодовете на символите на този ред
20 | for (char symbol : line.toCharArray()) {
21 | sum += (int) symbol;
22 | }
23 | System.out.println(sum);
24 | }*/
25 |
26 | //начин 2:
27 | allLines.forEach(line -> {
28 | int sum = 0; //сума от кодовете на символите на този ред
29 | for (char symbol : line.toCharArray()) {
30 | sum += (int) symbol;
31 | }
32 | System.out.println(sum);
33 | });
34 |
35 | //начин 3:
36 | /*allLines.stream()
37 | .map(line -> line.toCharArray())
38 | .forEach(arr -> { //за всеки един масив от символи
39 | int sum = 0; //сума от кодовете на символите на този ред
40 | for (char symbol : arr) {
41 | sum += (int) symbol;
42 | }
43 | System.out.println(sum);
44 | });*/
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Solutions/WordsCount_06.java:
--------------------------------------------------------------------------------
1 | package StreamsFileasAndDirectories;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 | import java.nio.file.Files;
6 | import java.nio.file.Path;
7 | import java.util.Arrays;
8 | import java.util.HashMap;
9 | import java.util.List;
10 | import java.util.Map;
11 |
12 | public class WordsCount_06 {
13 | public static void main(String[] args) throws IOException {
14 | //1. да намерим кои думи ще броим
15 | //words.txt -> думи, които трябва да търсим
16 | String pathWords = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\JavaAdvanced_Jan_2023\\src\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\Exercises Resources\\words.txt";
17 | List allLinesWithWords = Files.readAllLines(Path.of(pathWords));
18 | //дума -> бр. срещанията
19 | Map countWords = new HashMap<>();
20 |
21 | for (String line : allLinesWithWords){
22 | //line = "of which The".split(" ") -> ["of", "which", "The"]
23 | String [] wordsOnCurrentRow = line.split("\\s+");
24 | Arrays.stream(wordsOnCurrentRow).forEach(word -> {
25 | countWords.put(word, 0);
26 | });
27 | }
28 |
29 | //2. преброим думите от стъпка 1 колко пъти се срещат във файл text.txt
30 | // countWords -> кои са думите, които търсим
31 | String pathText = "C:\\Users\\I353529\\Documents\\SoftUni\\Projects\\JavaAdvanced_Jan_2023\\src\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\Exercises Resources\\text.txt";
32 | List allLinesWithText = Files.readAllLines(Path.of(pathText));
33 | for (String line : allLinesWithText) {
34 | //line = "There are many variations of passages of Lorem Ipsum available".split(" ")
35 | //премахваме препинателните знаци -> точка, запетая, ?, !, :
36 | line = line.replaceAll("[\\.\\,\\?\\!\\:]", "");
37 | String [] words = line.split("\\s+"); //думите на съответния ред
38 | for (String word : words) {
39 | if (countWords.containsKey(word)) {
40 | countWords.put(word, countWords.get(word) + 1);
41 | }
42 | }
43 | }
44 |
45 | //3. знаем коя буква колко пъти се среща
46 | //сортираме записите по броя на срещанията -> sort by value descending order
47 | //запис: key(дума) -> value (бр. срещанията)
48 | PrintWriter writer = new PrintWriter("result.txt");
49 | countWords.entrySet().stream()
50 | .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue())) //сортиран map
51 | .forEach(entry -> writer.println(entry.getKey() + " - " + entry.getValue()));
52 | writer.close();
53 |
54 | //sorted (число)
55 | //число е 0 -> не разменя местата на записите
56 | //число е 1 -> разменя местата на записите
57 | //число е - 1 -> не разменя местата на записите
58 |
59 | //compareTo -> връща цяло число
60 | //0 -> първото == второто
61 | //1 -> първото > второто
62 | //-1 -> второто > първото
63 |
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Streams, Files and Directories - Exercise/Videos/StreamsFilesDirectories_Videos.txt:
--------------------------------------------------------------------------------
1 | Изпитна задача от минал изпит на 23.10.2021:
2 | 02. Mouse and cheese -> https://pastebin.com/xi1RzPPx
3 | видео: https://youtu.be/6tLG9EHzeps?t=9706
--------------------------------------------------------------------------------