Compare commits

..

50 Commits

Author SHA1 Message Date
a8cbadbe7d Added a Kotlin variation. 2023-05-07 23:15:50 +03:00
64c9e43742 Added a Kotlin variation. 2023-05-07 23:15:28 +03:00
5ca9ab6c17 Added a Kotlin variation. 2023-05-07 23:14:50 +03:00
a97f742be2 Added a Kotlin variation. 2023-05-07 23:14:24 +03:00
2494bea36c Camel case. 2023-05-07 22:20:31 +03:00
ca2b85ef9e . 2023-05-07 17:09:03 +03:00
77f96fafa6 Working model of Lab 3. 2023-05-07 17:07:56 +03:00
084f131c90 . 2023-05-07 16:46:18 +03:00
197426e266 Initial lab 3. 2023-05-07 15:19:23 +03:00
661c3641a1 Naming changes. 2023-05-07 15:19:06 +03:00
fc5704dd15 Cargo.toml added release profile. 2023-05-07 14:08:43 +03:00
45ef70b268 Finished lab_1 in Rust. 2023-05-07 09:26:25 +03:00
fe97b8dcde . 2023-05-06 23:56:34 +03:00
5c8d2bb8a1 . 2023-05-06 23:55:52 +03:00
6b6076f56c Merge branch 'ІО-23/30-Швед-Андрій-Дмитрович' of https://github.com/ASDjonok/OOP_IO-2x_2023 into ІО-23/30-Швед-Андрій-Дмитрович 2023-05-06 23:50:25 +03:00
9b08eb0dfc . 2023-05-06 23:50:22 +03:00
Rhinemann
9cce8b222e Delete Rust/lab_1/target directory 2023-05-06 23:47:52 +03:00
74209977bc . 2023-05-06 23:44:34 +03:00
83b275cefd . 2023-05-06 23:18:57 +03:00
af7af4d6f2 . 2023-05-06 23:09:06 +03:00
a4a3e09735 Lab 1. 2023-05-03 10:40:04 +03:00
acc2d533cb modified: Java/Lab 2/Lab_2.java 2023-05-03 10:39:06 +03:00
8013099c36 All sorts of corrections. 2023-05-03 10:32:23 +03:00
8100129706 Ceanup. 2023-05-02 11:42:37 +03:00
83d98b2982 Merge branch 'ІО-23/30-Швед-Андрій-Дмитрович' of https://github.com/ASDjonok/OOP_IO-2x_2023 into ІО-23/30-Швед-Андрій-Дмитрович 2023-05-02 11:40:28 +03:00
4af0ab5655 . 2023-05-02 11:38:55 +03:00
Rhinemann
07e9fbdc88 Delete Lab_2.class 2023-05-02 11:35:28 +03:00
Rhinemann
41aaaf4623 Delete Lab_1.class 2023-05-02 11:35:16 +03:00
99e9428dba Moved folders. 2023-05-02 11:34:34 +03:00
fe36219746 Update Lab 1. 2023-05-02 09:58:31 +03:00
896fc1f4d4 Minor cleanup 2023-04-26 14:37:46 +03:00
7fa667cb2d Changes 2023-04-26 14:34:13 +03:00
74a44852af Add Lab 2 2023-03-23 09:10:55 +02:00
Rhinemann
75112d90c2 Delete OOP_IO-2x_2023.iml 2023-03-23 08:59:27 +02:00
Rhinemann
e21575fa93 Delete .gitignore 2023-03-23 08:59:19 +02:00
Rhinemann
cf3d055f64 Delete src directory 2023-03-23 08:57:30 +02:00
Rhinemann
bdf5611f46 Delete .idea directory 2023-03-23 08:57:03 +02:00
Rhinemann
80de92fa1e Lab 1 commit 2023-03-22 17:02:31 +02:00
Oleksii Aleshchenko
14c58d0cc4 add lab2 2023-03-16 15:58:44 +02:00
Oleksii Aleshchenko
afc13cf9f8 add char example for lab1 2023-03-16 15:21:51 +02:00
Oleksii Aleshchenko
e910ee6e4d add final way of check division by zero for lab1 2023-03-16 15:07:48 +02:00
Oleksii Aleshchenko
6ab6cc17db add break with label (commented in line 34) and return for lab1 2023-03-16 15:00:12 +02:00
Oleksii Aleshchenko
25173d66d1 add flag "wasDivisionByZero" for lab1 2023-03-16 14:47:04 +02:00
Oleksii Aleshchenko
41ad598b79 add lab1 2023-03-09 16:01:01 +02:00
Oleksii Aleshchenko
13e1a61ad9 update Main with example for difference & and && 2023-03-02 16:07:34 +02:00
Oleksii Aleshchenko
f692ae7588 update polymorphism example 2023-03-02 15:48:38 +02:00
Oleksii Aleshchenko
429bcc7b3d add polymorphism example 2023-03-02 15:26:42 +02:00
Oleksii Aleshchenko
4b159fa22b update inheritance example 2023-03-02 14:41:44 +02:00
Oleksii Aleshchenko
2880b770f7 add inheritance example 2023-02-23 16:04:53 +02:00
Oleksii Aleshchenko
53a9d20438 Update Main.java 2023-02-23 14:30:35 +02:00
78 changed files with 290 additions and 1056 deletions

4
.gitignore vendored
View File

@@ -1,2 +1,2 @@
# Project exclude paths
/out/
Rust/lab_1/target
Rust/lab_2/target

31
Java/lab_1/lab_1.java Normal file
View File

@@ -0,0 +1,31 @@
import java.util.Scanner;
public class lab_1 {
public static int protectedInput(String variableToRead, Scanner input) {
do {
try {
System.out.printf("Enter %s: ", variableToRead);
return input.nextInt();
} catch (Exception e) {
System.out.printf("%s must be an integer.\n", variableToRead.toUpperCase());
input.nextLine();
}
} while (true);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int n = protectedInput("n", input);
final int m = protectedInput("m", input);
final int a = protectedInput("a", input);
final int b = protectedInput("b", input);
input.close();
final float s = ((float) (b + m) / 2) * (m - b + 1) * (n - a + 1);
System.out.println("S = " + s);
}
}

21
Java/lab_1/lab_1.kt Normal file
View File

@@ -0,0 +1,21 @@
fun protectedInput(variableName: String): Int {
do {
try {
print("Enter $variableName: ")
return readln().toInt()
} catch (e: Exception) {
println("${variableName.uppercase()} must be an integer!")
}
} while (true)
}
fun main() {
val n: Int = protectedInput("n")
val m: Int = protectedInput("m")
val a: Int = protectedInput("a")
val b: Int = protectedInput("b")
val s: Float = (b + m).toFloat() / 2 * (m - b + 1) * (n - a + 1)
println("S = $s")
}

106
Java/lab_2/lab_2.java Normal file
View File

@@ -0,0 +1,106 @@
import java.util.Scanner;
public class lab_2 {
public static short protectedInput(String inputPrompt, String errorMessage, Scanner input) {
short read_variable;
do {
try {
System.out.println();
System.out.print(inputPrompt);
read_variable = input.nextShort();
break;
} catch (Exception e) {
System.out.println(errorMessage);
input.nextLine();
}
} while (true);
return read_variable;
}
public static String format(int number) {
int width = String.valueOf(number).length() + 1;
String format = "|%" + width + "d ";
return format;
}
public static double average(short[] row) {
short sum = 0;
for (short element : row) {
sum += element;
}
double result = sum / row.length;
return result;
}
public static void main(String[] args) {
short a, rows = 0, columns = 0;
String format;
Scanner input = new Scanner(System.in);
a = protectedInput("Input a constant to multipy a matrix by: ",
"A constant must be a short-data type integer, try again.", input);
System.out.println();
System.out.println("Input size of the matrix.");
do {
rows = protectedInput("Rows: ",
"A number of rows must be a short-data type integer, try again.", input);
} while (rows <= 0);
do {
columns = protectedInput("Columns: ",
"A number of columns must be a short-data type integer, try again.", input);
} while (columns <= 0);
input.close();
short[][] matrix_B = new short[rows][columns];
System.out.println();
System.out.println("Matrix B:");
format = format(rows * columns);
for (short i = 0; i < rows; i++) {
for (short j = 0; j < columns; j++) {
matrix_B[i][j] = (short) ((i + 1) * (j + 1));
System.out.printf(format, matrix_B[i][j]);
}
System.out.println("|");
}
System.out.println();
System.out.println("Matrix a×B:");
format = format(rows * columns * a);
for (short i = 0; i < matrix_B.length; i++) {
for (short j = 0; j < matrix_B[i].length; j++) {
matrix_B[i][j] *= (short) (a);
System.out.printf(format, matrix_B[i][j]);
}
System.out.println("|");
}
System.out.println();
System.out.println("Averages of each row:");
for (short[] row : matrix_B) {
System.out.println(average(row));
}
}
}

58
Java/lab_3/lab_3.java Normal file
View File

@@ -0,0 +1,58 @@
package OOP.Java.lab_3;
public class lab_3 {
static int maxStrLength;
static String result;
public static void cSubUtil(StringBuilder stringbuilder, int leftBoundary, int rightBoundary) {
String string = stringbuilder.toString().toLowerCase().replaceAll("[^a-z]","");
// check if the indices lie in the range of string
// and also if it is palindrome
while (leftBoundary >= 0 && rightBoundary < string.length() && string.toLowerCase().charAt(leftBoundary) == string.toLowerCase().charAt(rightBoundary)) {
// expand the boundary
leftBoundary--;
rightBoundary++;
}
// if it's length is greater than maxLength update
// maxLength and res
if (rightBoundary - leftBoundary - 1 >= maxStrLength) {
result = string.substring(leftBoundary + 1, rightBoundary);
maxStrLength = rightBoundary - leftBoundary - 1;
}
return;
}
public static int longestPalSubstr(StringBuilder string)
{
result = "";
maxStrLength = 1;
// for every index in the string check palindromes
// starting from that index
for (int i = 0; i < string.length(); i++) {
// check for odd length palindromes
cSubUtil(string, i, i);
// check for even length palindromes
cSubUtil(string, i, i + 1);
}
System.out.println("Longest palindrome substring is: " + compareStrings(string));
return compareStrings(string).length();
}
public static String compareStrings(StringBuilder builder) {
for (int leftBoundary = 0; leftBoundary <= builder.length(); leftBoundary++) {
for (int rightBoundary = builder.length(); leftBoundary >= 0; rightBoundary--) {
if (result.equals(builder.substring(leftBoundary, rightBoundary).toString().toLowerCase().replaceAll("[^a-z]",""))) {
return builder.substring(leftBoundary, rightBoundary).toString();
}
}
}
return "";
}
public static void main(String[] args) {
StringBuilder stringToDetect = new StringBuilder("Eva, can I see bees in a cave?");
System.out.println("Initial string: " + stringToDetect.toString());
System.out.println("Length is: " + longestPalSubstr(stringToDetect));
}
}

16
Rust/lab_1/Cargo.lock generated Normal file
View File

@@ -0,0 +1,16 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "lab_1"
version = "0.1.0"
dependencies = [
"text_io",
]
[[package]]
name = "text_io"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5f0c8eb2ad70c12a6a69508f499b3051c924f4b1cfeae85bfad96e6bc5bba46"

16
Rust/lab_1/Cargo.toml Normal file
View File

@@ -0,0 +1,16 @@
[package]
name = "lab_1"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.release]
opt-level = 'z' # Optimize for size
lto = true # Enable link-time optimization
codegen-units = 1 # Reduce number of codegen units to increase optimizations
panic = 'abort' # Abort on panic
strip = true # Strip symbols from binary*
[dependencies]
text_io = "0.1.12"

22
Rust/lab_1/src/main.rs Normal file
View File

@@ -0,0 +1,22 @@
fn protected_read(variable_name: &str) -> i32 {
use text_io::try_read;
loop {
print!("Enter {}: ", variable_name);
let read_result: Result<i32, _> = try_read!();
match read_result {
Ok(read_integer) => return read_integer,
Err(_e) => println!("{} must be an integer!", variable_name.to_uppercase()),
}
}
}
fn main() {
let n: i32 = protected_read("n");
let m: i32 = protected_read("m");
let a: i32 = protected_read("a");
let b: i32 = protected_read("b");
let s: f32 = ((b + m) as f32 / 2f32) * ((m - b + 1) * (n - a + 1)) as f32;
println!("S = {}", s);
}

7
Rust/lab_2/Cargo.lock generated Normal file
View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "lab_2"
version = "0.1.0"

8
Rust/lab_2/Cargo.toml Normal file
View File

@@ -0,0 +1,8 @@
[package]
name = "lab_2"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

3
Rust/lab_2/src/main.rs Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
println!("Hello, world!");
}

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

Binary file not shown.

View File

@@ -1,21 +0,0 @@
public class Main {
public static void main(String[] args) {
float s = 0.0f, a = 2.0f, b = 1.0f, m = 6.0f, n = 4.0f;
int c = 1;
for (float i = a; i <= m; i++) {
// Перевірка ділення на 0.
if (i == -1) {
System.out.println("Помилка: ділення на нуль не можливе.");
return;
}
for (float j = b; j <= n; j++) {
s += (i + j) / (i + c);
}
}
System.out.println("S = " + s);
}
}

Binary file not shown.

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

Binary file not shown.

View File

@@ -1,59 +0,0 @@
public class Main {
public static void main(String[] args) {
// Створення матриць.
char[][] a = {
{12, 4, 8, 11},
{16, 9, 3, 13},
{7, 11, 16, 15}
};
char[][] b = {
{15, 12, 4, 5},
{19, 1, 3, 11},
{2, 11, 6, 10}
};
System.out.println("Матриця A: ");
for (char[] i : a) {
for (char j : i) {
/* При виведенні елементів ми додаємо пробіли на кінці
цілого числа (%-4d) задля легшого читання матриці.
*/
System.out.printf("%-4d", (int) j);
}
System.out.println();
}
System.out.println("\nМатриця B: ");
for (char[] i : b) {
for (char j : i) {
System.out.printf("%-4d", (int) j);
}
System.out.println();
}
// Перевірка на те, чи є матриці однакових форм.
if (a[0].length != b[0].length || a.length != b.length) {
System.out.println("Матриці А і В мають різні форми.");
} else {
int[][] c = new int[a.length][a[0].length];
float sum = 0;
System.out.println("\nМатриця С: ");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
c[i][j] = (byte) a[i][j] ^ (byte) b[i][j];
sum += c[i][j];
System.out.printf("%-4d", c[i][j]);
}
System.out.println();
}
float average = sum / (c.length * c[0].length);
System.out.printf("\nСереднє значення матриці С: %.3f", average);
}
}
}

Binary file not shown.

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

Binary file not shown.

View File

@@ -1,54 +0,0 @@
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuffer text = new StringBuffer(scanner.nextLine());
String str_text = text.toString();
// Заміна ? й ! на .
str_text = str_text.replaceAll("[?!]", ".");
// Очищення від спеціальних символів.
str_text = str_text.replaceAll("\"", "");
str_text = str_text.replaceAll("-", "");
str_text = str_text.replaceAll("[,':;^*&%$#@]", "");
// Створення масиву з речень.
String[] spl_text = str_text.split("\\.");
// Перевірка на кількість речень.
if (spl_text.length == 0 || spl_text.length == 1) {
System.out.println("Не вдалося виконати дію з рядками (було введено одне речення або взагалі нічого)");
return;
}
System.out.println("Слова першого речення, яких немає у жодному з наступних:");
for (String st : spl_text[0].split(" ")) {
int index = 0;
for (int i = 1; i < spl_text.length; i++) {
// Усунення кейсу з регістром, усунення пробілів.
if (Arrays.asList(spl_text[i].toLowerCase().trim().split(" ")).contains(st.trim().toLowerCase())) {
index = 1;
break;
}
}
// Перевірка на те, чи було дане слово хоча б в одному реченні.
if (index == 0) {
System.out.println(st.trim().toLowerCase());
}
}
}
}
/* [Input]
"У молодості я взяв собі за правило не пити ні краплі спиртного до обіду. Тепер, коли я вже немолодий, я тримаюся правила не пити ні краплі спиртного до сніданку". - Вінстон Черчилль
[Output]
у
молодості
взяв
собі
за
правило
обіду
*/

Binary file not shown.

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -1,40 +0,0 @@
package lab4;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Створення об'єктів класу Student.
Student First = new Student("Михайло", "Гордун", 21, "ІПСА", true);
Student Second = new Student("Дмитро", "Шарій", 19, "ТЕФ", false);
Student Third = new Student("Аліна", "Шарій", 18, "ЕФ", false);
Student Fourth = new Student("Назар", "Лоленко", 17, "ФІОТ", true);
Student Fifth = new Student("Олександра", "Зеленська", 18, "ФМВ", true);
// Створення масиву об'єктів класу Student.
Student[] ObjArray = new Student[] {First, Second, Third, Fourth, Fifth};
// Сортування по алфавіту (прізвище ім'я).
Arrays.sort(ObjArray, new Sorting.SortByAlphabet());
System.out.println("\nСортування за алфавітом (зростання):");
for (Student Student : ObjArray) {
System.out.println(Student.lastName + " " + Student.firstName);
}
/* Сортування по віці (спадання).
Масив сортує масив по зростанню, але в циклі ітерація
проходить навпаки, тим самим виводячи елементи з кінця
до початку.
*/
Arrays.sort(ObjArray, new Sorting.SortByAge());
System.out.println("\nСортування за віком (спадання):");
for (int i = ObjArray.length-1; i >= 0; i--) {
System.out.print(ObjArray[i].lastName + " ");
System.out.print(ObjArray[i].firstName);
System.out.println(", вік: " + ObjArray[i].age);
}
}
}

View File

@@ -1,52 +0,0 @@
package lab4;
import java.util.Comparator;
public class Sorting {
// Непорушний клас, створений на основі абстратного класу Comparator.
public static class SortByAlphabet implements Comparator<Student> {
/* Реалізація методу compare().
Метод compare(Object o1, Object 02) є одним із абстрактних методів
класу Comparator. Нам потрібно або зробити наш клас абстактним, або
реалізувати даний метод. Якщо ж оголосити клас SortByAlphabet
абстрактним, ми не зможемо створити на основі його об'єкт, тому
вибір очевидний - реалізація методу.
*/
@Override
public int compare(Student st1, Student st2) {
/* Якщо в нас буде 2 однакових прізвища на порівняння, нам потрібно
порівнювати імена аби сортування по алфавіту було правильним.
*/
if (st1.lastName.compareTo(st2.lastName) == 0) {
return st1.firstName.compareTo(st2.firstName);
} else {
return st1.lastName.compareTo(st2.lastName);
}
}
}
// Непорушний клас, створений на основі абстратного класу Comparator.
public static class SortByAge implements Comparator<Student> {
// Аналогічно тут, реалізуємо метод compare().
@Override
public int compare(Student st1, Student st2) {
/* Метод compareTo() приймає лише дані типу String, тому
ми перетворюємо вік з int в String. Звісно ж це може привести
до неточності. Числа будуть порівнюватись спочатку по перших
цифрах, потім по других і тд. Якщо в нас буде, наприклад вік
107 і 18 на порівнянні, прогрма порахує, що 18 > 107 по
порядку. Тут цим знехтується, адже я сумніваюсь що існують
студенти яким >100 років.
*/
String age1 = Integer.toString(st1.age);
String age2 = Integer.toString(st2.age);
return age1.compareTo(age2);
}
}
}

View File

@@ -1,44 +0,0 @@
package lab4;
public class Student {
// Створення полів класу.
public String firstName;
public String lastName;
public int age;
private String faculty;
private boolean hasStipend;
// Конструктор класу.
public Student(String fn, String ln, int age, String fac, boolean wealth) {
setValues(fn, ln, age, fac, wealth);
getValues();
}
/* Метод, який нічого не повертає.
Визначає поля класу.
*/
private void setValues(String fn, String ln, int age, String fac, boolean wealth) {
this.firstName = fn;
this.lastName = ln;
this.age = age;
this.faculty = fac;
this.hasStipend = wealth;
}
/* Метод, який нічого не повертає.
Виводить значення полів.
*/
private void getValues() {
System.out.println("Прізвище та ім'я: " + this.lastName + " " + this.firstName);
System.out.println("Вік: " + this.age);
System.out.println("Факультет: " + this.faculty);
System.out.print("Наявність стипендії: ");
if (this.hasStipend)
System.out.println("є");
else
System.out.println("немає");
System.out.println("~".repeat(40));
}
}

Binary file not shown.

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -1,5 +0,0 @@
package lab5;
public record Letter(char value) {
}

View File

@@ -1,38 +0,0 @@
package lab5;
import java.util.*;
public class Main {
public static void main(String[] args) {
String inputText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tempor dictum velit, vitae sollicitudin mauris facilisis et. Praesent mi odio, pretium eget sem ac, ultricies eleifend elit. Maecenas vulputate efficitur risus, a ornare lorem sollicitudin vitae. Pellentesque rhoncus posuere risus eu placerat. Maecenas luctus felis ac interdum sodales. Quisque nec est lectus.";
// Створений Text об'єкт
Text text = new Text(inputText);
// Пошук у першому реченні слів, яких немає в наступних реченнях
List<String> result = findUniqueWords(text);
System.out.println("Unique words in the first sentence: " + result);
}
public static List<String> findUniqueWords(Text text) {
if (text.getSentences().isEmpty()) {
throw new IllegalArgumentException("Text must contain at least one sentence.");
}
Sentence firstSentence = text.getSentences().get(0);
List<String> wordsInFirstSentence = firstSentence.getStringWords();
Set<String> uniqueWords = new HashSet<>(wordsInFirstSentence);
for (int i = 1; i < text.getSentences().size(); i++) {
Sentence sentence = text.getSentences().get(i);
List<String> wordsInCurrentSentence = sentence.getStringWords();
wordsInCurrentSentence.forEach(uniqueWords::remove);
}
return new ArrayList<>(uniqueWords);
}
}

View File

@@ -1,5 +0,0 @@
package lab5;
public record Punctuation(char value) {
}

View File

@@ -1,62 +0,0 @@
package lab5;
import java.util.ArrayList;
import java.util.List;
public class Sentence {
private final List<Object> wordsAndPunctuations;
public Sentence(String stringSentence) {
List<Object> wordsAndPunctuations = new ArrayList<>();
StringBuilder word = new StringBuilder();
for (int i = 0; i < stringSentence.length(); i++) {
char ch = stringSentence.charAt(i);
if (Character.isLetterOrDigit(ch)) {
word.append(ch);
} else if (Character.isWhitespace(ch)) {
if (word.length() > 0) {
wordsAndPunctuations.add(new Word(word.toString()));
word.setLength(0);
}
} else if (String.valueOf(ch).matches(".*\\p{Punct}.*")) {
if (word.length() > 0) {
wordsAndPunctuations.add(new Word(word.toString()));
word.setLength(0);
}
wordsAndPunctuations.add(new Punctuation(ch));
}
}
if (word.length() > 0) {
wordsAndPunctuations.add(new Word(word.toString()));
}
this.wordsAndPunctuations = wordsAndPunctuations;
}
public List<Object> getWordsAndPunctuations() {
return wordsAndPunctuations;
}
public List<Word> extractWords() {
List<Word> words = new ArrayList<>();
for (Object element : getWordsAndPunctuations()) {
if (element instanceof Word) {
words.add((Word) element);
}
}
return words;
}
public List<String> getStringWords() {
List<String> wordStrings = new ArrayList<>();
for (Word word : extractWords()) {
wordStrings.add(word.getStringWord());
}
return wordStrings;
}
}

View File

@@ -1,21 +0,0 @@
package lab5;
import java.util.ArrayList;
import java.util.List;
public class Text {
private final List<Sentence> sentences;
public Text(String stringText) {
this.sentences = new ArrayList<>();
String[] splitText = stringText.split("(?<=[!.?])\\s*");
for (String sentence : splitText) {
getSentences().add(new Sentence(sentence));
}
}
public List<Sentence> getSentences() {
return sentences;
}
}

View File

@@ -1,28 +0,0 @@
package lab5;
import java.util.ArrayList;
import java.util.List;
public class Word {
private final String stringWord;
private final List<Letter> letters;
public Word(String stringWord) {
List<Letter> letters = new ArrayList<>();
char[] chars = stringWord.toCharArray();
for (char c : chars) {
letters.add(new Letter(c));
}
this.letters = letters;
this.stringWord = stringWord;
}
public List<Letter> getLetters() {
return letters;
}
public String getStringWord() {
return stringWord;
}
}

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -1,17 +0,0 @@
package lab6;
public class Bmw extends Car {
public String mark = "BMW";
public Bmw(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
super(_model, speed, price, year, fuel, engineCapacity, country);
}
@Override
public void printValues() {
System.out.println("Марка: BMW");
super.printValues();
}
}

View File

@@ -1,40 +0,0 @@
package lab6;
import java.util.Comparator;
public class Car {
protected String _model;
protected float speed;
protected int price;
protected int year;
protected float fuel;
protected float engineCapacity;
protected String country;
public Car(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
setValues(_model, speed, price, year, fuel, engineCapacity, country);
printValues();
}
public void setValues(String _m, float s, int p, int y, float f, float e, String c) {
this._model = _m;
this.speed = s;
this.price = p;
this.year = y;
this.fuel = f;
this.engineCapacity = e;
this.country = c;
}
public void printValues() {
System.out.println("Модель: " + _model + " " + year);
System.out.println("Максимальна швидкість: " + speed + "км/год");
System.out.println("Ціна: " + price + "$");
System.out.println("Витрати палива: " + fuel + "л/100км");
System.out.println("Об'єм двигуна: " + engineCapacity);
System.out.println("Країна-виробник: " + country);
System.out.println("~".repeat(40));
}
}

View File

@@ -1,17 +0,0 @@
package lab6;
public class Ford extends Car {
public String mark = "Ford";
public Ford(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
super(_model, speed, price, year, fuel, engineCapacity, country);
}
@Override
public void printValues() {
System.out.println("Марка: Ford");
super.printValues();
}
}

View File

@@ -1,17 +0,0 @@
package lab6;
public class Lexus extends Car {
public String mark = "Lexus";
public Lexus(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
super(_model, speed, price, year, fuel, engineCapacity, country);
}
@Override
public void printValues() {
System.out.println("Марка: Lexus\nМатеринська компанія: Toyota");
super.printValues();
}
}

View File

@@ -1,55 +0,0 @@
package lab6;
/*
Номер заліковї книжки - 2518.
Завдання:
9)Визначити ієрархію легкових автомобілів. Створити таксопарк.
Порахувати вартість автопарку. Провести сортування автомобілів
парку за витратами палива. Знайти автомобіль у компанії, що
відповідає заданому діапазону швидкості автомобіля.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println(" ".repeat(15) + "Таксопарк" + " ".repeat(15));
System.out.println("~".repeat(40));
Volkswagen Car1 = new Volkswagen("Golf 4", 224, 5000, 2001, 6.8f, 1.6f, "Німеччина");
Volkswagen Car2 = new Volkswagen("Passat", 240, 15000, 2007, 7.0f, 2.0f, "Німеччина");
Toyota Car3 = new Toyota("Prius", 231, 12500, 2014, 4.3f, 1.8f, "Японія");
Peguot Car4 = new Peguot("308", 220, 12000, 2007, 6.1f, 1.6f, "Франція");
Lexus Car5 = new Lexus("LS", 250, 80000, 2022, 10.9f, 3.5f, "Японія");
Skoda Car6 = new Skoda("Octavia", 220, 25000, 2022, 6.2f, 1.5f, "Чехія");
Ford Car7 = new Ford("Focus", 242, 7800, 2014, 6.9f, 2.0f, "США");
Bmw Car8 = new Bmw("5-Series", 250, 50000, 2018, 8.3f, 3.0f, "Німеччина");
Car[] CarList = new Car[] {Car1, Car2, Car3, Car4, Car5, Car6, Car7, Car8};
/*
Використовується лямбда функція, щоб описати компаратор в Arrays.sort().
*/
java.util.Arrays.sort(CarList, (a, b) -> Float.compare(a.fuel, b.fuel));
System.out.println("Сортування автомобілів за витратами палива:");
for (Car Car : CarList) {
System.out.println(Car._model + ": " + Car.fuel + "л/100км");
}
Scanner scanner = new Scanner(System.in);
System.out.print("\nВведіть діапазон швидкості автомобіля:\ід ");
float speed_down = scanner.nextFloat();
System.out.print("до ");
float speed_up = scanner.nextFloat();
System.out.println("Автомобілі із заданою швидкістю:");
for (Car Car : CarList) {
if ((Car.speed >= speed_down) && (Car.speed <= speed_up)) {
System.out.println(Car._model + ": " + Car.speed + " км/год");
}
}
}
}

View File

@@ -1,17 +0,0 @@
package lab6;
public class Peguot extends Car {
public String mark = "Peguot";
public Peguot(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
super(_model, speed, price, year, fuel, engineCapacity, country);
}
@Override
public void printValues() {
System.out.println("Марка: Peguot");
super.printValues();
}
}

View File

@@ -1,17 +0,0 @@
package lab6;
public class Skoda extends Car {
public String mark = "Skoda";
public Skoda(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
super(_model, speed, price, year, fuel, engineCapacity, country);
}
@Override
public void printValues() {
System.out.println("Марка: Skoda\nМатеринська компанія: Volkswagen");
super.printValues();
}
}

View File

@@ -1,17 +0,0 @@
package lab6;
public class Toyota extends Car {
public String mark = "Toyota";
public Toyota(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
super(_model, speed, price, year, fuel, engineCapacity, country);
}
@Override
public void printValues() {
System.out.println("Марка: Toyota");
super.printValues();
}
}

View File

@@ -1,17 +0,0 @@
package lab6;
public class Volkswagen extends Car {
public String mark = "Volkswagen";
public Volkswagen(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
super(_model, speed, price, year, fuel, engineCapacity, country);
}
@Override
public void printValues() {
System.out.println("Марка: Volkswagen");
super.printValues();
}
}

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -1,42 +0,0 @@
package lab7;
public class Car {
protected String mark;
protected String model;
protected int price;
protected int year;
protected float fuel;
public Car(String mark, String model, int price, int year, float fuel) {
setValues(mark, model, price, year, fuel);
}
// Цей конструктор був створений окремо для класу ElectricCar
public Car(String mark, String model, int price, int year) {
setValues(mark, model, price, year);
}
public void setValues(String mark, String model, int price, int year, float fuel) {
this.mark = mark;
this.model = model;
this.price = price;
this.year = year;
this.fuel = fuel;
}
public void setValues(String mark, String model, int price, int year) {
this.mark = mark;
this.model = model;
this.price = price;
this.year = year;
}
public void printValues() {
System.out.println("Марка: " + mark);
System.out.println("Модель: " + model + " " + year);
System.out.println("Ціна: " + price + "$");
System.out.println("Витрати палива: " + fuel + "л/100км");
}
}

View File

@@ -1,137 +0,0 @@
package lab7;
import java.util.*;
public class CarCollection<T extends Car> implements List<T> {
private final LinkedList<T> carList;
public CarCollection() {
carList = new LinkedList<>();
}
public CarCollection(T car) {
carList = new LinkedList<>();
carList.add(car);
}
public CarCollection(Collection<? extends T> c) {
carList = new LinkedList<>(c);
}
// Реалізація методів List
@Override
public int size() {
return carList.size();
}
@Override
public boolean isEmpty() {
return carList.isEmpty();
}
@Override
public boolean contains(Object o) {
return carList.contains(o);
}
@Override
public Iterator<T> iterator() {
return carList.iterator();
}
@Override
public Object[] toArray() {
return carList.toArray();
}
@Override
public <T1> T1[] toArray(T1[] a) {
return carList.toArray(a);
}
@Override
public boolean add(T t) {
return carList.add(t);
}
@Override
public boolean remove(Object o) {
return carList.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return carList.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends T> c) {
return carList.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
return carList.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c) {
return carList.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return carList.retainAll(c);
}
@Override
public void clear() {
carList.clear();
}
@Override
public T get(int index) {
return carList.get(index);
}
@Override
public T set(int index, T element) {
return carList.set(index, element);
}
@Override
public void add(int index, T element) {
carList.add(index, element);
}
@Override
public T remove(int index) {
return carList.remove(index);
}
@Override
public int indexOf(Object o) {
return carList.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return carList.lastIndexOf(o);
}
@Override
public ListIterator<T> listIterator() {
return carList.listIterator();
}
@Override
public ListIterator<T> listIterator(int index) {
return carList.listIterator(index);
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
return carList.subList(fromIndex, toIndex);
}
}

View File

@@ -1,29 +0,0 @@
package lab7;
public class CombatsCar extends Car {
private final int crew;
private final float weight;
private final String country;
public CombatsCar(String mark, String model, int price, int year, float fuel, int crew, float weight, String country) {
super(mark, model, price, year, fuel);
this.crew = crew;
this.weight = weight;
this.country = country;
}
public String getCountry() {
return country;
}
public void printValues() {
super.printValues();
System.out.println("--- Особливості бойової машини ---");
System.out.println("Екіпаж: " + crew + " людей");
System.out.println("Бойова маса: " + weight + "т");
System.out.println("Країна-виробник: " + country);
}
}

View File

@@ -1,25 +0,0 @@
package lab7;
public class ElectricCar extends Car {
private final float electricity;
private final float chargingSpeed;
public ElectricCar(String mark, String model, int price, int year, float electricity, int chargingSpeed) {
super(mark, model, price, year);
this.electricity = electricity;
this.chargingSpeed = chargingSpeed;
}
public float getElectricity() {
return electricity;
}
public void printValues() {
super.printValues();
System.out.println("-Особливості електрокару-");
System.out.println("Споживання електроенергії: " + electricity + " кВт·год/100км");
System.out.println("Швидкість зарядки (з 0% до 100%): " + chargingSpeed + " хв");
}
}

View File

@@ -1,73 +0,0 @@
package lab7;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Використання пустого конструктора CarCollection
CarCollection<SportsCar> sportsCars = new CarCollection<>();
sportsCars.add(new SportsCar("Ferrari", "458 Italia", 230000, 2015, 9.8f, 562, 202, 4.5f));
sportsCars.add(new SportsCar("Lamborghini", "Huracan", 260000, 2020, 9.5f, 640, 211, 5.2f));
sportsCars.add(new SportsCar("Porsche", "911", 150000, 2018, 14.3f, 450, 191, 3.0f));
sportsCars.add(new SportsCar("McLaren", "570S", 200000, 2017, 11.2f, 562, 204, 3.8f));
sportsCars.add(new SportsCar("Aston Martin", "Vantage", 150000, 2021, 12.3f, 503, 195, 4.0f));
// Сортування спорткарів за ціною
System.out.println("~~~~~ Відсортовані спорткари за ціною ~~~~~");
sportsCars.sort(Comparator.comparingInt(SportsCar::getPrice));
for (int i = sportsCars.size() - 1; i >= 0; i--) {
sportsCars.get(i).printValues();
System.out.println();
}
// Використання конструктора CarCollection з передаванням в його лише один об'єкт
CarCollection<CombatsCar> combatsCars = new CarCollection<>(new CombatsCar("Humvee", "M1114", 220000, 1995, 6.5f, 4, 5.5f, "США"));
combatsCars.add(new CombatsCar("Puma", "IFV", 3500000, 2010, 10.7f, 6, 31f, "Німеччина"));
combatsCars.add(new CombatsCar("Warrior", "IFV", 4500000, 1988, 12.4f, 3, 29f, "Великобританія"));
combatsCars.add(new CombatsCar("ZBD", "05", 1200000, 2011, 9.4f, 4, 25f, "Китай"));
combatsCars.add(new CombatsCar("VBCI", "IFV", 5000000, 2008, 10.7f, 8, 32f, "Франція"));
// Пошук бойової машини за країною-виробником
Scanner scanner = new Scanner(System.in);
System.out.print("Введіть країну-виробницю бойової машини: ");
String userCountry = scanner.nextLine();
System.out.println("Результати пошуку:\n");
for (CombatsCar car : combatsCars) {
if (car.getCountry().equals(userCountry)) {
car.printValues();
}
}
ArrayList<ElectricCar> electricCarsList = new ArrayList<>();
electricCarsList.add(new ElectricCar("Tesla", "Model S", 80000, 2022, 21.5f, 45));
electricCarsList.add(new ElectricCar("Chevrolet", "Bolt", 35000, 2021, 28.0f, 60));
electricCarsList.add(new ElectricCar("Nissan", "Leaf", 32000, 2021, 24.0f, 40));
electricCarsList.add(new ElectricCar("BMW", "i3", 45000, 2021, 19.5f, 30));
electricCarsList.add(new ElectricCar("Hyundai", "Kona", 42000, 2022, 22.0f, 50));
// Використання конструктора CarCollection з передаванням в його колекцію об'єктів
CarCollection<ElectricCar> electricCars = new CarCollection<>(electricCarsList);
// Пошук автомобіля по діапазону споживання електроенергії
System.out.println("\nВведіть діапазон споживання електроенергії (кВт·год/100км):");
System.out.print("від ");
float electricityLowerLimit = scanner.nextFloat();
System.out.print("до ");
float electricityUpperLimit = scanner.nextFloat();
System.out.println("Результати пошуку:\n");
for (ElectricCar car : electricCars) {
if (car.getElectricity() < electricityUpperLimit & car.getElectricity() > electricityLowerLimit) {
car.printValues();
}
}
}
}

View File

@@ -1,28 +0,0 @@
package lab7;
public class SportsCar extends Car {
private final int power;
private final float speed;
private final float engineCapacity;
public SportsCar(String mark, String model, int price, int year, float fuel, int power, float speed, float engineCapacity) {
super(mark, model, price, year, fuel);
this.power = power;
this.speed = speed;
this.engineCapacity = engineCapacity;
}
public int getPrice() {
return price;
}
public void printValues() {
super.printValues();
System.out.println("-Особливості спорткару-");
System.out.println("Потужість: " + power + " кінських сил");
System.out.println("Максимальна швидкість: " + speed + " км/год");
System.out.println("Об'єм двигуна: " + engineCapacity + "л");
}
}