1
0
This commit is contained in:
Rokas Puzonas 2022-10-26 21:19:38 +03:00
parent e3445df230
commit 057b52e3bd
131 changed files with 11103 additions and 0 deletions

3
LD1_2/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

6
LD1_2/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_18" default="true" project-jdk-name="11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
LD1_2/.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/LD1_2.iml" filepath="$PROJECT_DIR$/LD1_2.iml" />
</modules>
</component>
</project>

124
LD1_2/.idea/uiDesigner.xml generated Normal file
View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

11
LD1_2/LD1_2.iml Normal file
View File

@ -0,0 +1,11 @@
<?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>

4
LD1_2/U24a.txt Normal file
View File

@ -0,0 +1,4 @@
0, Atsuktuvas, 0.99
1, Varztas, 0.05
2, Laidas, 2.00
3, Plaktukas, 2.99

9
LD1_2/U24b.txt Normal file
View File

@ -0,0 +1,9 @@
Petraitis, Petras, 0, 10
Jonaitis, Jonas, 1, 20
Jonaitis, Jonas, 1, 20
Jonaitis, Jonas, 1, 20
Onaite, Ona, 2, 200
Jonaitis, Brolis, 1, 100
Jonaitis, Jonas, 1, 20
Jonaitis, Jonas, 1, 20
Onaite, Ona, 0, 20

View File

@ -0,0 +1,31 @@
package com.company;
import models.Order;
import models.Product;
import utils.InOutUtils;
import utils.LinkedList;
import utils.TaskUtils;
public class Main {
public static void main(String[] args) {
LinkedList<Order> orders = new LinkedList<Order>();
LinkedList<Product> products = new LinkedList<Product>();
InOutUtils.readProducts("U24a.txt", products);
InOutUtils.readOrders("U24b.txt", orders);
int n = 1000;
float k = 10.0f;
var mostPopularProductIds = TaskUtils.FindMostPopularProducts(orders);
var mostPopularProducts = TaskUtils.FindByID(products, mostPopularProductIds);
var filteredProducts = TaskUtils.FilterByQuantitySoldAndPrice(products, orders, n, k);
var customersWithSingleProduct = TaskUtils.FindCustomerWithSingleProduct(orders);
InOutUtils.printProducts(products, "Įtaisai");
InOutUtils.printOrders(orders, "Pirkėjai");
InOutUtils.printMostPopularProducts(orders, mostPopularProducts, "Populiariausi įtaisai");
InOutUtils.printOrdersWithPrices(customersWithSingleProduct, products, "Vienos rūšies pirkėjai");
InOutUtils.printProducts(filteredProducts, String.format("Atrinkti įtaisai (n=%d, k=%.2f)", n, k));
}
}

View File

@ -0,0 +1,44 @@
package models;
public class Order implements Comparable<Order> {
public String customerSurname;
public String customerName;
public String productID;
public int productAmount;
public Order(String customerSurname, String customerName, String productID, int productAmount) {
this.customerSurname = customerSurname;
this.customerName = customerName;
this.productID = productID;
this.productAmount = productAmount;
}
@Override
public int compareTo(Order o) {
if (productAmount > o.productAmount) {
return 1;
} else if (productAmount == o.productAmount) {
int surnameCompare = customerSurname.compareTo(o.customerSurname);
if (surnameCompare < 0) {
return 1;
} else if (surnameCompare == 0 && customerName.compareTo(o.customerName) < 0) {
return 1;
}
}
return equals(o) ? 0 : -1;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Order))
return false;
Order order = (Order)o;
return customerName.equals(order.customerName) &&
customerSurname.equals(order.customerSurname) &&
productAmount == order.productAmount &&
productID.equals(order.productID);
}
}

View File

@ -0,0 +1,29 @@
package models;
public class Product implements Comparable<Product> {
public String ID;
public String name;
public float price;
public Product(String ID, String name, float price) {
this.ID = ID;
this.name = name;
this.price = price;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Product))
return false;
Product product = (Product)o;
return ID.equals(product.ID) &&
name.equals(product.name) &&
price == product.price;
}
@Override
public int compareTo(Product o) {
return ID.compareTo(o.ID);
}
}

View File

@ -0,0 +1,139 @@
package utils;
import models.Order;
import models.Product;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class InOutUtils {
public static void readOrders(String filePath, List<Order> outputData) {
FileInputStream fileStream = null;
Scanner scanner = null;
try {
fileStream = new FileInputStream(filePath);
scanner = new Scanner(fileStream, StandardCharsets.UTF_8);
while (scanner.hasNextLine()) {
String[] lines = scanner.nextLine().split(",");
String customerSurname = lines[0].trim();
String customerName = lines[1].trim();
String productID = lines[2].trim();
int productAmount = Integer.parseInt(lines[3].trim());
outputData.add(new Order(customerSurname, customerName, productID, productAmount));
}
fileStream.close();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (scanner != null) {
scanner.close();
}
}
}
public static void readProducts(String filePath, List<Product> outputData) {
FileInputStream fileStream = null;
Scanner scanner = null;
try {
fileStream = new FileInputStream(filePath);
scanner = new Scanner(fileStream, StandardCharsets.UTF_8);
while (scanner.hasNextLine()) {
String[] lines = scanner.nextLine().split(",");
String ID = lines[0].trim();
String name = lines[1].trim();
float price = Float.parseFloat(lines[2].trim());
outputData.add(new Product(ID, name, price));
}
fileStream.close();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (scanner != null) {
scanner.close();
}
}
}
public static void printOrders(LinkedList<Order> orders, String header)
{
if (orders.get(0) == null) {
System.out.println("Tuščia");
return;
}
System.out.println("-".repeat(49));
System.out.printf("| %-45s |%n", header);
System.out.println("-".repeat(49));
System.out.printf("| %-10s | %-6s | %7s | %13s |%n", "Pavardė", "Vardas", "Įtaisas", "Įtaiso kiekis");
System.out.println("-".repeat(49));
for (Order e : orders) {
System.out.printf("| %-10s | %-6s | %7s | %13d |%n", e.customerSurname, e.customerName, e.productID, e.productAmount);
}
System.out.println("-".repeat(49));
}
public static void printProducts(LinkedList<Product> products, String header)
{
if (products.get(0) == null) {
System.out.println("Tuščia");
return;
}
System.out.println("-".repeat(35));
System.out.printf("| %-31s |%n", header);
System.out.println("-".repeat(35));
System.out.printf("| %-2s | %-18s | %5s |%n", "ID", "Vardas", "Kaina");
System.out.println("-".repeat(35));
for (Product e : products)
{
System.out.printf("| %-2s | %-18s | %5.2f |%n", e.ID, e.name, e.price);
}
System.out.println("-".repeat(35));
}
public static void printOrdersWithPrices(LinkedList<Order> orders, LinkedList<Product> products, String header)
{
if (orders.get(0) == null) {
System.out.println("Tuščia");
return;
}
System.out.println("-".repeat(53));
System.out.printf("| %-49s |%n", header);
System.out.println("-".repeat(53));
System.out.printf("| %-10s | %-6s | %13s | %11s |%n", "Pavardė", "Vardas", "Įtaiso kiekis", "Kaina, eur.");
System.out.println("-".repeat(53));
for (Order order : orders) {
Product product = TaskUtils.FindByID(products, order.productID);
System.out.printf("| %-10s | %-6s | %13s | %11.2f |%n", order.customerSurname, order.customerName, order.productAmount, order.productAmount * product.price);
}
System.out.println("-".repeat(53));
}
public static void printMostPopularProducts(LinkedList<Order> orders, LinkedList<Product> products, String header)
{
if (products.get(0) == null) {
System.out.println("Tuščia");
return;
}
System.out.println("-".repeat(62));
System.out.printf("| %-58s |%n", header);
System.out.println("-".repeat(62));
System.out.printf("| %-2s | %-10s | %19s | %18s |%n", "ID", "Vardas", "Įtaisų kiekis, vnt.", "Įtaisų kaina, eur.");
System.out.println("-".repeat(62));
for (Product e : products)
{
int sales = TaskUtils.CountProductSales(orders, e.ID);
System.out.printf("| %-2s | %-10s | %19d | %18.2f |%n", e.ID, e.name, sales, sales * e.price);
}
System.out.println("-".repeat(62));
}
}

View File

@ -0,0 +1,89 @@
package utils;
import java.util.Iterator;
/*
Realizuokite visus interfeiso metodus susietojo sarašo pagrindu.
Nesinaudokite java klase LinkedList<E>, visa logika meginkite parasyti patys.
Jeigu reikia, galima kurti papildomus metodus ir kintamuosius.
*/
public class LinkedList<T> implements List<T> {
private class Node {
public T value;
public Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public Node(T value) {
this.value = value;
}
}
Node head, tail;
@Override
public void add(T item) {
if (head == null) {
this.head = new Node(item);
this.tail = this.head;
} else {
Node d = new Node(item);
this.tail.next = d;
this.tail = d;
}
}
@Override
public T get(int index) {
Node current = this.head;
for (int i = 0; i < index && current != null; i++) {
current = current.next;
}
return current != null ? current.value : null;
}
@Override
public boolean remove(T item) {
Node prev = null;
Node current = this.head;
while (current != null) {
if (current.value.equals(item)) {
if (current.next == null) {
this.tail = prev;
prev.next = null;
} else if (prev == null) {
this.head = current.next;
} else {
prev.next = current.next;
}
return true;
}
prev = current;
current = current.next;
}
return false;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
public Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
T value = current.value;
current = current.next;
return value;
}
};
}
}

View File

@ -0,0 +1,7 @@
package utils;
public interface List<T> extends Iterable<T>{
public void add(T item); // add item to the end
public T get(int index); // get element by its place in list
public boolean remove(T item); // remove item, if item removed return true, else return false
}

View File

@ -0,0 +1,118 @@
package utils;
import models.Order;
import models.Product;
import java.util.HashMap;
public class TaskUtils {
public static LinkedList<String> FindMostPopularProducts(Iterable<Order> orders) {
HashMap<String, Integer> productSales = new HashMap<String, Integer>();
for (Order order : orders) {
if (!productSales.containsKey(order.productID)) {
productSales.put(order.productID, order.productAmount);
} else {
productSales.replace(order.productID, productSales.get(order.productID) + order.productAmount);
}
}
LinkedList<String> mostPopularProducts = new LinkedList<String>();
int mostPopularCount = 0;
for (String product : productSales.keySet()) {
int count = productSales.get(product);
if (count > mostPopularCount) {
mostPopularCount = count;
mostPopularProducts = new LinkedList<String>();
mostPopularProducts.add(product);
} else if (count == mostPopularCount) {
mostPopularProducts.add(product);
}
}
return mostPopularProducts;
}
public static int CountProductSales(Iterable<Order> orders, String product) {
int sales = 0;
for (Order order : orders) {
if (order.productID.equals(product)) {
sales += order.productAmount;
}
}
return sales;
}
public static Product FindByID(Iterable<Product> products, String id) {
for (Product product : products) {
if (product.ID.equals(id)) {
return product;
}
}
return null;
}
public static LinkedList<Product> FindByID(Iterable<Product> products, Iterable<String> ids) {
LinkedList<Product> foundProducts = new LinkedList<Product>();
for (String id : ids) {
foundProducts.add(FindByID(products, id));
}
return foundProducts;
}
public static LinkedList<Product> FilterByQuantitySoldAndPrice(Iterable<Product> products, Iterable<Order> orders, int minSold, float maxPrice) {
LinkedList<Product> filtered = new LinkedList<Product>();
for (Product product : products) {
if (product.price < maxPrice) {
int sold = CountProductSales(orders, product.ID);
if (sold >= minSold) {
filtered.add(product);
}
}
}
return filtered;
}
public static LinkedList<Order> MergeOrders(Iterable<Order> orders)
{
HashMap<String, Order> ordersByName = new HashMap<>();
for (Order order : orders)
{
var key = order.customerSurname + order.customerName + order.productID;
if (ordersByName.containsKey(key))
{
ordersByName.get(key).productAmount += order.productAmount;
} else
{
ordersByName.put(key, new Order(order.customerSurname, order.customerName, order.productID, order.productAmount));
}
}
LinkedList<Order> mergedOrders = new LinkedList<Order>();
for (Order order : ordersByName.values())
{
mergedOrders.add(order);
}
return mergedOrders;
}
public static LinkedList<Order> FindCustomerWithSingleProduct(Iterable<Order> orders) {
HashMap<String, LinkedList<Order>> ordersByCustomer = new HashMap<>();
for (Order order : MergeOrders(orders)) {
var key = order.customerName + order.customerSurname;
if (!ordersByCustomer.containsKey(key)) {
ordersByCustomer.put(key, new LinkedList<>());
}
ordersByCustomer.get(key).add(order);
}
LinkedList<Order> finalList = new LinkedList<Order>();
for (LinkedList<Order> customerOrders : ordersByCustomer.values())
{
if (customerOrders.get(1) == null)
{
finalList.add(customerOrders.get(0));
}
}
return finalList;
}
}

3
LD1_intro/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

1
LD1_intro/.idea/.name generated Normal file
View File

@ -0,0 +1 @@
LD1_intro.iml

1
LD1_intro/.idea/description.html generated Normal file
View File

@ -0,0 +1 @@
<html>Simple <b>Java</b> application that includes a class with <code>main()</code> method</html>

6
LD1_intro/.idea/encodings.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>

9
LD1_intro/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectKey">
<option name="state" value="project://e2804f05-5315-4fc6-a121-c522a6c26470" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
LD1_intro/.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/LD1_intro.iml" filepath="$PROJECT_DIR$/LD1_intro.iml" />
</modules>
</component>
</project>

3
LD1_intro/.idea/project-template.xml generated Normal file
View File

@ -0,0 +1,3 @@
<template>
<input-field default="com.company">IJ_BASE_PACKAGE</input-field>
</template>

124
LD1_intro/.idea/uiDesigner.xml generated Normal file
View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

11
LD1_intro/LD1_intro.iml Normal file
View File

@ -0,0 +1,11 @@
<?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

@ -0,0 +1,59 @@
package com.company;
import models.Student;
import utils.*;
public class Main {
public static void main(String[] args) {
String filePath = "students_data.txt";
Array<Student> students_arr = new Array<Student>();
DataReader.readFromFile(filePath, students_arr);
System.out.println("============Tests with array implementation============");
performTests(students_arr);
LinkedList<Student> students_llist = new LinkedList<Student>();
// Realizavus LinkedList klase ir atkomentavus turetume gauti tokius
// pacius rezultatus kaip ir klases Array atveju
DataReader.readFromFile(filePath, students_llist);
System.out.println("============Tests with linked list implementation============");
performTests(students_llist);
}
private static void performTests(List<Student> students) {
System.out.println("Initial students list:");
for(Student student : students){
System.out.println(student);
}
System.out.println(students.remove(new Student("Tomas", "Tomaitis", 22, "IF-7/1")));
System.out.println(students.remove(new Student("Jonas", "Jonaitis", 19, "IFF-9/3")));
System.out.println(students.remove(new Student("Vardenis", "Pavardenis", 99, "XX-XX")));
System.out.println("\nAfter removal:");
for(Student student : students){
System.out.println(student);
}
students.add(new Student("Ona", "Onaite", 20,"IFF-8/1"));
System.out.println("\nAfter addition at the end and insertion at the start:");
for(Student student : students){
System.out.println(student);
}
System.out.println("\nTesting get() method:");
for(int i = 0; i < 2; i++){
System.out.println(students.get(i));
}
}
}

View File

@ -0,0 +1,30 @@
package models;
public class Student {
String firstName;
String lastName;
int age;
String group;
public Student(){}
public Student(String firstName, String lastName, int age, String group){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.group = group;
}
@Override
public String toString(){
return String.format("%s %s age: %d group: %s", firstName, lastName, age, group);
}
@Override
public boolean equals(Object student) {
if (student == null)
return false;
return ((Student) student).firstName.equals(this.firstName) && ((Student) student).lastName.equals(this.lastName);
}
}

View File

@ -0,0 +1,44 @@
package utils;
import java.util.ArrayList;
import java.util.Iterator;
public class Array<T> implements List<T> {
public ArrayList<T> array;
public Array(){
array = new ArrayList<T>();
}
@Override
public void add(T item) {
array.add(item);
}
@Override
public T get(int index) {
return array.get(index);
}
@Override
public boolean remove(T item) {
return array.remove(item);
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < array.size() && array.get(currentIndex) != null;
}
@Override
public T next() {
return array.get(currentIndex++);
}
};
}
}

View File

@ -0,0 +1,32 @@
package utils;
import models.Student;
import java.io.FileInputStream;
import java.util.Scanner;
public class DataReader {
public static void readFromFile(String filePath, List outputData) {
FileInputStream fileStream = null;
Scanner scanner = null;
try {
fileStream = new FileInputStream(filePath);
scanner = new Scanner(fileStream, "UTF-8");
while (scanner.hasNextLine()) {
String[] lines = scanner.nextLine().split(";");
outputData.add(new Student(lines[0], lines[1], Integer.parseInt(lines[2]), lines[3]));
}
fileStream.close();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (scanner != null) {
scanner.close();
}
}
}
}

View File

@ -0,0 +1,89 @@
package utils;
import java.util.Iterator;
/*
Realizuokite visus interfeiso metodus susietojo sarašo pagrindu.
Nesinaudokite java klase LinkedList<E>, visa logika meginkite parasyti patys.
Jeigu reikia, galima kurti papildomus metodus ir kintamuosius.
*/
public class LinkedList<T> implements List<T> {
private class Node {
public T value;
public Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public Node(T value) {
this.value = value;
}
}
Node head, tail;
@Override
public void add(T item) {
if (head == null) {
this.head = new Node(item);
this.tail = this.head;
} else {
Node d = new Node(item);
this.tail.next = d;
this.tail = d;
}
}
@Override
public T get(int index) {
Node current = this.head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.value;
}
@Override
public boolean remove(T item) {
Node prev = null;
Node current = this.head;
while (current != null) {
if (current.value.equals(item)) {
if (current.next == null) {
this.tail = prev;
prev.next = null;
} else if (prev == null) {
this.head = current.next;
} else {
prev.next = current.next;
}
return true;
}
prev = current;
current = current.next;
}
return false;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
public Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
T value = current.value;
current = current.next;
return value;
}
};
}
}

View File

@ -0,0 +1,7 @@
package utils;
public interface List<T> extends Iterable<T>{
public void add(T item); // add item to the end
public T get(int index); // get element by its place in list
public boolean remove(T item); // remove item, if item removed return true, else return false
}

View File

@ -0,0 +1,3 @@
Tomas;Tomaitis;19;IFF-9/1
Giedrius;Giedraitis;18;IFF-9/1
Jonas;Jonaitis;20;IFF-8/3

3
Lab1b_BendriniaiSarasai/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1 @@
<html>Simple <b>Java</b> application that includes a class with <code>main()</code> method</html>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>

12
Lab1b_BendriniaiSarasai/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="ProjectKey">
<option name="state" value="project://e2804f05-5315-4fc6-a121-c522a6c26470" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Lab1b_BendriniaiSarasai.iml" filepath="$PROJECT_DIR$/Lab1b_BendriniaiSarasai.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,3 @@
<template>
<input-field default="com.company">IJ_BASE_PACKAGE</input-field>
</template>

View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

View File

@ -0,0 +1,22 @@
Renault Laguna 1997 50000 1700.0
Renault Megane 2001 20000 3500.0
Toyota Corolla 2001 20000 8500.8
Renault Laguna 2001 115900 7500.0
Renault Megane 1946 365100 9500.0
Honda Civic 2007 36400 8500.3
Ford Focus 2009 40000 36000.0
Ford Focus 2008 50000 34000.0
Ford Focus 2007 60000 32000.0
Ford Focus 2006 70000 30000.0
Ford Focus 2005 80000 28000.0
Ford Focus 2004 90000 26000.0
Ford Focus 2003 100000 24000.0
Ford Focus 2002 110000 22000.0
Ford Focus 2001 120000 20000.0
Ford Focus 2000 130000 18000.0
Ford Focus 1999 140000 16000.0
Ford Focus 1998 150000 14000.0
Ford Mondeo 2009 37000 36000.0
Fiat Bravo 2008 27000 36000.0
Ford Fiesta 2009 37000 16000.0
Audi A6 2006 87000 36000.0

View File

@ -0,0 +1,11 @@
<?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

@ -0,0 +1,171 @@
/** @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra, 2014 09 23
*
* Tai yra demonstracinė automobilio klasė (jos objektai dedami į LinkedList),
* kuri realizuoja interfeisą Parsable<T>.
****************************************************************************/
package com.ktu;
import util.Ks;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Scanner;
import util.Parsable;
public class Car implements Parsable<Car> {
// bendri duomenys visiems automobiliams (visai klasei)
final static private int minYear = 1994;
final static private double minPrice = 200.0;
final static private double maxPrice = 120_000.0;
// kiekvieno automobilio individualūs duomenys
private String make;
private String model;
private int year;
private int mileage;
private double price;
public Car() {
}
public Car(String make, String model,
int year, int mileage, double price) {
this.make = make;
this.model = model;
this.year = year;
this.mileage = mileage;
this.price = price;
}
public Car(String data) {
parse(data);
}
@Override
public final void parse(String data) {
try { // ed - tai elementarūs duomenys, atskirti tarpais
Scanner ed = new Scanner(data);
make = ed.next();
model = ed.next();
year = ed.nextInt();
mileage = ed.nextInt();
setPrice(ed.nextDouble());
} catch (InputMismatchException e) {
Ks.ern("Blogas duomenų formatas apie auto -> " + data);
} catch (NoSuchElementException e) {
Ks.ern("Trūksta duomenų apie auto -> " + data);
}
}
public String validate() {
String error = "";
int currentYear = LocalDate.now().getYear();
if (year < minYear || year > currentYear) {
error = "Netinkami gamybos metai, turi būti ["
+ minYear + ":" + currentYear + "]";
}
if (price < minPrice || price > maxPrice) {
error += " Kaina už leistinų ribų [" + minPrice
+ ":" + maxPrice + "]";
}
return error;
}
@Override
public String toString() { // surenkama visa reikalinga informacija
return String.format("%-8s %-8s %4d %7d %8.1f %s",
make, model, year, mileage, price, validate());
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public int getMileage() {
return mileage;
}
public double getPrice() {
return price;
}
// keisti bus galima tik kainą - kiti parametrai pastovūs
public void setPrice(double price) {
this.price = price;
}
@Override
public int compareTo(Car otherCar) {
// lyginame pagal svarbiausią požymį - kainą
double otherPrice = otherCar.getPrice();
if (price < otherPrice) {
return -1;
}
if (price > otherPrice) {
return +1;
}
return 0;
}
// pradžioje pagal markes, o po to pagal modelius
public final static Comparator<Car> byMakeAndModel
= Comparator.comparing(Car::getMake).thenComparing(Car::getModel);
public final static Comparator<Car> byPrice = (car1, car2) -> {
double price1 = car1.getPrice();
double price2 = car2.getPrice();
// didėjanti tvarka, pradedant nuo mažiausios
if (price1 < price2) {
return -1;
}
if (price1 > price2) {
return 1;
}
return 0;
};
public final static Comparator<Car> byYearAndPrice = (car1, car2) -> {
// metai mažėjančia tvarka, esant vienodiems lyginama price
if (car1.getYear() < car2.getYear()) {
return 1;
}
if (car1.getYear() > car2.getYear()) {
return -1;
}
if (car1.getPrice() < car2.getPrice()) {
return 1;
}
if (car1.getPrice() > car2.getPrice()) {
return -1;
}
return 0;
};
// metodas main = tiesiog paprastas pirminis automobilių išbandymas
public static void main(String... args) {
// suvienodiname skaičių formatus pagal LT lokalę (10-ainis kablelis)
Locale.setDefault(new Locale("LT"));
Car a1 = new Car("Renault", "Laguna", 1997, 50000, 599);
Car a2 = new Car("Renault", "Megane", 2015, 20000, 3500);
Car a3 = new Car();
Car a4 = new Car();
a3.parse("Toyota Corolla 2001 20000 8500,8");
a4.parse("Toyota Avensis 1990 20000 500,8");
Ks.oun(a1);
Ks.oun(a2);
Ks.oun(a3);
Ks.oun(a4);
}
}

View File

@ -0,0 +1,11 @@
package com.ktu;
import util.ParsableList;
public class CarList extends ParsableList<Car> {
@Override
protected Car createElement(String data) {
return new Car(data);
}
}

View File

@ -0,0 +1,62 @@
/**
* Tai yra automobilių sąrašų kūrimo ir tolimesnių taikomųjų veiksmų klasė.
****************************************************************************/
package com.ktu;
public class CarMarket {
public CarList allCars = new CarList();
// suformuojamas sąrašas automobilių, kurie pagaminti vėliau nei riba
public CarList getNewerCars(int fromYear) {
CarList cars = new CarList();
for (Car c : allCars) {
if (c.getYear() >= fromYear) {
cars.add(c);
}
}
return cars;
}
// suformuojamas sąrašas automobilių, kurių kaina yra tarp ribų
public CarList getByPrice(int fromPrice, int toPrice) {
CarList cars = new CarList();
for (Car c : allCars) {
if (c.getPrice() >= fromPrice && c.getPrice() <= toPrice) {
cars.add(c);
}
}
return cars;
}
// suformuojamas sąrašas automobilių, turinčių didžiausią ridą
public CarList getHighestMileageCars() {
CarList cars = new CarList();
// formuojamas sąrašas su maksimalia reikšme vienos peržiūros metu
double maxMileage = 0;
for (Car c : allCars) {
double mileage = c.getMileage();
if (mileage >= maxMileage) {
if (mileage > maxMileage) {
cars.clear();
maxMileage = mileage;
}
cars.add(c);
}
}
return cars;
}
// suformuojams sąrašas automobilių, kurių modelio kodas atitinka nurodytą
public CarList getByMakeAndModel(String makeAndModel) {
CarList cars = new CarList();
for (Car c : allCars) {
String carMakeAndModel = c.getMake() + " " + c.getModel();
if (carMakeAndModel.startsWith(makeAndModel)) {
cars.add(c);
}
}
return cars;
}
// metodo main nėra -> demo bandymai klasėje ManualTest
}

View File

@ -0,0 +1,172 @@
/** @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra, 2014 09 23
*
* Tai yra demonstracinė automobilių sąrašo bandymų klasė, kuri skirta tiesiog
* veiksmų su sąrašais išbandymui.
*************************************************************************** */
package com.ktu;
import util.Ks;
import java.util.Comparator;
import java.util.Locale;
public class ManualTest {
CarList cars = new CarList();
void execute() {
//createCars();
createCarList();
// countRenault();
// appendCarList();
// checkCarMarketFilters();
// checkCarMarketSorting();
}
void createCars() {
Car c1 = new Car("Renault", "Laguna", 1997, 50000, 1700);
Car c2 = new Car("Renault", "Megane", 2001, 20000, 3500);
Car c3 = new Car("Toyota", "Corolla", 2001, 20000, 8500.8);
Car c4 = new Car();
Car c5 = new Car();
Car c6 = new Car();
c4.parse("Renault Laguna 2001 115900 7500");
c5.parse("Renault Megane 1946 365100 9500");
c6.parse("Honda Civic 2007 36400 8500,3");
Ks.oun(c1);
Ks.oun(c2);
Ks.oun(c3);
Ks.oun("Pirmų 3 auto ridos vidurkis= "
+ (c1.getMileage() + c2.getMileage() + c3.getMileage()) / 3);
Ks.oun(c4);
Ks.oun(c5);
Ks.oun(c6);
Ks.oun("Kitų 3 auto kainų suma= "
+ (c4.getPrice() + c5.getPrice() + c6.getPrice()));
}
void createCarList() {
Car c1 = new Car("Renault", "Laguna", 1997, 50000, 1700);
Car c2 = new Car("Renault", "Megane", 2001, 20000, 3500);
Car c3 = new Car("Toyota", "Corolla", 2001, 20000, 8500.8);
cars.add(c1);
cars.add(c2);
cars.add(c3);
cars.println("Pirmi 3 auto");
cars.add("Renault Laguna 2001 115900 7500");
cars.add("Renault Megane 1946 365100 9500");
cars.add("Honda Civic 2007 36400 8500,3");
cars.println("Visi 6 auto");
cars.forEach(System.out::println);
Ks.oun("Pirmų 3 auto ridos vidurkis= "
+ (cars.get(0).getMileage() + cars.get(1).getMileage()
+ cars.get(2).getMileage()) / 3);
Ks.oun("Kitų 3 auto kainų suma= "
+ (cars.get(3).getPrice() + cars.get(4).getPrice()
+ cars.get(5).getPrice()));
// palaipsniui atidenkite sekančias eilutes ir išbandykite
cars.add(0, new Car("Mazda","6",2007,50000,27000));
cars.add(6, new Car("Hyundai","Lantra",1998,9500,777));
cars.set(4, c3);
cars.println("Po įterpimų");
cars.remove(7);
cars.remove(0);
cars.println("Po išmetimų");
cars.remove(0); cars.remove(0); cars.remove(0);
cars.remove(0); cars.remove(0); cars.remove(0);
cars.println("Po visų išmetimų");
cars.remove(0);
cars.println("Po visų išmetimų");
}
void countRenault() {
int sk = 0;
for (Car c : cars) {
if (c.getMake().compareTo("Renault") == 0) {
sk++;
}
}
Ks.oun("Renault automobilių yra = " + sk);
}
void appendCarList() {
for (int i = 0; i < 8; i++) {
cars.add(new Car("Ford", "Focus",
2009 - i, 40000 + i * 10000, 36000 - i * 2000));
}
cars.add("Ford Mondeo 2009 37000 36000.0");
cars.add("Fiat Bravo 2008 27000 32500,0");
cars.add("Ford Fiesta 2009 37000 16000,0");
cars.add("Audi A6 2006 87000 36000,0");
cars.println("Testuojamų automobilių sąrašas");
cars.save("ban.txt");
}
void checkCarMarketFilters() {
CarMarket market = new CarMarket();
market.allCars.load("ban.txt");
market.allCars.println("Bandomasis rinkinys");
cars = market.getNewerCars(2001);
cars.println("Pradedant nuo 2001");
cars = market.getByPrice(3000, 10000);
cars.println("Kaina tarp 3000 ir 10000");
cars = market.getHighestMileageCars();
cars.println("Daugiausiai nuvažiavę");
cars = market.getByMakeAndModel("F");
cars.println("Turi būti tik Fiatai ir Fordai");
cars = market.getByMakeAndModel("Ford M");
cars.println("Turi būti tik Ford Mondeo");
int n = 0;
for (Car c : cars) {
n++; // testuojame ciklo veikimą
}
Ks.oun("Ford Mondeo kiekis = " + n);
}
void checkCarMarketSorting() {
CarMarket market = new CarMarket();
market.allCars.load("ban.txt");
Ks.oun("========" + market.allCars.get(0));
market.allCars.println("Bandomasis rinkinys");
market.allCars.sortBuble(Car.byMakeAndModel);
market.allCars.println("Rūšiavimas pagal Markę ir Modelį");
market.allCars.sortBuble(Car.byPrice);
market.allCars.println("Rūšiavimas pagal kainą");
market.allCars.sortBuble(Car.byYearAndPrice);
market.allCars.println("Rūšiavimas pagal Metus ir Kainą");
market.allCars.sortBuble(byMileage);
market.allCars.sortBuble(Comparator.comparingInt(Car::getMileage));
market.allCars.println("Rūšiavimas pagal Ridą");
market.allCars.sortBuble();
market.allCars.println("Rūšiavimas pagal compareTo - Kainą");
}
static Comparator<Car> byMileage = (car1, car2) -> {
int m1 = car1.getMileage();
int m2 = car2.getMileage();
// rida atvirkščia mažėjančia tvarka, pradedant nuo didžiausios
if (m1 < m2) {
return 1;
}
if (m1 > m2) {
return -1;
}
return 0;
};
public static void main(String... args) {
// suvienodiname skaičių formatus pagal LT lokalę (10-ainis kablelis)
Locale.setDefault(new Locale("LT"));
new ManualTest().execute();
}
}

View File

@ -0,0 +1,38 @@
package com.ktu;
import util.ArrayStack;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
public class Optional1 {
public static void main(String... args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
boolean result = check(line);
System.out.println(result);
}
}
public static boolean check(String line) {
ArrayStack<Character> stack = new ArrayStack<>();
for (char c : line.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if (c == ')' || c == ']' || c == '}') {
char opening_c = stack.pop();
if (!((opening_c == '(' && c == ')') ||
(opening_c == '[' && c == ']') ||
(opening_c == '{' && c == '}'))) {
return false;
}
}
}
return stack.isEmpty();
}
}

View File

@ -0,0 +1,39 @@
package com.ktu;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.stream.Collectors;
public class Optional2 {
static int[] slidingMaximum(int[] nums, int m)
{
int[] ans = new int[nums.length - m + 1];
Deque<Integer> d = new ArrayDeque<>();
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
while (!d.isEmpty() && nums[d.getLast()] < num) {
d.removeLast();
}
d.addLast(i);
if (d.getFirst() == i - m) {
d.removeFirst();
}
if (i >= m-1) {
ans[i - m + 1] = nums[d.getFirst()];
}
}
return ans;
}
public static void main(String args[])
{
int m = 3;
int[] numbers = { 8, 7, 5, 4, 3, 1 };
int[] ans = slidingMaximum(numbers, m);
System.out.println(Arrays.stream(ans).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
}
}

View File

@ -0,0 +1,103 @@
/** @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra, 2014 09 23
*
* Tai yra darbo su sąrašais greitaveikos tyrimo klasė.
* Pavyzdyje pateiktas rikiavimo metodų tyrimas.
* Tyrimo metu pateiktais metodais naudojamasi kaip šablonais,
* išbandant įvairius rūšiavimo aspektus.
*************************************************************************** */
package com.ktu;
import util.Ks;
import util.LinkedList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.Random;
public class SimpleBenchmark {
Car[] cars;
LinkedList<Car> carSeries = new LinkedList<>();
Random rg = new Random(); // atsitiktinių generatorius
int[] counts = {2_000, 4_000, 8_000, 16_000};
// pabandykite, ar Jūsų kompiuteris įveiks šiuos eksperimentus
// static int[] counts = {10_000, 20_000, 40_000, 80_000};
void generateCars(int count) {
String[][] makesAndModels = { // galimų automobilių markių ir modelių masyvas
{"Mazda", "121", "323", "626", "MX6"},
{"Ford", "Fiesta", "Escort", "Focus", "Sierra", "Mondeo"},
{"Saab", "92", "96"},
{"Honda", "Accord", "Civic", "Jazz"},
{"Renault", "Laguna", "Megane", "Twingo", "Scenic"},
{"Peugeot", "206", "207", "307"}
};
cars = new Car[count];
rg.setSeed(2017);
for (int i = 0; i < count; i++) {
int makeIndex = rg.nextInt(makesAndModels.length); // markės indeksas 0..
int modelIndex = rg.nextInt(makesAndModels[makeIndex].length - 1) + 1;// modelio indeksas 1..
cars[i] = new Car(makesAndModels[makeIndex][0], makesAndModels[makeIndex][modelIndex],
1994 + rg.nextInt(20), // metai tarp 1994 ir 2013
6000 + rg.nextInt(222_000), // rida tarp 6000 ir 228000
1000 + rg.nextDouble() * 350_000); // kaina tarp 1000 ir 351_000
}
Collections.shuffle(Arrays.asList(cars));
carSeries.clear();
for (Car c : cars) {
carSeries.add(c);
}
}
void generateAndExecute(int elementCount) {
// Paruošiamoji tyrimo dalis
long t0 = System.nanoTime();
generateCars(elementCount);
LinkedList<Car> carSeries2 = carSeries.clone();
LinkedList<Car> carSeries3 = carSeries.clone();
LinkedList<Car> carSeries4 = carSeries.clone();
long t1 = System.nanoTime();
System.gc();
System.gc();
System.gc();
long t2 = System.nanoTime();
// Greitaveikos bandymai ir laiko matavimai
carSeries.sortSystem();
long t3 = System.nanoTime();
carSeries2.sortSystem(Car.byPrice);
long t4 = System.nanoTime();
carSeries3.sortBuble();
long t5 = System.nanoTime();
carSeries4.sortBuble(Car.byPrice);
long t6 = System.nanoTime();
Ks.ouf("%7d %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f \n", elementCount,
(t1 - t0) / 1e9, (t2 - t1) / 1e9, (t3 - t2) / 1e9,
(t4 - t3) / 1e9, (t5 - t4) / 1e9, (t6 - t5) / 1e9);
}
void execute() {
long memTotal = Runtime.getRuntime().totalMemory();
Ks.oun("memTotal= " + memTotal);
// Pasižiūrime kaip generuoja automobilius (20) vienetų)
generateCars(20);
for (Car c : carSeries) {
Ks.oun(c);
}
Ks.oun("1 - Pasiruošimas tyrimui - duomenų generavimas");
Ks.oun("2 - Pasiruošimas tyrimui - šiukšlių surinkimas");
Ks.oun("3 - Rūšiavimas sisteminiu greitu būdu be Comparator");
Ks.oun("4 - Rūšiavimas sisteminiu greitu būdu su Comparator");
Ks.oun("5 - Rūšiavimas List burbuliuku be Comparator");
Ks.oun("6 - Rūšiavimas List burbuliuku su Comparator");
Ks.ouf("%6d %7d %7d %7d %7d %7d %7d \n", 0, 1, 2, 3, 4, 5, 6);
for (int n : counts) {
generateAndExecute(n);
}
}
public static void main(String[] args) {
// suvienodiname skaičių formatus pagal LT lokalę (10-ainis kablelis)
Locale.setDefault(new Locale("LT"));
new SimpleBenchmark().execute();
}
}

View File

@ -0,0 +1,42 @@
package util;
import java.util.ArrayList;
public class ArrayQueue<E> implements Queue<E> {
private ArrayList<E> data;
private int start = 0;
private int end = -1;
public ArrayQueue() {
data = new ArrayList<>();
}
@Override
public void enqueue(E item) {
data.set(++end, item);
}
@Override
public E dequeue() {
if (isEmpty()) return null;
E value = data.get(start++);
if (isEmpty()) {
data = new ArrayList<>();
start = 0;
end = -1;
}
return value;
}
@Override
public E peak() {
if (isEmpty()) return null;
return data.get(start);
}
@Override
public boolean isEmpty() {
return start > end;
}
}

View File

@ -0,0 +1,35 @@
package util;
import java.util.ArrayList;
public class ArrayStack<E> implements Stack<E> {
private ArrayList<E> data;
public ArrayStack() {
data = new ArrayList<>();
}
@Override
public E pop() {
int size = data.size();
if (size == 0) return null;
return data.remove(size-1);
}
@Override
public void push(E item) {
data.add(item);
}
@Override
public E peak() {
int size = data.size();
if (size == 0) return null;
return data.get(size-1);
}
@Override
public boolean isEmpty() {
return data.size() == 0;
}
}

View File

@ -0,0 +1,159 @@
/** @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra, 2014 09 23
*
* Klasė yra skirta patogiam duomenų paėmimui klaviatūros bei
* efektyviam rezultatų pateikimui į sout ir serr srautus.
* Visi metodai yra statiniai ir skirti vienam duomenų tipui.
*************************************************************************** */
package util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Arrays;
public class Ks { // KTU system - imituojama Javos System klasė
private static final BufferedReader keyboard
= new BufferedReader(new InputStreamReader(System.in));
private static String dataFolderKTU = "Duomenys";
static public String giveString(String prompt) {
Ks.ou(prompt);
try {
return keyboard.readLine();
} catch (IOException e) {
Ks.ern("Neveikia klaviatūros srautas, darbas baigtas");
System.exit(0);
}
return "";
}
static public long giveLong(String prompt) {
while (true) {
String s = giveString(prompt);
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
Ks.ern("Neteisingas skaičiaus formatas, pakartokite");
}
}
}
static public long giveLong(String prompt, long bound1, long bound2) {
while (true) {
long a = giveLong(prompt + " tarp ribų [" + bound1 + ":" + bound2 + "]=");
if (a < bound1) {
Ks.ern("Skaičius mažesnis nei leistina, pakartokite");
} else if (a > bound2) {
Ks.ern("Skaičius didesnis nei leistina, pakartokite");
} else {
return a;
}
}
}
static public int giveInt(String prompt) {
while (true) {
long a = giveLong(prompt);
if (a < Integer.MIN_VALUE) {
Ks.ern("Skaičius mažesnis nei Integer.MIN_VALUE"
+ ", pakartokite");
} else if (a > Integer.MAX_VALUE) {
Ks.ern("Skaičius didesnis nei Integer.MAX_VALUE"
+ ", pakartokite");
} else {
return (int) a;
}
}
}
static public int giveInt(String prompt, int bound1, int bound2) {
return (int) giveLong(prompt, bound1, bound2);
}
static public double giveDouble(String prompt) {
while (true) {
String s = giveString(prompt);
try {
return Double.parseDouble(s);
} catch (NumberFormatException e) {
if (s.contains(",")) {
Ks.ern("Vietoje kablelio naudokite tašką"
+ ", pakartokite");
} else {
Ks.ern("Neteisingas skaičiaus formatas"
+ ", pakartokite");
}
}
}
}
static public double giveDouble(String prompt, double bound1, double bound2) {
while (true) {
double a = giveDouble(prompt + " tarp ribų [" + bound1 + ":" + bound2 + "]=");
if (a < bound1) {
Ks.ern("Skaičius mažesnis nei leistina, pakartokite");
} else if (a > bound2) {
Ks.ern("Skaičius didesnis nei leistina, pakartokite");
} else {
return a;
}
}
}
static public String giveFileName() {
File dir = new File(dataFolderKTU);
dir.mkdir();
oun("Jums prieinami failai " + Arrays.toString(dir.list()));
String fn = giveString("Nurodykite pasirinktą duomenų failo vardą: ");
return (fn);
}
static public String getDataFolder() {
return dataFolderKTU;
}
static public void setDataFolder(String folderName) {
dataFolderKTU = folderName;
}
private static final PrintStream sout = System.out;
private static final PrintStream serr = System.out;
private static int lineNr;
private static int errorNr;
private static final boolean formatStartOfLine = true;
static public void ou(Object obj) {
if (formatStartOfLine) {
sout.printf("%2d| %s", ++lineNr, obj);
} else {
sout.println(obj);
}
}
static public void oun(Object obj) {
if (formatStartOfLine) {
sout.printf("%2d| %s\n", ++lineNr, obj);
} else {
sout.println(obj);
}
}
static public void ouf(String format, Object... args) {
sout.printf(format, args);
}
static public void er(Object obj) {
serr.printf("***Klaida %d: %s", ++errorNr, obj);
}
static public void ern(Object obj) {
serr.printf("***Klaida %d: %s\n", ++errorNr, obj);
}
static public void erf(String format, Object... args) {
serr.printf(format, args);
}
}

View File

@ -0,0 +1,408 @@
/**
* @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra, 2014 09 23
*
* Tai pirmoji kompleksinės duomenų struktūros klasė, kuri leidžia apjungti
* atskirus objektus į vieną visumą - sąrašą. Objektai, kurie bus dedami į
* sąrašą, turi tenkinti interfeisą Comparable<E>.
*
* Užduotis: Peržiūrėkite ir išsiaiškinkite pateiktus metodus. Metodų algoritmai
* yra aptarti paskaitos metu. Realizuokite nurodytus metodus.
* ****************************************************************************
*/
package util;
import java.util.Arrays;
import java.util.Comparator;
/**
* Koreguota 2015-09-18
*
* @author Aleksis
* @param <E> Sąrašo elementų tipas (klasė)
*/
public class LinkedList<E extends Comparable<E>>
implements List<E>, Iterable<E>, Cloneable {
private Node<E> first; // rodyklė į pirmą mazgą
private Node<E> last; // rodyklė į paskutinį mazgą
private Node<E> current; // rodyklė į einamąjį mazgą, naudojama getNext
private int size; // sąrašo dydis, tuo pačiu elementų skaičius
/**
* Constructs an empty list.
*/
public LinkedList() {
}
/**
* metodas add įdeda elementą į sąrašo pabaigą
*
* @param e - tai įdedamas elementas (jis negali būti null)
* @return true, jei operacija atlikta sėkmingai
*/
@Override
public boolean add(E e) {
if (e == null) {
return false; // nuliniai objektai nepriimami
}
if (first == null) {
first = new Node<>(e, first);
last = first;
} else {
Node<E> e1 = new Node(e, null);
last.next = e1;
last = e1;
}
size++;
return true;
}
/**
* Įterpia elementą prieš k-ąją poziciją
*
* @param k pozicija
* @param e įterpiamasis elementas
* @return jei k yra blogas, grąžina null
*/
@Override
public boolean add(int k, E e) {
if (e == null) return false;
if (k < 0 || k >= size) return false;
Node<E> prev = null;
Node<E> current = this.first;
for (int i = 0; i < k; i++) {
prev = current;
current = current.next;
}
Node<E> d = new Node<>(e, null);
if (prev == null && current.next == null) {
this.last = d;
this.first = d;
} else if (current.next == null) {
this.last.next = d;
this.last = d;
} else if (prev == null) {
d.next = this.first;
this.first = d;
} else {
prev.next = d;
d.next = current;
}
size++;
return true;
}
/**
*
* @return sąrašo dydis (elementų kiekis)
*/
@Override
public int size() {
return size;
}
/**
* patikrina ar sąrašas yra tuščias
*
* @return true, jei tuščias
*/
@Override
public boolean isEmpty() {
return first == null;
}
/**
* Išvalo sąrašą
*/
@Override
public void clear() {
size = 0;
first = null;
last = null;
current = null;
}
/**
* Grąžina elementą pagal jo indeksą (pradinis indeksas 0)
*
* @param k indeksas
* @return k-ojo elemento reikšmę; jei k yra blogas, gąžina null
*/
@Override
public E get(int k) {
if (k < 0 || k >= size) {
return null;
}
current = first.findNode(k);
return current.element;
}
/**
* Pakeičia k-ojo elemento reikšmę
*
* @param k keičiamo elemento indeksas
* @param e nauja elemento reikšmė
* @return senoji reikšmė
*/
@Override
public E set(int k, E e) {
int i = 0;
Node<E> current = this.first;
while (current != null && i < k) {
current = current.next;
i = i + 1;
}
if (i == k && current != null) {
E old = current.element;
current.element = e;
return old;
} else {
return null;
}
}
/**
* pereina prie kitos reikšmės ir grąžina
*
* @return kita reikšmė
*/
@Override
public E getNext() {
if (current == null) {
return null;
}
current = current.next;
if (current == null) {
return null;
}
return current.element;
}
/**
* Šalina elementą pagal indeksą
*
* @param k šalinamojo indeksas
* @return pašalintas elementas
*/
@Override
public E remove(int k) {
if (k < 0 || k >= size) return null;
Node<E> prev = null;
Node<E> current = this.first;
for (int i = 0; i < k; i++) {
prev = current;
current = current.next;
}
if (prev == null && current.next == null) {
this.last = null;
this.first = null;
} else if (current.next == null) {
this.last = prev;
} else if (prev == null) {
this.first = current.next;
} else {
prev.next = current.next;
}
size--;
return current.element;
}
/**
*
* @return sąrašo kopiją
*/
@Override
public LinkedList<E> clone() {
LinkedList<E> cl = null;
try {
cl = (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
Ks.ern("Blogai veikia ListKTU klasės protėvio metodas clone()");
System.exit(1);
}
if (first == null) {
return cl;
}
cl.first = new Node<>(this.first.element, null);
Node<E> e2 = cl.first;
for (Node<E> e1 = first.next; e1 != null; e1 = e1.next) {
e2.next = new Node<>(e2.element, null);
e2 = e2.next;
e2.element = e1.element;
}
cl.last = e2.next;
cl.size = this.size;
return cl;
}
// !
/**
* Formuojamas Object masyvas (E tipo masyvo negalima sukurti) ir surašomi
* sąrašo elementai
*
* @return sąrašo elementų masyvas
*/
public Object[] toArray() {
Object[] a = new Object[size];
int i = 0;
for (Node<E> e1 = first; e1 != null; e1 = e1.next) {
a[i++] = e1.element;
}
return a;
}
/**
* Masyvo rikiavimas Arrays klasės metodu sort
*/
public void sortSystem() {
Object[] a = this.toArray();
Arrays.sort(a);
int i = 0;
for (Node<E> e1 = first; e1 != null; e1 = e1.next) {
e1.element = (E) a[i++];
}
}
/**
* Rikiavimas Arrays klasės metodu sort pagal komparatorių
*
* @param c komparatorius
*/
public void sortSystem(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
int i = 0;
for (Node<E> e1 = first; e1 != null; e1 = e1.next) {
e1.element = (E) a[i++];
}
}
/**
* Sąrašo rikiavimas burbuliuko metodu
*/
public void sortBuble() {
if (first == null) {
return;
}
for (;;) {
boolean jauGerai = true;
Node<E> e1 = first;
for (Node<E> e2 = first.next; e2 != null; e2 = e2.next) {
if (e1.element.compareTo(e2.element) > 0) {
E t = e1.element;
e1.element = e2.element;
e2.element = t;
jauGerai = false;
}
e1 = e2;
}
if (jauGerai) {
return;
}
}
}
/**
* Sąrašo rikiavimas burbuliuko metodu pagal komparatorių
*
* @param c komparatorius
*/
public void sortBuble(Comparator<? super E> c) {
if (first == null) {
return;
}
for (;;) {
boolean jauGerai = true;
Node<E> e1 = first;
for (Node<E> e2 = first.next; e2 != null; e2 = e2.next) {
if (c.compare(e1.element, e2.element) > 0) {
E t = e1.element;
e1.element = e2.element;
e2.element = t;
jauGerai = false;
}
e1 = e2;
}
if (jauGerai) {
return;
}
}
}
/**
* Sukuria iteratoriaus objektą sąrašo elementų peržiūrai
*
* @return iteratoriaus objektą
*/
@Override
public java.util.Iterator<E> iterator() {
return new Iterator();
}
/**
* Iteratoriaus metodų klasė
*/
class Iterator implements java.util.Iterator<E> {
private Node<E> iterPosition;
Iterator() {
iterPosition = first;
}
@Override
public boolean hasNext() {
return iterPosition != null;
}
@Override
public E next() {
E d = iterPosition.element;
iterPosition = iterPosition.next;
return d;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Studentams reikia realizuoti remove()");
}
}
/**
* Vidinė mazgo klasė
*
* @param <E> mazgo duomenų tipas
*/
private static class Node<E> {
private E element; // ji nematoma klasės ListKTU ribų
private Node<E> next; // next - kaip įprasta - nuoroda į kitą mazgą
Node(E data, Node<E> next) { //mazgo konstruktorius
this.element = data;
this.next = next;
}
/**
* Suranda sąraše k-ąjį mazgą
*
* @param k ieškomo mazgo indeksas (prasideda nuo 0)
* @return surastas mazgas
*/
public Node<E> findNode(int k) {
Node<E> e = this;
for (int i = 0; i < k; i++) {
e = e.next;
}
return e;
}
} // klasės Node pabaiga
}

View File

@ -0,0 +1,29 @@
package util;
public class LinkedListQueue<E extends Comparable<E>> implements Queue<E> {
private LinkedList<E> data;
public LinkedListQueue() {
data = new LinkedList<>();
}
@Override
public void enqueue(E item) {
data.add(item);
}
@Override
public E dequeue() {
return data.remove(0);
}
@Override
public E peak() {
return data.get(0);
}
@Override
public boolean isEmpty() {
return data.isEmpty();
}
}

View File

@ -0,0 +1,29 @@
package util;
public class LinkedListStack<E extends Comparable<E>> implements Stack<E> {
private LinkedList<E> data;
public LinkedListStack() {
data = new LinkedList();
}
@Override
public E pop() {
return data.remove(0);
}
@Override
public void push(E item) {
data.add(0, item);
}
@Override
public E peak() {
return data.get(0);
}
@Override
public boolean isEmpty() {
return data.isEmpty();
}
}

View File

@ -0,0 +1,60 @@
/** @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra, 2014 09 23
*
* Tai pirmosios kolekcijų duomenų struktūros klasės interfeisas,
* apibrėžiantis operacijas, kurių pagalba atskiri objektai apjungiami
* į vieną visumą - sąrašą.
***************************************************************************** */
package util;
public interface List<E> {
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return true, if operation is Ok
*/
boolean add(E e);
boolean add(int k, E e);
/**
* Returns the number of elements in this list.
*
* @param k index of the element to be removed
* @return removed object e
*/
E remove(int k);
int size();
boolean isEmpty();
/**
* Removes all of the elements from this list.
*/
void clear();
/**
* Positional Access Operations. Returns the element at the specified
* position in this list.
*
* @param k index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
E get(int k);
E getNext();
/**
* Replaces the element at the specified position in this list with the
* specified element.
*
* @param k index of the element to replace
* @param e element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
E set(int k, E e);
}

View File

@ -0,0 +1,10 @@
/** @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra, 2014 09 23
*
* Tai yra interfeisas, kurį turi tenkinti KTU studentų kuriamos duomenų klasės.
* Metodai užtikrina patogų duomenų suformavimą String eilučių.
***************************************************************************** */
package util;
public interface Parsable<T> extends Comparable<T> {
void parse(String dataString); // suformuoja objektą eilutės
}

View File

@ -0,0 +1,103 @@
/** @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra, 2014 09 23
*
* Tai išvestinė kompleksinės duomenų struktūros klasė, kuri leidžia
* papildomai atlikti įvedimo - išvedimo veiksmus su sąrašo elementais.
* Objektai, kurie bus dedami į sąrašą, turi tenkinti interfeisą Parsable<E>.
*****************************************************************************
*/
package util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.function.Function;
public class ParsableList<E extends Parsable<E>> extends LinkedList<E> {
private Function<String, E> createFunction;
public ParsableList() {
}
public ParsableList(Function<String, E> createFunction) {
this.createFunction = createFunction;
}
public void add(String dataString) { // sukuria elementą String
add(createElement(dataString)); // ir įdeda į pabaigą
}
public void load(String fName) {//suformuoja sąrašą fName failo
clear();
if (fName.length() == 0) {
return;
}
try {
(new File(Ks.getDataFolder())).mkdir();
String fN = Ks.getDataFolder() + File.separatorChar + fName;
BufferedReader fReader
= new BufferedReader(new FileReader(new File(fN)));
String dLine;
while ((dLine = fReader.readLine()) != null) {
add(dLine);
}
fReader.close();
} catch (FileNotFoundException e) {
Ks.ern("Duomenų failas " + fName + " nerastas");
// System.exit(0);
} catch (IOException e) {
Ks.ern("Failo " + fName + " skaitymo klaida");
System.exit(0);
}
}
public void save(String fName) { // išsaugoja sąrašą faile fName
PrintWriter fWriter = null; // tekstiniu formatu
try { // tinkamu vėlesniam skaitymui
// jei vardo nėra - failas neformuojamas
if (fName.equals("")) {
return;
}
String fN = Ks.getDataFolder() + File.separatorChar + fName;
fWriter = new PrintWriter(new FileWriter(new File(fN)));
for (Parsable d1 = super.get(0); d1 != null; d1 = super.getNext()) {
fWriter.println(d1.toString());
}
fWriter.close();
} catch (IOException e) {
Ks.ern("!!! Klaida formuojant " + fName + " failą.");
System.exit(0);
}
}
public void println() { // sąrašas spausdinamas į Ks.oun("");
int eilNr = 0;
if (super.isEmpty()) {
Ks.oun("Sąrašas yra tuščias");
} else {
for (Parsable d1 = super.get(0); d1 != null; d1 = super.getNext()) {
String printData = String.format("%3d: %s ", eilNr++, d1.toString());
Ks.oun(printData);
}
}
Ks.oun("****** Bendras elementų kiekis yra " + super.size());
}
public void println(String title) { // spausdinant galima nurodyti antraštę
Ks.oun("========" + title + "=======");
println();
Ks.oun("======== Sąrašo pabaiga =======");
}
protected E createElement(String data) {
if (createFunction == null) {
throw new IllegalStateException("Nenustatyta sąrašo elementų kūrimo funkcija");
}
return createFunction.apply(data);
}
}

View File

@ -0,0 +1,8 @@
package util;
public interface Queue<E> {
void enqueue(E item);
E dequeue();
E peak();
boolean isEmpty();
}

View File

@ -0,0 +1,8 @@
package util;
public interface Stack<E> {
E pop();
void push(E item);
E peak();
boolean isEmpty();
}

3
Lab2_AibesMedziai/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

1
Lab2_AibesMedziai/.idea/.name generated Normal file
View File

@ -0,0 +1 @@
Lab2_AibesMedziai

16
Lab2_AibesMedziai/.idea/compiler.xml generated Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="Lab2_AibesMedziai" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="Lab2_AibesMedziai" target="1.8" />
</bytecodeTargetLevel>
</component>
</project>

463
Lab2_AibesMedziai/.idea/dbnavigator.xml generated Normal file
View File

@ -0,0 +1,463 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DBNavigator.Project.DataEditorManager">
<record-view-column-sorting-type value="BY_INDEX" />
<value-preview-text-wrapping value="true" />
<value-preview-pinned value="false" />
</component>
<component name="DBNavigator.Project.DataExportManager">
<export-instructions>
<create-header value="true" />
<friendly-headers value="false" />
<quote-values-containing-separator value="true" />
<quote-all-values value="false" />
<value-separator value="" />
<file-name value="" />
<file-location value="" />
<scope value="GLOBAL" />
<destination value="FILE" />
<format value="EXCEL" />
<charset value="windows-1252" />
<charset value="windows-1252" />
</export-instructions>
</component>
<component name="DBNavigator.Project.DatabaseBrowserManager">
<autoscroll-to-editor value="false" />
<autoscroll-from-editor value="true" />
<show-object-properties value="true" />
<loaded-nodes />
</component>
<component name="DBNavigator.Project.DatabaseFileManager">
<open-files />
</component>
<component name="DBNavigator.Project.EditorStateManager">
<last-used-providers />
</component>
<component name="DBNavigator.Project.ExecutionManager">
<retain-sticky-names value="false" />
</component>
<component name="DBNavigator.Project.MethodExecutionManager">
<method-browser />
<execution-history>
<group-entries value="true" />
<execution-inputs />
</execution-history>
<argument-values-cache />
</component>
<component name="DBNavigator.Project.ObjectDependencyManager">
<last-used-dependency-type value="INCOMING" />
</component>
<component name="DBNavigator.Project.ObjectQuickFilterManager">
<last-used-operator value="EQUAL" />
<filters />
</component>
<component name="DBNavigator.Project.ParserDiagnosticsManager">
<diagnostics-history />
</component>
<component name="DBNavigator.Project.ScriptExecutionManager" clear-outputs="true">
<recently-used-interfaces />
</component>
<component name="DBNavigator.Project.Settings">
<connections />
<browser-settings>
<general>
<display-mode value="TABBED" />
<navigation-history-size value="100" />
<show-object-details value="false" />
</general>
<filters>
<object-type-filter>
<object-type name="SCHEMA" enabled="true" />
<object-type name="USER" enabled="true" />
<object-type name="ROLE" enabled="true" />
<object-type name="PRIVILEGE" enabled="true" />
<object-type name="CHARSET" enabled="true" />
<object-type name="TABLE" enabled="true" />
<object-type name="VIEW" enabled="true" />
<object-type name="MATERIALIZED_VIEW" enabled="true" />
<object-type name="NESTED_TABLE" enabled="true" />
<object-type name="COLUMN" enabled="true" />
<object-type name="INDEX" enabled="true" />
<object-type name="CONSTRAINT" enabled="true" />
<object-type name="DATASET_TRIGGER" enabled="true" />
<object-type name="DATABASE_TRIGGER" enabled="true" />
<object-type name="SYNONYM" enabled="true" />
<object-type name="SEQUENCE" enabled="true" />
<object-type name="PROCEDURE" enabled="true" />
<object-type name="FUNCTION" enabled="true" />
<object-type name="PACKAGE" enabled="true" />
<object-type name="TYPE" enabled="true" />
<object-type name="TYPE_ATTRIBUTE" enabled="true" />
<object-type name="ARGUMENT" enabled="true" />
<object-type name="DIMENSION" enabled="true" />
<object-type name="CLUSTER" enabled="true" />
<object-type name="DBLINK" enabled="true" />
</object-type-filter>
</filters>
<sorting>
<object-type name="COLUMN" sorting-type="NAME" />
<object-type name="FUNCTION" sorting-type="NAME" />
<object-type name="PROCEDURE" sorting-type="NAME" />
<object-type name="ARGUMENT" sorting-type="POSITION" />
<object-type name="TYPE ATTRIBUTE" sorting-type="POSITION" />
</sorting>
<default-editors>
<object-type name="VIEW" editor-type="SELECTION" />
<object-type name="PACKAGE" editor-type="SELECTION" />
<object-type name="TYPE" editor-type="SELECTION" />
</default-editors>
</browser-settings>
<navigation-settings>
<lookup-filters>
<lookup-objects>
<object-type name="SCHEMA" enabled="true" />
<object-type name="USER" enabled="false" />
<object-type name="ROLE" enabled="false" />
<object-type name="PRIVILEGE" enabled="false" />
<object-type name="CHARSET" enabled="false" />
<object-type name="TABLE" enabled="true" />
<object-type name="VIEW" enabled="true" />
<object-type name="MATERIALIZED VIEW" enabled="true" />
<object-type name="INDEX" enabled="true" />
<object-type name="CONSTRAINT" enabled="true" />
<object-type name="DATASET TRIGGER" enabled="true" />
<object-type name="DATABASE TRIGGER" enabled="true" />
<object-type name="SYNONYM" enabled="false" />
<object-type name="SEQUENCE" enabled="true" />
<object-type name="PROCEDURE" enabled="true" />
<object-type name="FUNCTION" enabled="true" />
<object-type name="PACKAGE" enabled="true" />
<object-type name="TYPE" enabled="true" />
<object-type name="DIMENSION" enabled="false" />
<object-type name="CLUSTER" enabled="false" />
<object-type name="DBLINK" enabled="true" />
</lookup-objects>
<force-database-load value="false" />
<prompt-connection-selection value="true" />
<prompt-schema-selection value="true" />
</lookup-filters>
</navigation-settings>
<dataset-grid-settings>
<general>
<enable-zooming value="true" />
<enable-column-tooltip value="true" />
</general>
<sorting>
<nulls-first value="true" />
<max-sorting-columns value="4" />
</sorting>
<audit-columns>
<column-names value="" />
<visible value="true" />
<editable value="false" />
</audit-columns>
</dataset-grid-settings>
<dataset-editor-settings>
<text-editor-popup>
<active value="false" />
<active-if-empty value="false" />
<data-length-threshold value="100" />
<popup-delay value="1000" />
</text-editor-popup>
<values-actions-popup>
<show-popup-button value="true" />
<element-count-threshold value="1000" />
<data-length-threshold value="250" />
</values-actions-popup>
<general>
<fetch-block-size value="100" />
<fetch-timeout value="30" />
<trim-whitespaces value="true" />
<convert-empty-strings-to-null value="true" />
<select-content-on-cell-edit value="true" />
<large-value-preview-active value="true" />
</general>
<filters>
<prompt-filter-dialog value="true" />
<default-filter-type value="BASIC" />
</filters>
<qualified-text-editor text-length-threshold="300">
<content-types>
<content-type name="Text" enabled="true" />
<content-type name="Properties" enabled="true" />
<content-type name="XML" enabled="true" />
<content-type name="DTD" enabled="true" />
<content-type name="HTML" enabled="true" />
<content-type name="XHTML" enabled="true" />
<content-type name="Java" enabled="true" />
<content-type name="SQL" enabled="true" />
<content-type name="PL/SQL" enabled="true" />
<content-type name="JSON" enabled="true" />
<content-type name="JSON5" enabled="true" />
<content-type name="Groovy" enabled="true" />
<content-type name="AIDL" enabled="true" />
<content-type name="YAML" enabled="true" />
<content-type name="Manifest" enabled="true" />
</content-types>
</qualified-text-editor>
<record-navigation>
<navigation-target value="VIEWER" />
</record-navigation>
</dataset-editor-settings>
<code-editor-settings>
<general>
<show-object-navigation-gutter value="false" />
<show-spec-declaration-navigation-gutter value="true" />
<enable-spellchecking value="true" />
<enable-reference-spellchecking value="false" />
</general>
<confirmations>
<save-changes value="false" />
<revert-changes value="true" />
</confirmations>
</code-editor-settings>
<code-completion-settings>
<filters>
<basic-filter>
<filter-element type="RESERVED_WORD" id="keyword" selected="true" />
<filter-element type="RESERVED_WORD" id="function" selected="true" />
<filter-element type="RESERVED_WORD" id="parameter" selected="true" />
<filter-element type="RESERVED_WORD" id="datatype" selected="true" />
<filter-element type="RESERVED_WORD" id="exception" selected="true" />
<filter-element type="OBJECT" id="schema" selected="true" />
<filter-element type="OBJECT" id="role" selected="true" />
<filter-element type="OBJECT" id="user" selected="true" />
<filter-element type="OBJECT" id="privilege" selected="true" />
<user-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="false" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</user-schema>
<public-schema>
<filter-element type="OBJECT" id="table" selected="false" />
<filter-element type="OBJECT" id="view" selected="false" />
<filter-element type="OBJECT" id="materialized view" selected="false" />
<filter-element type="OBJECT" id="index" selected="false" />
<filter-element type="OBJECT" id="constraint" selected="false" />
<filter-element type="OBJECT" id="trigger" selected="false" />
<filter-element type="OBJECT" id="synonym" selected="false" />
<filter-element type="OBJECT" id="sequence" selected="false" />
<filter-element type="OBJECT" id="procedure" selected="false" />
<filter-element type="OBJECT" id="function" selected="false" />
<filter-element type="OBJECT" id="package" selected="false" />
<filter-element type="OBJECT" id="type" selected="false" />
<filter-element type="OBJECT" id="dimension" selected="false" />
<filter-element type="OBJECT" id="cluster" selected="false" />
<filter-element type="OBJECT" id="dblink" selected="false" />
</public-schema>
<any-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="true" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</any-schema>
</basic-filter>
<extended-filter>
<filter-element type="RESERVED_WORD" id="keyword" selected="true" />
<filter-element type="RESERVED_WORD" id="function" selected="true" />
<filter-element type="RESERVED_WORD" id="parameter" selected="true" />
<filter-element type="RESERVED_WORD" id="datatype" selected="true" />
<filter-element type="RESERVED_WORD" id="exception" selected="true" />
<filter-element type="OBJECT" id="schema" selected="true" />
<filter-element type="OBJECT" id="user" selected="true" />
<filter-element type="OBJECT" id="role" selected="true" />
<filter-element type="OBJECT" id="privilege" selected="true" />
<user-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="true" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</user-schema>
<public-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="true" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</public-schema>
<any-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="true" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</any-schema>
</extended-filter>
</filters>
<sorting enabled="true">
<sorting-element type="RESERVED_WORD" id="keyword" />
<sorting-element type="RESERVED_WORD" id="datatype" />
<sorting-element type="OBJECT" id="column" />
<sorting-element type="OBJECT" id="table" />
<sorting-element type="OBJECT" id="view" />
<sorting-element type="OBJECT" id="materialized view" />
<sorting-element type="OBJECT" id="index" />
<sorting-element type="OBJECT" id="constraint" />
<sorting-element type="OBJECT" id="trigger" />
<sorting-element type="OBJECT" id="synonym" />
<sorting-element type="OBJECT" id="sequence" />
<sorting-element type="OBJECT" id="procedure" />
<sorting-element type="OBJECT" id="function" />
<sorting-element type="OBJECT" id="package" />
<sorting-element type="OBJECT" id="type" />
<sorting-element type="OBJECT" id="dimension" />
<sorting-element type="OBJECT" id="cluster" />
<sorting-element type="OBJECT" id="dblink" />
<sorting-element type="OBJECT" id="schema" />
<sorting-element type="OBJECT" id="role" />
<sorting-element type="OBJECT" id="user" />
<sorting-element type="RESERVED_WORD" id="function" />
<sorting-element type="RESERVED_WORD" id="parameter" />
</sorting>
<format>
<enforce-code-style-case value="true" />
</format>
</code-completion-settings>
<execution-engine-settings>
<statement-execution>
<fetch-block-size value="100" />
<execution-timeout value="20" />
<debug-execution-timeout value="600" />
<focus-result value="false" />
<prompt-execution value="false" />
</statement-execution>
<script-execution>
<command-line-interfaces />
<execution-timeout value="300" />
</script-execution>
<method-execution>
<execution-timeout value="30" />
<debug-execution-timeout value="600" />
<parameter-history-size value="10" />
</method-execution>
</execution-engine-settings>
<operation-settings>
<transactions>
<uncommitted-changes>
<on-project-close value="ASK" />
<on-disconnect value="ASK" />
<on-autocommit-toggle value="ASK" />
</uncommitted-changes>
<multiple-uncommitted-changes>
<on-commit value="ASK" />
<on-rollback value="ASK" />
</multiple-uncommitted-changes>
</transactions>
<session-browser>
<disconnect-session value="ASK" />
<kill-session value="ASK" />
<reload-on-filter-change value="false" />
</session-browser>
<compiler>
<compile-type value="KEEP" />
<compile-dependencies value="ASK" />
<always-show-controls value="false" />
</compiler>
<debugger>
<debugger-type value="ASK" />
<use-generic-runners value="true" />
</debugger>
</operation-settings>
<ddl-file-settings>
<extensions>
<mapping file-type-id="VIEW" extensions="vw" />
<mapping file-type-id="TRIGGER" extensions="trg" />
<mapping file-type-id="PROCEDURE" extensions="prc" />
<mapping file-type-id="FUNCTION" extensions="fnc" />
<mapping file-type-id="PACKAGE" extensions="pkg" />
<mapping file-type-id="PACKAGE_SPEC" extensions="pks" />
<mapping file-type-id="PACKAGE_BODY" extensions="pkb" />
<mapping file-type-id="TYPE" extensions="tpe" />
<mapping file-type-id="TYPE_SPEC" extensions="tps" />
<mapping file-type-id="TYPE_BODY" extensions="tpb" />
</extensions>
<general>
<lookup-ddl-files value="true" />
<create-ddl-files value="false" />
<synchronize-ddl-files value="true" />
<use-qualified-names value="false" />
<make-scripts-rerunnable value="true" />
</general>
</ddl-file-settings>
<general-settings>
<regional-settings>
<date-format value="MEDIUM" />
<number-format value="UNGROUPED" />
<locale value="SYSTEM_DEFAULT" />
<use-custom-formats value="false" />
</regional-settings>
<environment>
<environment-types>
<environment-type id="development" name="Development" description="Development environment" color="-2430209/-12296320" readonly-code="false" readonly-data="false" />
<environment-type id="integration" name="Integration" description="Integration environment" color="-2621494/-12163514" readonly-code="true" readonly-data="false" />
<environment-type id="production" name="Production" description="Productive environment" color="-11574/-10271420" readonly-code="true" readonly-data="true" />
<environment-type id="other" name="Other" description="" color="-1576/-10724543" readonly-code="false" readonly-data="false" />
</environment-types>
<visibility-settings>
<connection-tabs value="true" />
<dialog-headers value="true" />
<object-editor-tabs value="true" />
<script-editor-tabs value="false" />
<execution-result-tabs value="true" />
</visibility-settings>
</environment>
</general-settings>
</component>
<component name="DBNavigator.Project.StatementExecutionManager">
<execution-variables />
</component>
</project>

7
Lab2_AibesMedziai/.idea/encodings.xml generated Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

View File

@ -0,0 +1,36 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="JavaDoc" enabled="true" level="WARNING" enabled_by_default="true">
<option name="TOP_LEVEL_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="INNER_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="METHOD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="@return@param@throws or @exception" />
</value>
</option>
<option name="FIELD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="IGNORE_DEPRECATED" value="false" />
<option name="IGNORE_JAVADOC_PERIOD" value="true" />
<option name="IGNORE_DUPLICATED_THROWS" value="false" />
<option name="IGNORE_POINT_TO_ITSELF" value="false" />
<option name="myAdditionalJavadocTags" value="užduotis" />
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>

6
Lab2_AibesMedziai/.idea/jpa-buddy.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JpaBuddyIdeaProjectConfig">
<option name="renamerInitialized" value="true" />
</component>
</project>

View File

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: junit:junit:4.13">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/junit/junit/4.13/junit-4.13.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/junit/junit/4.13/junit-4.13-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/junit/junit/4.13/junit-4.13-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: net.sf.jopt-simple:jopt-simple:4.6">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/net/sf/jopt-simple/jopt-simple/4.6/jopt-simple-4.6.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/net/sf/jopt-simple/jopt-simple/4.6/jopt-simple-4.6-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/net/sf/jopt-simple/jopt-simple/4.6/jopt-simple-4.6-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: org.apache.commons:commons-math3:3.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/commons/commons-math3/3.2/commons-math3-3.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/commons/commons-math3/3.2/commons-math3-3.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/commons/commons-math3/3.2/commons-math3-3.2-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: org.hamcrest:hamcrest-core:1.3">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: org.openjdk.jmh:jmh-core:1.25.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/openjdk/jmh/jmh-core/1.25.2/jmh-core-1.25.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/openjdk/jmh/jmh-core/1.25.2/jmh-core-1.25.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/openjdk/jmh/jmh-core/1.25.2/jmh-core-1.25.2-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: org.openjdk.jmh:jmh-generator-annprocess:1.25.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/openjdk/jmh/jmh-generator-annprocess/1.25.2/jmh-generator-annprocess-1.25.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/openjdk/jmh/jmh-generator-annprocess/1.25.2/jmh-generator-annprocess-1.25.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/openjdk/jmh/jmh-generator-annprocess/1.25.2/jmh-generator-annprocess-1.25.2-sources.jar!/" />
</SOURCES>
</library>
</component>

14
Lab2_AibesMedziai/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="temurin-17" project-jdk-type="JavaSDK" />
<component name="ProjectType">
<option name="id" value="jpab" />
</component>
</project>

8
Lab2_AibesMedziai/.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Lab2_AibesMedziai.iml" filepath="$PROJECT_DIR$/Lab2_AibesMedziai.iml" />
</modules>
</component>
</project>

124
Lab2_AibesMedziai/.idea/uiDesigner.xml generated Normal file
View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/target/generated-sources/annotations" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/src/benchmark/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.openjdk.jmh:jmh-core:1.25.2" level="project" />
<orderEntry type="library" name="Maven: net.sf.jopt-simple:jopt-simple:4.6" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-math3:3.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.openjdk.jmh:jmh-generator-annprocess:1.25.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.13" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
</component>
</module>

View File

@ -0,0 +1,22 @@
Renault Laguna 2007 50000 1700.0
Renault Megane 2011 20000 3500.0
Toyota Corolla 2011 20000 8500.8
Renault Laguna 2011 115900 7500.0
Renault Megane 1946 365100 9500.0
Honda Civic 2017 36400 8500.3
Ford Focus 2019 40000 36000.0
Ford Focus 2018 50000 34000.0
Ford Focus 2017 60000 32000.0
Ford Focus 2016 70000 30000.0
Ford Focus 2015 80000 28000.0
Ford Focus 2014 90000 26000.0
Ford Focus 2013 100000 24000.0
Ford Focus 2012 110000 22000.0
Ford Focus 2011 120000 20000.0
Ford Focus 2010 130000 18000.0
Ford Focus 2009 140000 16000.0
Ford Focus 2008 150000 14000.0
Ford Mondeo 2019 37000 36000.0
Fiat Bravo 2018 27000 36000.0
Ford Fiesta 2019 37000 16000.0
Audi A6 2016 87000 36000.0

BIN
Lab2_AibesMedziai/ktu.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

181
Lab2_AibesMedziai/pom.xml Normal file
View File

@ -0,0 +1,181 @@
<!--
Copyright (c) 2014, Oracle America, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Oracle nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>edu.ktu.ds</groupId>
<artifactId>lab2</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Lab2</name>
<!--
This is the demo/sample template build script for building Java benchmarks with JMH.
Edit as needed.
-->
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!--
JMH version to use with this project.
-->
<jmh.version>1.25.2</jmh.version>
<!--
Java source/target to use for compilation.
-->
<javac.target>1.8</javac.target>
<!--
Name of the benchmark Uber-JAR to generate.
-->
<uberjar.name>benchmarks</uberjar.name>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<compilerVersion>${javac.target}</compilerVersion>
<source>${javac.target}</source>
<target>${javac.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>${uberjar.name}</finalName>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
<filters>
<filter>
<!--
Shading signed JARs will fail without this.
http://stackoverflow.com/questions/999489/invalid-signature-file-when-attempting-to-run-a-jar
-->
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.5</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.3</version>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -0,0 +1,88 @@
package edu.ktu.ds.lab2;
import edu.ktu.ds.lab2.utils.AvlSet;
import edu.ktu.ds.lab2.utils.BstSet;
import edu.ktu.ds.lab2.utils.Set;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;
import java.util.concurrent.TimeUnit;
// https://github.com/dastruktu/benchmark/blob/master/src/main/java/edu/ktu/ds/benchmark/JmhBenchmark.java
@BenchmarkMode(Mode.AverageTime)
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(time = 1, timeUnit = TimeUnit.SECONDS)
public class AddAllBenchmark {
/*
Benchmark (listSize) Mode Cnt Score Error Units
AddAllBenchmark.avlSetAddAll 4000 avgt 5 12274.192 ± 1052.512 us/op
AddAllBenchmark.avlSetAddAll 8000 avgt 5 53572.221 ± 4584.040 us/op
AddAllBenchmark.avlSetAddAll 16000 avgt 5 199682.597 ± 19894.433 us/op
AddAllBenchmark.avlSetAddAll 32000 avgt 5 787332.020 ± 51936.079 us/op
AddAllBenchmark.avlSetAddAll 64000 avgt 5 2572856.880 ± 71156.461 us/op
AddAllBenchmark.avlSetAddAll 128000 avgt 5 7860938.300 ± 771355.219 us/op
AddAllBenchmark.bstSetAddAll 4000 avgt 5 499094.557 ± 444521.742 us/op
AddAllBenchmark.bstSetAddAll 8000 avgt 5 3312173.700 ± 200121.728 us/op
AddAllBenchmark.bstSetAddAll 16000 avgt 5 25703766.940 ± 551969.795 us/op
*/
public int chunkSize = 200;
@Param({"4000", "8000", "16000", "32000", "64000", "128000"})
public int listSize;
ArrayList<Set<Integer>> chunks;
BstSet<Integer> bstSet;
AvlSet<Integer> avlSet;
@Setup(Level.Trial)
public void generateChunks() {
chunks = new ArrayList<>();
chunks.ensureCapacity(listSize/chunkSize);
Random r = new Random();
for (int i = 0; i < listSize/chunkSize; i++) {
Set<Integer> chunk = new AvlSet<>();
for (int j = 0; j < listSize; j++) {
chunk.add(r.nextInt(100_000));
}
chunks.add(chunk);
}
}
@Setup(Level.Iteration)
public void createSets() {
bstSet = new BstSet<>();
avlSet = new AvlSet<>();
}
@Benchmark
public void bstSetAddAll(Blackhole bh) {
for (Set<Integer> chunk : chunks) {
bstSet.addAll(chunk);
}
}
@Benchmark
public void avlSetAddAll(Blackhole bh) {
for (Set<Integer> chunk : chunks) {
avlSet.addAll(chunk);
}
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(AddAllBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}

View File

@ -0,0 +1,96 @@
package edu.ktu.ds.lab2.demo;
import edu.ktu.ds.lab2.utils.AvlSet;
import edu.ktu.ds.lab2.utils.BstSet;
import edu.ktu.ds.lab2.utils.BstSetIterative;
import edu.ktu.ds.lab2.utils.SortedSet;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(time = 1, timeUnit = TimeUnit.SECONDS)
public class Benchmark {
@State(Scope.Benchmark)
public static class FullSet {
Car[] cars;
BstSet<Car> carSet;
@Setup(Level.Iteration)
public void generateElements(BenchmarkParams params) {
cars = Benchmark.generateElements(Integer.parseInt(params.getParam("elementCount")));
}
@Setup(Level.Invocation)
public void fillCarSet(BenchmarkParams params) {
carSet = new BstSet<>();
addElements(cars, carSet);
}
}
@Param({"10000", "20000", "40000", "80000"})
public int elementCount;
Car[] cars;
@Setup(Level.Iteration)
public void generateElements() {
cars = generateElements(elementCount);
}
static Car[] generateElements(int count) {
return new CarsGenerator().generateShuffle(count, 1.0);
}
@org.openjdk.jmh.annotations.Benchmark
public BstSet<Car> addBstRecursive() {
BstSet<Car> carSet = new BstSet<>(Car.byPrice);
addElements(cars, carSet);
return carSet;
}
@org.openjdk.jmh.annotations.Benchmark
public BstSetIterative<Car> addBstIterative() {
BstSetIterative<Car> carSet = new BstSetIterative<>(Car.byPrice);
addElements(cars, carSet);
return carSet;
}
@org.openjdk.jmh.annotations.Benchmark
public AvlSet<Car> addAvlRecursive() {
AvlSet<Car> carSet = new AvlSet<>(Car.byPrice);
addElements(cars, carSet);
return carSet;
}
@org.openjdk.jmh.annotations.Benchmark
public void removeBst(FullSet carSet) {
for (Car car : carSet.cars) {
carSet.carSet.remove(car);
}
}
public static void addElements(Car[] carArray, SortedSet<Car> carSet) {
for (Car car : carArray) {
carSet.add(car);
}
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(Benchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}

View File

@ -0,0 +1,227 @@
package edu.ktu.ds.lab2.demo;
import edu.ktu.ds.lab2.utils.Ks;
import edu.ktu.ds.lab2.utils.Parsable;
import java.time.LocalDate;
import java.util.*;
/**
* @author EK
*/
public final class Car implements Parsable<Car> {
// bendri duomenys visiems automobiliams (visai klasei)
private static final int minYear = 2000;
private static final int currentYear = LocalDate.now().getYear();
private static final double minPrice = 100.0;
private static final double maxPrice = 333000.0;
private static final String idCode = "TA"; // ***** nauja
private static int serNr = 100; // ***** nauja
private final String carRegNr;
private String make = "";
private String model = "";
private int year = -1;
private int mileage = -1;
private double price = -1.0;
public Car() {
carRegNr = idCode + (serNr++); // suteikiamas originalus carRegNr
}
public Car(String make, String model, int year, int mileage, double price) {
carRegNr = idCode + (serNr++); // suteikiamas originalus carRegNr
this.make = make;
this.model = model;
this.year = year;
this.mileage = mileage;
this.price = price;
validate();
}
public Car(String dataString) {
carRegNr = idCode + (serNr++); // suteikiamas originalus carRegNr
this.parse(dataString);
validate();
}
public Car(Builder builder) {
carRegNr = idCode + (serNr++); // suteikiamas originalus carRegNr
this.make = builder.make;
this.model = builder.model;
this.year = builder.year;
this.mileage = builder.mileage;
this.price = builder.price;
validate();
}
public Car create(String dataString) {
return new Car(dataString);
}
private void validate() {
String errorType = "";
if (year < minYear || year > currentYear) {
errorType = "Netinkami gamybos metai, turi būti ["
+ minYear + ":" + currentYear + "]";
}
if (price < minPrice || price > maxPrice) {
errorType += " Kaina už leistinų ribų [" + minPrice
+ ":" + maxPrice + "]";
}
if (!errorType.isEmpty()) {
Ks.ern("Automobilis yra blogai sugeneruotas: " + errorType + ". " + this);
}
}
@Override
public void parse(String dataString) {
try { // duomenys, atskirti tarpais
Scanner scanner = new Scanner(dataString);
make = scanner.next();
model = scanner.next();
year = scanner.nextInt();
setMileage(scanner.nextInt());
setPrice(scanner.nextDouble());
} catch (InputMismatchException e) {
Ks.ern("Blogas duomenų formatas -> " + dataString);
} catch (NoSuchElementException e) {
Ks.ern("Trūksta duomenų -> " + dataString);
}
}
@Override
public String toString() { // papildyta su carRegNr
return getCarRegNr() + "=" + make + "_" + model + ":" + year + " " + getMileage() + " " + String.format("%4.1f", price);
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getCarRegNr() { //** nauja.
return carRegNr;
}
@Override
public int compareTo(Car car) {
return getCarRegNr().compareTo(car.getCarRegNr());
}
public static Comparator<Car> byMake = (Car c1, Car c2) -> c1.make.compareTo(c2.make); // pradžioje pagal markes, o po to pagal modelius
public static Comparator<Car> byPrice = (Car c1, Car c2) -> {
// didėjanti tvarka, pradedant nuo mažiausios
if (c1.price < c2.price) {
return -1;
}
if (c1.price > c2.price) {
return +1;
}
return 0;
};
public static Comparator<Car> byYearPrice = (Car c1, Car c2) -> {
// metai mažėjančia tvarka, esant vienodiems lyginama kaina
if (c1.year > c2.year) {
return +1;
}
if (c1.year < c2.year) {
return -1;
}
if (c1.price > c2.price) {
return +1;
}
if (c1.price < c2.price) {
return -1;
}
return 0;
};
// Car klases objektų gamintojas (builder'is)
public static class Builder {
private final static Random RANDOM = new Random(1949); // Atsitiktinių generatorius
private final static String[][] MODELS = { // galimų automobilių markių ir modelių masyvas
{"Mazda", "3", "6", "CX-3", "MX-5"},
{"Ford", "Fiesta", "Kuga", "Focus", "Galaxy", "Mondeo"},
{"VW", "Golf", "Jetta", "Passat", "Tiguan"},
{"Honda", "HR-V", "CR-V", "Civic", "Jazz"},
{"Renault", "Clio", "Megane", "Twingo", "Scenic"},
{"Peugeot", "208", "308", "508", "Partner"},
{"Audi", "A3", "A4", "A6", "A8", "Q3", "Q5"}
};
private String make = "";
private String model = "";
private int year = -1;
private int mileage = -1;
private double price = -1.0;
public Car build() {
return new Car(this);
}
public Car buildRandom() {
int ma = RANDOM.nextInt(MODELS.length); // markės indeksas 0..
int mo = RANDOM.nextInt(MODELS[ma].length - 1) + 1;// modelio indeksas 1..
return new Car(MODELS[ma][0],
MODELS[ma][mo],
2000 + RANDOM.nextInt(22),// metai tarp 2000 ir 2021
6000 + RANDOM.nextInt(222000),// rida tarp 6000 ir 228000
800 + RANDOM.nextDouble() * 88000);// kaina tarp 800 ir 88800
}
public Builder year(int year) {
this.year = year;
return this;
}
public Builder make(String make) {
this.make = make;
return this;
}
public Builder model(String model) {
this.model = model;
return this;
}
public Builder mileage(int mileage) {
this.mileage = mileage;
return this;
}
public Builder price(double price) {
this.price = price;
return this;
}
}
}

View File

@ -0,0 +1,29 @@
package edu.ktu.ds.lab2.demo;
import edu.ktu.ds.lab2.utils.BstSet;
import edu.ktu.ds.lab2.utils.Set;
public class CarMarket {
public static Set<String> duplicateCarMakes(Car[] cars) {
Set<Car> uni = new BstSet<>(Car.byMake);
Set<String> duplicates = new BstSet<>();
for (Car car : cars) {
int sizeBefore = uni.size();
uni.add(car);
if (sizeBefore == uni.size()) {
duplicates.add(car.getMake());
}
}
return duplicates;
}
public static Set<String> uniqueCarModels(Car[] cars) {
Set<String> uniqueModels = new BstSet<>();
for (Car car : cars) {
uniqueModels.add(car.getModel());
}
return uniqueModels;
}
}

View File

@ -0,0 +1,80 @@
package edu.ktu.ds.lab2.demo;
import edu.ktu.ds.lab2.gui.ValidationException;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class CarsGenerator {
private int startIndex = 0, lastIndex = 0;
private boolean isStart = true;
private Car[] cars;
public Car[] generateShuffle(int setSize, double shuffleCoef) throws ValidationException {
return generateShuffle(setSize, setSize, shuffleCoef);
}
/**
* @param setSize
* @param setTake
* @param shuffleCoef
* @return Gražinamas setSize ilgio Automobilių masyvas
* @throws ValidationException
*/
public Car[] generateShuffle(int setSize,
int setTake,
double shuffleCoef) throws ValidationException {
Car[] cars = IntStream.range(0, setSize)
.mapToObj(i -> new Car.Builder().buildRandom())
.toArray(Car[]::new);
return shuffle(cars, setTake, shuffleCoef);
}
public Car takeCar() throws ValidationException {
if (lastIndex < startIndex) {
throw new ValidationException(String.valueOf(lastIndex - startIndex), 4);
}
// Vieną kartą Automobilis imamas masyvo pradžios, kitą kartą - galo.
isStart = !isStart;
return cars[isStart ? startIndex++ : lastIndex--];
}
private Car[] shuffle(Car[] cars, int amountToReturn, double shuffleCoef) throws ValidationException {
if (cars == null) {
throw new IllegalArgumentException("Automobilių nėra (null)");
}
if (amountToReturn <= 0) {
throw new ValidationException(String.valueOf(amountToReturn), 1);
}
if (cars.length < amountToReturn) {
throw new ValidationException(cars.length + " >= " + amountToReturn, 2);
}
if ((shuffleCoef < 0) || (shuffleCoef > 1)) {
throw new ValidationException(String.valueOf(shuffleCoef), 3);
}
int amountToLeave = cars.length - amountToReturn;
int startIndex = (int) (amountToLeave * shuffleCoef / 2);
Car[] takeToReturn = Arrays.copyOfRange(cars, startIndex, startIndex + amountToReturn);
Car[] takeToLeave = Stream
.concat(Arrays.stream(Arrays.copyOfRange(cars, 0, startIndex)),
Arrays.stream(Arrays.copyOfRange(cars, startIndex + amountToReturn, cars.length)))
.toArray(Car[]::new);
Collections.shuffle(Arrays.asList(takeToReturn)
.subList(0, (int) (takeToReturn.length * shuffleCoef)));
Collections.shuffle(Arrays.asList(takeToLeave)
.subList(0, (int) (takeToLeave.length * shuffleCoef)));
this.startIndex = 0;
this.lastIndex = takeToLeave.length - 1;
this.cars = takeToLeave;
return takeToReturn;
}
}

View File

@ -0,0 +1,13 @@
package edu.ktu.ds.lab2.demo;
import edu.ktu.ds.lab2.gui.MainWindow;
/*
* Darbo atlikimo tvarka - čia yra pradinė Swing GUI klasė.
*/
public class DemoExecution {
public static void main(String[] args) {
MainWindow.createAndShowGUI();
}
}

View File

@ -0,0 +1,150 @@
package edu.ktu.ds.lab2.demo;
import edu.ktu.ds.lab2.utils.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;
/*
* Aibės testavimas be Gui
* Dirbant su Intellij ir norint konsoleje matyti gražų pasuktą medį,
* reikia File -> Settings -> Editor -> File Encodings -> Global encoding pakeisti į UTF-8
*
*/
public class ManualTest {
static Car[] cars;
static ParsableSortedSet<Car> cSeries = new ParsableBstSet<>(Car::new, Car.byPrice);
public static void main(String[] args) throws CloneNotSupportedException {
Locale.setDefault(Locale.US); // Suvienodiname skaičių formatus
executeTest();
}
public static void executeTest() throws CloneNotSupportedException {
Car c1 = new Car("Renault", "Laguna", 2007, 50000, 1700);
Car c2 = new Car.Builder()
.make("Renault")
.model("Megane")
.year(2011)
.mileage(20000)
.price(3500)
.build();
Car c3 = new Car.Builder().buildRandom();
Car c4 = new Car("Renault Laguna 2011 115900 700");
Car c5 = new Car("Renault Megane 1946 365100 9500");
Car c6 = new Car("Honda Civic 2011 36400 80.3");
Car c7 = new Car("Renault Laguna 2011 115900 7500");
Car c8 = new Car("Renault Megane 1946 365100 950");
Car c9 = new Car("Honda Civic 2017 36400 850.3");
Car[] carsArray = {c9, c7, c8, c5, c1, c6};
Ks.oun("Auto Aibė:");
ParsableSortedSet<Car> carsSet = new ParsableBstSet<>(Car::new);
for (Car c : carsArray) {
carsSet.add(c);
Ks.oun("Aibė papildoma: " + c + ". Jos dydis: " + carsSet.size());
}
Ks.oun("");
Ks.oun(carsSet.toVisualizedString());
ParsableSortedSet<Car> carsSetCopy = (ParsableSortedSet<Car>) carsSet.clone();
carsSetCopy.add(c2);
carsSetCopy.add(c3);
carsSetCopy.add(c4);
Ks.oun("Papildyta autoaibės kopija:");
Ks.oun(carsSetCopy.toVisualizedString());
c9.setMileage(10000);
Ks.oun("Originalas:");
Ks.ounn(carsSet.toVisualizedString());
Ks.oun("Ar elementai egzistuoja aibėje?");
for (Car c : carsArray) {
Ks.oun(c + ": " + carsSet.contains(c));
}
Ks.oun(c2 + ": " + carsSet.contains(c2));
Ks.oun(c3 + ": " + carsSet.contains(c3));
Ks.oun(c4 + ": " + carsSet.contains(c4));
Ks.oun("");
Ks.oun("Ar elementai egzistuoja aibės kopijoje?");
for (Car c : carsArray) {
Ks.oun(c + ": " + carsSetCopy.contains(c));
}
Ks.oun(c2 + ": " + carsSetCopy.contains(c2));
Ks.oun(c3 + ": " + carsSetCopy.contains(c3));
Ks.oun(c4 + ": " + carsSetCopy.contains(c4));
Ks.oun("");
Ks.oun("Automobilių aibė su iteratoriumi:");
Ks.oun("");
for (Car c : carsSet) {
Ks.oun(c);
}
Ks.oun("");
Ks.oun("Automobilių aibė AVL-medyje:");
ParsableSortedSet<Car> carsSetAvl = new ParsableAvlSet<>(Car::new);
for (Car c : carsArray) {
carsSetAvl.add(c);
}
Ks.ounn(carsSetAvl.toVisualizedString());
Ks.oun("Automobilių aibė su iteratoriumi:");
Ks.oun("");
for (Car c : carsSetAvl) {
Ks.oun(c);
}
Ks.oun("");
Ks.oun("Automobilių aibė su atvirkštiniu iteratoriumi:");
Ks.oun("");
Iterator<Car> iter = carsSetAvl.descendingIterator();
while (iter.hasNext()) {
Ks.oun(iter.next());
}
Ks.oun("");
Ks.oun("Automobilių aibės toString() metodas:");
Ks.ounn(carsSetAvl);
// Išvalome ir suformuojame aibes skaitydami failo
carsSet.clear();
carsSetAvl.clear();
Ks.oun("");
Ks.oun("Automobilių aibė DP-medyje:");
carsSet.load("data\\ban.txt");
Ks.ounn(carsSet.toVisualizedString());
Ks.oun("Išsiaiškinkite, kodėl medis augo tik į vieną pusę.");
Ks.oun("");
Ks.oun("Automobilių aibė AVL-medyje:");
carsSetAvl.load("data\\ban.txt");
Ks.ounn(carsSetAvl.toVisualizedString());
Set<String> carsSet4 = CarMarket.duplicateCarMakes(carsArray);
Ks.oun("Pasikartojančios automobilių markės:\n" + carsSet4);
Set<String> carsSet5 = CarMarket.uniqueCarModels(carsArray);
Ks.oun("Unikalūs automobilių modeliai:\n" + carsSet5);
}
static ParsableSortedSet<Car> generateSet(int kiekis, int generN) {
cars = new Car[generN];
for (int i = 0; i < generN; i++) {
cars[i] = new Car.Builder().buildRandom();
}
Collections.shuffle(Arrays.asList(cars));
cSeries.clear();
Arrays.stream(cars).limit(kiekis).forEach(cSeries::add);
return cSeries;
}
}

View File

@ -0,0 +1,67 @@
package edu.ktu.ds.lab2.gui;
import javax.swing.*;
import java.awt.*;
/**
* Klasė, skirta duomenų išvedimui į GUI
*
* @author darius
*/
public class KsGui {
private static int lineNr;
private static boolean formatStartOfLine = true;
public static void setFormatStartOfLine(boolean formatStartOfLine) {
KsGui.formatStartOfLine = formatStartOfLine;
}
private static String getStartOfLine() {
return (formatStartOfLine) ? ++lineNr + "| " : "";
}
public static void oun(JTextArea ta, Object o) {
ou(ta, o);
ta.append(System.lineSeparator());
}
public static void ou(JTextArea ta, Object o) {
if (o instanceof Iterable) {
for (Object iterable : (Iterable) o) {
ta.append(iterable.toString() + System.lineSeparator());
}
} else {
ta.append(o.toString());
}
}
public static void ou(JTextArea ta, Object o, String msg) {
ta.append(getStartOfLine() + msg + ": ");
oun(ta, o);
}
public static void oun(JTextArea ta, Object o, String msg) {
ta.append(getStartOfLine() + msg + ": " + System.lineSeparator());
oun(ta, o);
}
public static void ounerr(JTextArea ta, Exception e) {
ta.setBackground(Color.pink);
ta.append(getStartOfLine() + e.toString() + System.lineSeparator());
for (StackTraceElement ste : e.getStackTrace()) {
ta.append(ste.toString() + System.lineSeparator());
}
ta.append(System.lineSeparator());
}
public static void ounerr(JTextArea ta, String msg) {
ta.setBackground(Color.pink);
ta.append(getStartOfLine() + msg + ". " + System.lineSeparator());
}
public static void ounerr(JTextArea ta, String msg, String parameter) {
ta.setBackground(Color.pink);
ta.append(getStartOfLine() + msg + ": " + parameter + System.lineSeparator());
}
}

View File

@ -0,0 +1,445 @@
package edu.ktu.ds.lab2.gui;
import edu.ktu.ds.lab2.demo.Car;
import edu.ktu.ds.lab2.demo.CarsGenerator;
import edu.ktu.ds.lab2.utils.Ks;
import edu.ktu.ds.lab2.utils.ParsableAvlSet;
import edu.ktu.ds.lab2.utils.ParsableBstSet;
import edu.ktu.ds.lab2.utils.ParsableSortedSet;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.stream.IntStream;
/**
* Lab2 langas su Swing'u
* <pre>
* MainWindow (BorderLayout)
* |-----------------------Center-------------------------|
* | |-----------------scrollOutput-------------------| |
* | | |------------------------------------------| | |
* | | | | | |
* | | | | | |
* | | | taOutput | | |
* | | | | | |
* | | | | | |
* | | | | | |
* | | | | | |
* | | | | | |
* | | |------------------------------------------| | | | |
* | |------------------------------------------------| | |
* |------------------------South-------------------------|
* | |~~~~~~~~~~~~~~~~~~~scrollSouth~~~~~~~~~~~~~~~~~~| |
* | | | |
* | | |------------||-----------||-----------| | |
* | | | panButtons || panParam1 || panParam2 | | |
* | | | || || | | |
* | | |------------||-----------||-----------| | |
* | | | |
* | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| |
* |------------------------------------------------------|
* </pre>
*
* @author darius.matulis@ktu.lt
*/
public class MainWindow extends JFrame implements ActionListener {
private static final ResourceBundle MESSAGES = ResourceBundle.getBundle("edu.ktu.ds.lab2.gui.messages");
private static final int TF_WIDTH = 8;
private final JTextArea taOutput = new JTextArea();
private final JScrollPane scrollOutput = new JScrollPane(taOutput);
private final JTextField tfInput = new JTextField();
private final JComboBox<String> cmbTreeType = new JComboBox<>();
private final JPanel panSouth = new JPanel();
private final JScrollPane scrollSouth = new JScrollPane(panSouth);
private final JPanel panParam2 = new JPanel();
private MainWindowMenu mainWindowMenu;
private Panels panParam1, panButtons;
private static ParsableSortedSet<Car> carsSet;
private final CarsGenerator carsGenerator = new CarsGenerator();
private int sizeOfInitialSubSet, sizeOfGenSet, sizeOfLeftSubSet;
private double shuffleCoef;
private final String[] errors;
public MainWindow() {
errors = new String[]{
MESSAGES.getString("badSetSize"),
MESSAGES.getString("badInitialData"),
MESSAGES.getString("badSetSizes"),
MESSAGES.getString("badShuffleCoef")
};
initComponents();
}
private void initComponents() {
// Kad prijungiant tekstą prie JTextArea vaizdas visada nušoktų į apačią
scrollOutput.getVerticalScrollBar()
.addAdjustmentListener((AdjustmentEvent e) -> taOutput.select(taOutput.getCaretPosition() * taOutput.getFont().getSize(), 0));
//======================================================================
// Formuojamas mygtukų tinklelis (mėlynas). Naudojame klasę Panels.
//======================================================================
// 4 eilutes, 2 stulpeliai
panButtons = new Panels(
new String[]{
MESSAGES.getString("button1"),
MESSAGES.getString("button2"),
MESSAGES.getString("button3"),
MESSAGES.getString("button4"),
MESSAGES.getString("button5"),
MESSAGES.getString("button6")},
2, 3);
panButtons.getButtons().forEach((btn) -> btn.addActionListener(this));
enableButtons(false);
//======================================================================
// Formuojama pirmoji parametrų lentelė (žalia). Naudojame klasę Panels.
//======================================================================
panParam1 = new Panels(
new String[]{
MESSAGES.getString("lblParam11"),
MESSAGES.getString("lblParam12"),
MESSAGES.getString("lblParam13"),
MESSAGES.getString("lblParam14"),
MESSAGES.getString("lblParam15")},
new String[]{
MESSAGES.getString("tfParam11"),
MESSAGES.getString("tfParam12"),
MESSAGES.getString("tfParam13"),
MESSAGES.getString("tfParam14"),
MESSAGES.getString("tfParam15")},
TF_WIDTH);
//======================================================================
// Formuojama antroji parametrų lentelė (gelsva).
//======================================================================
panParam2.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(3, 6, 3, 4);
// Išlygiavimas į kairę
c.anchor = GridBagConstraints.WEST;
// Komponentų išplėtimas iki maksimalaus celės dydžio
c.fill = GridBagConstraints.BOTH;
// Pirmas stulpelis
c.gridx = 0;
panParam2.add(new JLabel(MESSAGES.getString("lblParam21")), c);
panParam2.add(new JLabel(MESSAGES.getString("lblParam23")), c);
// Antras stulpelis
c.gridx = 1;
for (String s : new String[]{
MESSAGES.getString("cmbTreeType1"),
MESSAGES.getString("cmbTreeType2"),
MESSAGES.getString("cmbTreeType3")
}) {
cmbTreeType.addItem(s);
}
cmbTreeType.addActionListener(this);
panParam2.add(cmbTreeType, c);
// Vėl pirmas stulpelis, tačiau plotis - 2 celės
c.gridx = 0;
c.gridwidth = 2;
tfInput.setEditable(false);
tfInput.setBackground(Color.lightGray);
panParam2.add(tfInput, c);
//======================================================================
// Formuojamas bendras parametrų skydelis (tamsiai pilkas).
//======================================================================
panSouth.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
panSouth.add(panButtons);
panSouth.add(panParam1);
panSouth.add(panParam2);
mainWindowMenu = new MainWindowMenu() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
Object command = ae.getSource();
if (command.equals(mainWindowMenu.getMenu(0).getItem(0))) {
fileChooseMenu();
} else if (command.equals(mainWindowMenu.getMenu(0).getItem(1))) {
KsGui.ounerr(taOutput, MESSAGES.getString("notImplemented"));
} else if (command.equals(mainWindowMenu.getMenu(0).getItem(3))) {
System.exit(0);
} else if (command.equals(mainWindowMenu.getMenu(1).getItem(0))) {
JOptionPane.showOptionDialog(this,
MESSAGES.getString("author"),
MESSAGES.getString("menuItem21"),
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
new String[]{"OK"},
null);
}
} catch (ValidationException e) {
KsGui.ounerr(taOutput, e.getMessage());
} catch (Exception e) {
KsGui.ounerr(taOutput, MESSAGES.getString("systemError"));
e.printStackTrace(System.out);
}
}
};
// Meniu juosta patalpinama lange
setJMenuBar(mainWindowMenu);
//======================================================================
// Formuojamas Lab2 langas
//======================================================================
JPanel mainWindow = new JPanel();
mainWindow.setLayout(new BorderLayout());
// ..centre ir pietuose talpiname objektus..
mainWindow.add(scrollOutput, BorderLayout.CENTER);
mainWindow.add(scrollSouth, BorderLayout.SOUTH);
// Šio freimo "turinyje" talpinamas Lab2 skydelis
getContentPane().add(mainWindow);
appearance();
}
private void appearance() {
// Grafinių objektų rėmeliai
TitledBorder outputBorder = new TitledBorder(MESSAGES.getString("border1"));
outputBorder.setTitleFont(new Font(Font.SANS_SERIF, Font.BOLD, 11));
scrollOutput.setBorder(outputBorder);
TitledBorder southBorder = new TitledBorder(MESSAGES.getString("border2"));
southBorder.setTitleFont(new Font(Font.SANS_SERIF, Font.BOLD, 11));
scrollSouth.setBorder(southBorder);
panParam2.setBackground(new Color(255, 255, 153));// Gelsva
panParam1.setBackground(new Color(204, 255, 204));// Šviesiai žalia
panParam1.getTfOfTable().get(2).setEditable(false);
panParam1.getTfOfTable().get(2).setForeground(Color.red);
panParam1.getTfOfTable().get(4).setEditable(false);
panParam1.getTfOfTable().get(4).setBackground(Color.lightGray);
panButtons.setBackground(new Color(112, 162, 255)); // Blyškiai mėlyna
panSouth.setBackground(Color.GRAY);
taOutput.setFont(Font.decode("courier new-12"));
taOutput.setEditable(false);
}
@Override
public void actionPerformed(ActionEvent ae) {
try {
System.gc();
System.gc();
System.gc();
taOutput.setBackground(Color.white);
Object source = ae.getSource();
if (source instanceof JButton) {
handleButtons(source);
} else if (source instanceof JComboBox && source.equals(cmbTreeType)) {
enableButtons(false);
}
} catch (ValidationException e) {
if (e.getCode() >= 0 && e.getCode() <= 3) {
KsGui.ounerr(taOutput, errors[e.getCode()] + ": " + e.getMessage());
if (e.getCode() == 2) {
panParam1.getTfOfTable().get(0).setBackground(Color.red);
panParam1.getTfOfTable().get(1).setBackground(Color.red);
}
} else if (e.getCode() == 4) {
KsGui.ounerr(taOutput, MESSAGES.getString("allSetIsPrinted"));
} else {
KsGui.ounerr(taOutput, e.getMessage());
}
} catch (UnsupportedOperationException e) {
KsGui.ounerr(taOutput, e.getLocalizedMessage());
} catch (Exception e) {
KsGui.ounerr(taOutput, MESSAGES.getString("systemError"));
e.printStackTrace(System.out);
}
}
private void handleButtons(Object source) throws ValidationException {
if (source.equals(panButtons.getButtons().get(0))) {
treeGeneration(null);
} else if (source.equals(panButtons.getButtons().get(1))) {
treeIteration();
} else if (source.equals(panButtons.getButtons().get(2))) {
treeAdd();
} else if (source.equals(panButtons.getButtons().get(3))) {
treeRemove();
} else if (source.equals(panButtons.getButtons().get(4))
|| source.equals(panButtons.getButtons().get(5))) {
KsGui.setFormatStartOfLine(true);
KsGui.ounerr(taOutput, MESSAGES.getString("notImplemented"));
KsGui.setFormatStartOfLine(false);
}
}
public void treeGeneration(String filePath) throws ValidationException {
// Nuskaitomi uždavinio parametrai
readTreeParameters();
// Sukuriamas aibės objektas, priklausomai nuo medžio pasirinkimo
// cmbTreeType objekte
createTree();
Car[] carsArray;
// Jei failas nenurodytas - generuojama
if (filePath == null) {
carsArray = carsGenerator.generateShuffle(sizeOfGenSet, sizeOfInitialSubSet, shuffleCoef);
panParam1.getTfOfTable().get(2).setText(String.valueOf(sizeOfLeftSubSet));
} else { // Skaitoma is failo
carsSet.load(filePath);
carsArray = new Car[carsSet.size()];
int i = 0;
for (Object o : carsSet.toArray()) {
carsArray[i++] = (Car) o;
}
// Skaitant failo išmaišoma standartiniu Collections.shuffle metodu.
Collections.shuffle(Arrays.asList(carsArray), new Random());
}
// Išmaišyto masyvo elementai surašomi i aibę
carsSet.clear();
Arrays.stream(carsArray).forEach(a -> carsSet.add(a));
// Išvedami rezultatai
// Nustatoma, kad eilutės pradžioje neskaičiuotų išvedamų eilučių skaičiaus
KsGui.setFormatStartOfLine(true);
KsGui.oun(taOutput, carsSet.toVisualizedString(),
MESSAGES.getString("setInTree"));
// Nustatoma, kad eilutės pradžioje skaičiuotų išvedamų eilučių skaičių
KsGui.setFormatStartOfLine(false);
enableButtons(true);
}
private void treeAdd() throws ValidationException {
KsGui.setFormatStartOfLine(true);
Car car = carsGenerator.takeCar();
carsSet.add(car);
panParam1.getTfOfTable().get(2).setText(String.valueOf(--sizeOfLeftSubSet));
KsGui.setFormatStartOfLine(true);
KsGui.oun(taOutput, car, MESSAGES.getString("setAdd"));
KsGui.oun(taOutput, carsSet.toVisualizedString());
KsGui.setFormatStartOfLine(false);
}
private void treeRemove() {
KsGui.setFormatStartOfLine(true);
if (carsSet.isEmpty()) {
KsGui.ounerr(taOutput, MESSAGES.getString("setIsEmpty"));
} else {
int nr = new Random().nextInt(carsSet.size());
Car auto = (Car) carsSet.toArray()[nr];
carsSet.remove(auto);
KsGui.oun(taOutput, auto, MESSAGES.getString("setRemoval"));
panParam1.getTfOfTable().get(2).setText(String.valueOf(++sizeOfLeftSubSet));
}
KsGui.oun(taOutput, carsSet.toVisualizedString());
KsGui.setFormatStartOfLine(false);
}
private void treeIteration() {
KsGui.setFormatStartOfLine(true);
if (carsSet.isEmpty()) {
KsGui.ounerr(taOutput, MESSAGES.getString("setIsEmpty"));
} else {
KsGui.oun(taOutput, carsSet, MESSAGES.getString("setIterator"));
}
KsGui.setFormatStartOfLine(false);
}
private void readTreeParameters() throws ValidationException {
// Truputėlis kosmetikos..
for (int i = 0; i < 2; i++) {
panParam1.getTfOfTable().get(i).setBackground(Color.WHITE);
}
// Nuskaitomos parametrų reiksmės. Jei konvertuojant is String
// įvyksta klaida, sugeneruojama NumberFormatException situacija. Tam, kad
// atskirti kuriame JTextfield'e ivyko klaida, panaudojama nuosava
// situacija MyException
int i = 0;
try {
// Pakeitimas (replace) tam, kad sukelti situaciją esant
// neigiamam skaičiui
sizeOfGenSet = Integer.parseInt(panParam1.getParametersOfTable().get(i).replace("-", "x"));
sizeOfInitialSubSet = Integer.parseInt(panParam1.getParametersOfTable().get(++i).replace("-", "x"));
sizeOfLeftSubSet = sizeOfGenSet - sizeOfInitialSubSet;
++i;
shuffleCoef = Double.parseDouble(panParam1.getParametersOfTable().get(++i).replace("-", "x"));
} catch (NumberFormatException e) {
// Galima ir taip: pagauti exception'ą ir vėl mesti
throw new ValidationException(panParam1.getParametersOfTable().get(i), e, i);
}
}
private void createTree() throws ValidationException {
switch (cmbTreeType.getSelectedIndex()) {
case 0:
carsSet = new ParsableBstSet<>(Car::new);
break;
case 1:
carsSet = new ParsableAvlSet<>(Car::new);
break;
default:
enableButtons(false);
throw new ValidationException(MESSAGES.getString("notImplemented"));
}
}
private void enableButtons(boolean enable) {
IntStream.rangeClosed(1, 5)
.filter(i -> i < panButtons.getButtons().size() && panButtons.getButtons().get(i) != null)
.forEachOrdered(i -> panButtons.getButtons().get(i).setEnabled(enable));
}
private void fileChooseMenu() throws ValidationException {
JFileChooser fc = new JFileChooser(".");
// Nuimamas "all Files" filtras
// fc.setAcceptAllFileFilterUsed(false);
// Papildoma mūsų sukurtais filtrais
fc.addChoosableFileFilter(new javax.swing.filechooser.FileFilter() {
@Override
public boolean accept(File file) {
String filename = file.getName();
// Rodomos tik direktorijos ir txt failai
return file.isDirectory() || filename.endsWith(".txt");
}
@Override
public String getDescription() {
return "*.txt";
}
});
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
treeGeneration(file.getAbsolutePath());
}
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()
// Arba sitaip, tada swing komponentu isvaizda priklausys
// nuo naudojamos OS:
// UIManager.getSystemLookAndFeelClassName()
// Arba taip:
// "com.sun.java.swing.plaf.motif.MotifLookAndFeel"
// Linux'e dar taip:
// "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"
);
UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
Ks.ou(ex.getMessage());
}
MainWindow window = new MainWindow();
window.setLocation(50, 50);
window.setIconImage(new ImageIcon(MESSAGES.getString("icon")).getImage());
window.setTitle(MESSAGES.getString("title"));
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setPreferredSize(new Dimension(1100, 650));
window.pack();
window.setVisible(true);
}
}

View File

@ -0,0 +1,56 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.ktu.ds.lab2.gui;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.ResourceBundle;
/**
* @author darius
*/
public abstract class MainWindowMenu extends JMenuBar implements ActionListener {
private static final ResourceBundle MESSAGES = ResourceBundle.getBundle("edu.ktu.ds.lab2.gui.messages");
public MainWindowMenu() {
initComponents();
}
private void initComponents() {
// Sukuriama meniu juosta
JMenu jMenu1 = new JMenu(MESSAGES.getString("menu1"));
super.add(jMenu1);
JMenuItem jMenuItem11 = new JMenuItem(MESSAGES.getString("menuItem11"));
jMenuItem11.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK));
JMenuItem jMenuItem12 = new JMenuItem(MESSAGES.getString("menuItem12"));
jMenuItem12.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK));
JMenuItem jMenuItem13 = new JMenuItem(MESSAGES.getString("menuItem13"));
jMenuItem13.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK));
jMenu1.add(jMenuItem11);
jMenu1.add(jMenuItem12);
jMenu1.addSeparator();
jMenu1.add(jMenuItem13);
JMenu jMenu2 = new JMenu(MESSAGES.getString("menu2"));
super.add(jMenu2);
JMenuItem jMenuItem21 = new JMenuItem(MESSAGES.getString("menuItem21"));
jMenuItem21.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, InputEvent.SHIFT_DOWN_MASK));
jMenu2.add(jMenuItem21);
jMenuItem11.addActionListener(this);
jMenuItem12.addActionListener(this);
jMenuItem13.addActionListener(this);
jMenuItem21.addActionListener(this);
}
@Override
public abstract void actionPerformed(ActionEvent e);
}

View File

@ -0,0 +1,148 @@
package edu.ktu.ds.lab2.gui;
import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.util.List;
import java.util.Queue;
import java.util.*;
import java.util.stream.Collectors;
/**
* Klasės objektu galima sukurti du panelius: parametrų lentelę ir mygtukų
* tinklelį. Panelyje talpinamų objektų kiekis nustatomas parametrais.
*
* @author darius.matulis@ktu.lt
*/
public class Panels extends JPanel {
private final static int SPACING = 4;
private final List<JTextField> tfs = new ArrayList<>();
private final List<JButton> btns = new ArrayList<>();
/**
* Sukuriama parametrų lentelė (GridBag išdėstymo dėsnis)
* <pre>
* |-------------------------------|
* | |------------| |
* | lblTexts[0] | tfTexts[0] | |
* | |------------| |
* | |
* | |------------| |
* | lblTexts[1] | tfTexts[1] | |
* | |------------| |
* | ... ... |
* |-------------------------------|
* </pre>
*
* @param lblTexts
* @param tfTexts
* @param columnWidth
*/
public Panels(String[] lblTexts, String[] tfTexts, int columnWidth) {
super();
if (lblTexts == null || tfTexts == null) {
throw new IllegalArgumentException("Arguments for table of parameters are incorrect");
}
if (lblTexts.length > tfTexts.length) {
tfTexts = Arrays.copyOf(tfTexts, lblTexts.length);
Arrays.fill(tfTexts, "");
}
initTableOfParameters(columnWidth, lblTexts, tfTexts);
}
/**
* Sukuriamas mygtukų tinklelis (GridLayout išdėstymo dėsnis)
* <pre>
* |-------------------------------------|
* | |-------------| |-------------| |
* | | btnNames[0] | | btnNames[1] | ... |
* | |-------------| |-------------| |
* | |
* | |-------------| |-------------| |
* | | btnNames[2] | | btnNames[3] | ... |
* | |-------------| |-------------| |
* | ... ... |
* |-------------------------------------|
* </pre>
*
* @param btnNames
* @param gridX
* @param gridY
*/
public Panels(String[] btnNames, int gridX, int gridY) {
super();
if (btnNames == null || gridX < 1 || gridY < 1) {
throw new IllegalArgumentException("Arguments for buttons grid are incorrect");
}
initGridOfButtons(gridX, gridY, btnNames);
}
private void initTableOfParameters(int columnWidth, String[] lblTexts, String[] tfTexts) {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Spacing'as tarp komponentų
c.insets = new Insets(SPACING, SPACING, SPACING, SPACING);
// Lygiavimas į kairę
c.anchor = GridBagConstraints.WEST;
// Pasirenkamas pirmas stulpelis..
c.gridx = 0;
// ..ir į sudedami labeliai
Arrays.stream(lblTexts).forEach((lblText) -> add(new JLabel(lblText), c));
// Pasirenkamas antras stulpelis..
c.gridx = 1;
// ..ir į sudedami textfieldai
for (String tfText : tfTexts) {
JTextField tf = new JTextField(tfText, columnWidth);
tf.setHorizontalAlignment(JTextField.CENTER);
tf.setBackground(Color.WHITE);
tfs.add(tf);
add(tf, c);
}
}
private void initGridOfButtons(int gridX, int gridY, String[] btnNames) {
setLayout(new GridLayout(gridY, gridX, SPACING, SPACING));
Queue<String> btnNamesQueue = new LinkedList<>(Arrays.asList(btnNames));
for (int i = 0; i < gridX; i++) {
for (int j = 0; j < gridY; j++) {
if (btnNamesQueue.isEmpty()) {
break;
}
JButton button = new JButton(btnNamesQueue.poll());
btns.add(button);
add(button);
}
}
}
/**
* Gražinamas parametrų lentelės parametrų sąrašas
*
* @return Gražinamas parametrų lentelės parametrų sąrašas
*/
public List<String> getParametersOfTable() {
return tfs.stream().map(JTextComponent::getText).collect(Collectors.toList());
}
/**
* Gražinamas parametrų lentelės JTextField objektų sąrašas
*
* @return Gražinamas parametrų lentelės JTextField objektų sąrašas
*/
public List<JTextField> getTfOfTable() {
return tfs;
}
/**
* Gražinamas mygtukų tinklelio JButton objektų sąrašas
*
* @return Gražinamas mygtukų tinklelio JButton objektų sąrašas
*/
public List<JButton> getButtons() {
return btns;
}
}

View File

@ -0,0 +1,41 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.ktu.ds.lab2.gui;
/**
* Nuosava situacija, panaudota dialogo struktūrose įvedamų parametrų
* tikrinimui.
*/
public class ValidationException extends RuntimeException {
// Situacijos kodas. Pagal ji programuojama programos reakcija į situaciją
private final int code;
public ValidationException(String text) {
// (-1) - susitariama, kad tai neutralus kodas.
this(text, -1);
}
public ValidationException(String message, int code) {
super(message);
if (code < -1) {
throw new IllegalArgumentException("Illegal code in Validation Exception: " + code);
}
this.code = code;
}
public ValidationException(String message, Throwable throwable, int code) {
super(message, throwable);
if (code < -1) {
throw new IllegalArgumentException("Illegal code in MyException: " + code);
}
this.code = code;
}
public int getCode() {
return code;
}
}

View File

@ -0,0 +1,41 @@
package edu.ktu.ds.lab2.optional1;
import edu.ktu.ds.lab2.utils.BstSet;
public class Main {
public static void main(String[] args) {
int k = 2;
BstSet<Integer> set = new BstSet<>();
BstSet.BstNode<Integer> a = set.getRoot();
set.add(15);
set.add(23);
set.add(7);
set.add(4);
set.add(1);
set.add(9);
System.out.println(set.toVisualizedString());
System.out.println(IsBalanced(set.getRoot(), k) != -1);
}
public static <E> int IsBalanced(BstSet.BstNode<E> node, int maxBalance) {
if (node.left == null && node.right == null) return 0;
int leftHeight = -1;
int rightHeight = -1;
if (node.left != null) {
leftHeight = IsBalanced(node.left, maxBalance);
if (leftHeight == -1) return -1;
}
if (node.right != null) {
rightHeight = IsBalanced(node.right, maxBalance);
if (rightHeight == -1) return -1;
}
if (Math.abs(leftHeight - rightHeight) >= maxBalance) return -1;
return Math.max(leftHeight, rightHeight) + 1;
}
}

View File

@ -0,0 +1,86 @@
package edu.ktu.ds.lab2.optional2;
import edu.ktu.ds.lab2.utils.BstSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
BstSet<Integer> set = new BstSet<>();
set.add(15);
set.add(23);
set.add(7);
set.add(4);
set.add(12);
set.add(19);
set.add(26);
set.add(1);
set.add(5);
set.add(9);
set.add(14);
set.add(16);
set.add(21);
set.add(25);
set.add(30);
System.out.println(set.toVisualizedString());
System.out.println(getInnerValues(set));
}
public static <E extends Comparable<E>> ArrayList<E> getInnerValues(BstSet<E> set) {
HashSet<E> excludedValues = new HashSet<>();
excludedValues.addAll(getLeftEdge(set));
excludedValues.addAll(getRightEdge(set));
excludedValues.addAll(getBottomEdge(set));
ArrayList<E> innerValues = new ArrayList<>();
for (E value : set) {
if (!excludedValues.contains(value)) {
innerValues.add(value);
}
}
return innerValues;
}
public static <E extends Comparable<E>> ArrayList<E> getLeftEdge(BstSet<E> set) {
ArrayList<E> leftEdge = new ArrayList<>();
BstSet.BstNode<E> node = set.getRoot();
while (node != null) {
leftEdge.add(node.element);
node = node.left;
}
return leftEdge;
}
public static <E extends Comparable<E>> ArrayList<E> getRightEdge(BstSet<E> set) {
ArrayList<E> rightEdge = new ArrayList<>();
BstSet.BstNode<E> node = set.getRoot();
while (node != null) {
rightEdge.add(node.element);
node = node.right;
}
return rightEdge;
}
public static <E extends Comparable<E>> ArrayList<E> getBottomEdge(BstSet<E> set) {
ArrayList<E> bottomEdge = new ArrayList<>();
Stack<BstSet.BstNode<E>> stack = new Stack<>();
stack.add(set.getRoot());
while (!stack.isEmpty()) {
BstSet.BstNode<E> node = stack.pop();
if (node.left == null && node.right == null) {
bottomEdge.add(node.element);
} else {
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
}
return bottomEdge;
}
}

View File

@ -0,0 +1,236 @@
package edu.ktu.ds.lab2.utils;
import java.util.Comparator;
/**
* Rikiuojamos objektų kolekcijos - aibės realizacija AVL-medžiu.
*
* @param <E> Aibės elemento tipas. Turi tenkinti interfeisą Comparable<E>, arba
* per klasės konstruktorių turi būti paduodamas Comparator<E>
* interfeisą tenkinantis objektas.
* @author darius.matulis@ktu.lt
* @užduotis Peržiūrėkite ir išsiaiškinkite pateiktus metodus.
*/
public class AvlSet<E extends Comparable<E>> extends BstSet<E> implements SortedSet<E> {
public AvlSet() {
}
public AvlSet(Comparator<? super E> c) {
super(c);
}
/**
* Aibė papildoma nauju elementu.
*
* @param element
*/
@Override
public void add(E element) {
if (element == null) {
throw new IllegalArgumentException("Element is null in add(E element)");
}
root = addRecursive(element, (AVLNode<E>) root);
}
/**
* Privatus rekursinis metodas naudojamas add metode;
*
* @param element
* @param node
* @return
*/
private AVLNode<E> addRecursive(E element, AVLNode<E> node) {
if (node == null) {
size++;
return new AVLNode<>(element);
}
int cmp = c.compare(element, node.element);
if (cmp < 0) {
node.left = addRecursive(element, (AVLNode<E>) node.left);
} else if (cmp > 0) {
node.right = addRecursive(element, (AVLNode<E>) node.right);
}
if (cmp != 0) {
int balance = getBalance(node);
if (balance >= 2) {
int cmp2 = c.compare(element, node.left.element);
node = (cmp2 < 0) ? rightRotation(node) : doubleRightRotation(node);
} else if (balance <= -2) {
int cmp2 = c.compare(node.right.element, element);
node = (cmp2 < 0) ? leftRotation(node) : doubleLeftRotation(node);
}
}
node.updateHeight();
return node;
}
/**
* Pašalinamas elementas aibės.
*
* @param element
*/
@Override
public void remove(E element) {
if (element == null) {
throw new IllegalArgumentException("Element is null in remove(E element)");
}
root = removeRecursive(element, (AVLNode<E>) root);
}
private int getBalance(AVLNode<E> node) {
if (node == null) return 0;
return height((AVLNode<E>) node.left) - height((AVLNode<E>) node.right);
}
private AVLNode<E> removeRecursive(E element, AVLNode<E> node) {
if (node == null) return null;
int cmp = c.compare(element, node.element);
if (cmp < 0) {
node.left = removeRecursive(element, (AVLNode<E>) node.left);
} else if (cmp > 0) {
node.right = removeRecursive(element, (AVLNode<E>) node.right);
} else {
size--;
if (node.left == null && node.right == null) {
node = null;
} else if (node.left != null && node.right != null) {
if (node.right.left != null) {
BstNode<E> minimumParent = node;
BstNode<E> minimumNode = node.right;
while (minimumNode.left != null) {
minimumParent = minimumNode;
minimumNode = minimumNode.left;
}
minimumParent.left = minimumNode.right;
node.element = minimumNode.element;
} else {
node.element = node.right.element;
node.right = node.right.right;
}
} else if (node.left != null) {
node = (AVLNode<E>) node.left;
} else { // if (node.right != null)
node = (AVLNode<E>) node.right;
}
}
if (node != null) {
node.updateHeight();
if (cmp != 0) {
int balance = getBalance(node);
if (balance >= 2) {
int hl = node.left.left != null ? ((AVLNode<E>) node.left.left).height : -1;
int hr = node.left.right != null ? ((AVLNode<E>) node.left.right).height : -1;
node = (hl >= hr) ? rightRotation(node) : doubleRightRotation(node);
} else if (balance <= -2) {
int hl = node.right.left != null ? ((AVLNode<E>) node.right.left).height : -1;
int hr = node.right.right != null ? ((AVLNode<E>) node.right.right).height : -1;
node = (hr >= hl) ? leftRotation(node) : doubleLeftRotation(node);
}
}
}
return node;
}
// Papildomi privatūs metodai, naudojami operacijų su aibe realizacijai
// AVL-medžiu;
// n2
// / n1
// n1 ==> / \
// / n3 n2
// n3
private AVLNode<E> rightRotation(AVLNode<E> n2) {
AVLNode<E> n1 = (AVLNode<E>) n2.left;
n2.left = n1.right;
n1.right = n2;
n2.updateHeight();
n1.updateHeight();
return n1;
}
private AVLNode<E> leftRotation(AVLNode<E> n1) {
AVLNode<E> n2 = (AVLNode<E>) n1.right;
n1.right = n2.left;
n2.left = n1;
n1.updateHeight();
n2.updateHeight();
return n2;
}
// n3 n3
// / / n2
// n1 ==> n2 ==> / \
// \ / n1 n3
// n2 n1
//
private AVLNode<E> doubleRightRotation(AVLNode<E> n3) {
n3.left = leftRotation((AVLNode<E>) n3.left);
return rightRotation(n3);
}
private AVLNode<E> doubleLeftRotation(AVLNode<E> n1) {
n1.right = rightRotation((AVLNode<E>) n1.right);
return leftRotation(n1);
}
public String serialize() {
return serialize((AVLNode<E>) root);
}
private String serialize(AVLNode<E> node) {
StringBuilder builder = new StringBuilder();
if (node.left == null && node.right == null) {
builder.append(node.element);
} else {
builder.append("(");
if (node.left != null) {
builder.append(serialize((AVLNode<E>) node.left));
} else {
builder.append("null");
}
builder.append(",");
builder.append(node.element);
builder.append(",");
if (node.right != null) {
builder.append(serialize((AVLNode<E>) node.right));
} else {
builder.append("null");
}
builder.append(")");
}
return builder.toString();
}
private int height(AVLNode<E> n) {
return (n == null) ? -1 : n.height;
}
/**
* Vidinė kolekcijos mazgo klasė
*
* @param <N> mazgo elemento duomenų tipas
*/
protected class AVLNode<N> extends BstNode<N> {
protected int height;
protected AVLNode(N element) {
super(element);
this.height = 0;
}
public void updateHeight() {
height = Math.max(height((AVLNode<E>) this.left), height((AVLNode<E>) this.right)) + 1;
}
}
}

View File

@ -0,0 +1,501 @@
package edu.ktu.ds.lab2.utils;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Stack;
/**
* Rikiuojamos objektų kolekcijos - aibės realizacija dvejetainiu paieškos
* medžiu.
*
* @param <E> Aibės elemento tipas. Turi tenkinti interfeisą Comparable<E>, arba
* per klasės konstruktorių turi būti paduodamas Comparator<E> interfeisą
* tenkinantis objektas.
* @author darius.matulis@ktu.lt
* @užduotis Peržiūrėkite ir išsiaiškinkite pateiktus metodus.
*/
public class BstSet<E extends Comparable<E>> implements SortedSet<E>, Cloneable {
// Medžio šaknies mazgas
protected BstNode<E> root = null;
// Medžio dydis
protected int size = 0;
// Rodyklė į komparatorių
protected Comparator<? super E> c;
/**
* Sukuriamas aibės objektas DP-medžio raktams naudojant Comparable<E>
*/
public BstSet() {
this.c = Comparator.naturalOrder();
}
/**
* Sukuriamas aibės objektas DP-medžio raktams naudojant Comparator<E>
*
* @param c Komparatorius
*/
public BstSet(Comparator<? super E> c) {
this.c = c;
}
/**
* Patikrinama ar aibė tuščia.
*
* @return Grąžinama true, jei aibė tuščia.
*/
@Override
public boolean isEmpty() {
return root == null;
}
/**
* @return Grąžinamas aibėje esančių elementų kiekis.
*/
@Override
public int size() {
return size;
}
/**
* Išvaloma aibė.
*/
@Override
public void clear() {
root = null;
size = 0;
}
/**
* Patikrinama ar aibėje egzistuoja elementas.
*
* @param element - Aibės elementas.
* @return Grąžinama true, jei aibėje egzistuoja elementas.
*/
@Override
public boolean contains(E element) {
if (element == null) {
throw new IllegalArgumentException("Element is null in contains(E element)");
}
return get(element) != null;
}
/**
* Patikrinama ar visi abės set elementai egzistuoja aibėje
*
* @param set aibė
* @return
*/
@Override
public boolean containsAll(Set<E> set) {
for (E e : set) {
if (!contains(e)) {
return false;
}
}
return true;
}
/**
* Aibė papildoma nauju elementu.
*
* @param element - Aibės elementas.
*/
@Override
public void add(E element) {
if (element == null) {
throw new IllegalArgumentException("Element is null in add(E element)");
}
root = addRecursive(element, root);
}
/**
* Abės set elementai pridedami į esamą aibę, jeigu abi aibės turi patį elementą, jis nėra dedamas.
*
* @param set pridedamoji aibė
*/
@Override
public void addAll(Set<E> set) {
for (E element : set) {
add(element);
}
}
private BstNode<E> addRecursive(E element, BstNode<E> node) {
if (node == null) {
size++;
return new BstNode<>(element);
}
int cmp = c.compare(element, node.element);
if (cmp < 0) {
node.left = addRecursive(element, node.left);
} else if (cmp > 0) {
node.right = addRecursive(element, node.right);
}
return node;
}
/**
* Pašalinamas elementas aibės.
*
* @param element - Aibės elementas.
*/
@Override
public void remove(E element) {
if (element == null) {
throw new IllegalArgumentException("Element is null in remove(E element)");
}
root = removeRecursive(element, root);
}
/**
* Aibėje lieka tik tie elementai, kurie yra aibėje set.
*
* @param set aibė
*/
@Override
public void retainAll(Set<E> set) {
for (E e : this) {
if (!set.contains(e)) {
remove(e);
}
}
}
private BstNode<E> removeRecursive(E element, BstNode<E> node) {
if (node == null) return null;
int cmp = c.compare(element, node.element);
if (cmp < 0) {
node.left = removeRecursive(element, node.left);
} else if (cmp > 0) {
node.right = removeRecursive(element, node.right);
} else {
size--;
if (node.left == null && node.right == null) {
return null;
} else if (node.left != null && node.right != null) {
if (node.right.left != null) {
BstNode<E> minimumParent = node;
BstNode<E> minimumNode = node.right;
while (minimumNode.left != null) {
minimumParent = minimumNode;
minimumNode = minimumNode.left;
}
minimumParent.left = minimumNode.right;
node.element = minimumNode.element;
} else {
node.element = node.right.element;
node.right = node.right.right;
}
} else if (node.left != null) {
return node.left;
} else { // if (node.right != null)
return node.right;
}
}
return node;
}
private E get(E element) {
if (element == null) {
throw new IllegalArgumentException("Element is null in get(E element)");
}
BstNode<E> node = root;
while (node != null) {
int cmp = c.compare(element, node.element);
if (cmp < 0) {
node = node.left;
} else if (cmp > 0) {
node = node.right;
} else {
return node.element;
}
}
return null;
}
/**
* Grąžinamas aibės elementų masyvas.
*
* @return Grąžinamas aibės elementų masyvas.
*/
@Override
public Object[] toArray() {
int i = 0;
Object[] array = new Object[size];
for (Object o : this) {
array[i++] = o;
}
return array;
}
/**
* Aibės elementų išvedimas į String eilutę Inorder (Vidine) tvarka. Aibės
* elementai išvedami surikiuoti didėjimo tvarka pagal raktą.
*
* @return elementų eilutė
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean isFirst = true;
for (E element : this) {
if (!isFirst) {
sb.append(", ");
}
sb.append(element.toString());
isFirst = false;
}
sb.append("]");
return sb.toString();
}
/**
* Medžio vaizdavimas simboliais, žiūr.: unicode.org/charts/PDF/U2500.pdf
* Tai 4 galimi terminaliniai simboliai medžio šakos gale
*/
private static final String[] term = {"\u2500", "\u2534", "\u252C", "\u253C"};
private static final String rightEdge = "\u250C";
private static final String leftEdge = "\u2514";
private static final String endEdge = "\u25CF";
private static final String vertical = "\u2502 ";
private String horizontal;
/* Papildomas metodas, išvedantis aibės elementus į vieną String eilutę.
* String eilutė formuojama atliekant elementų postūmį nuo krašto,
* priklausomai nuo elemento lygio medyje. Galima panaudoti spausdinimui į
* ekraną ar failą tyrinėjant medžio algoritmų veikimą.
*
* @author E. Karčiauskas
*/
@Override
public String toVisualizedString() {
horizontal = term[0] + term[0];
return root == null ? ">" + horizontal : toTreeDraw(root, ">", "");
}
private String toTreeDraw(BstNode<E> node, String edge, String indent) {
if (node == null) { return ""; }
String step = (edge.equals(leftEdge)) ? vertical : " ";
StringBuilder sb = new StringBuilder();
sb.append(toTreeDraw(node.right, rightEdge, indent + step));
int t = (node.right != null ? 1 : 0) + (node.left != null ? 2 : 0);
sb.append(indent).append(edge).append(horizontal);
sb.append(term[t]).append(endEdge).append(node.element.toString());
sb.append(System.lineSeparator());
step = (edge.equals(rightEdge)) ? vertical : " ";
sb.append(toTreeDraw(node.left, leftEdge, indent + step));
return sb.toString();
}
/**
* Sukuria ir grąžina aibės kopiją.
*
* @return Aibės kopija.
* @throws java.lang.CloneNotSupportedException
*/
@Override
public Object clone() throws CloneNotSupportedException {
BstSet<E> cl = (BstSet<E>) super.clone();
if (root == null) {
return cl;
}
cl.root = cloneRecursive(root);
cl.size = this.size;
return cl;
}
private BstNode<E> cloneRecursive(BstNode<E> node) {
if (node == null) {
return null;
}
BstNode<E> clone = new BstNode<>(node.element);
clone.left = cloneRecursive(node.left);
clone.right = cloneRecursive(node.right);
return clone;
}
/**
* Grąžinamas aibės poaibis iki elemento.
*
* @param element - Aibės elementas.
* @return Grąžinamas aibės poaibis iki elemento.
*/
@Override
public Set<E> headSet(E element) {
Set<E> headSet = new BstSet<>();
for (E e : this) {
headSet.add(e);
if (c.compare(e, element) == 0) break;
}
return headSet;
}
/**
* Grąžinamas aibės poaibis nuo elemento element1 iki element2.
*
* @param element1 - pradinis aibės poaibio elementas.
* @param element2 - galinis aibės poaibio elementas.
* @return Grąžinamas aibės poaibis nuo elemento element1 iki element2.
*/
@Override
public Set<E> subSet(E element1, E element2) {
Set<E> subSet = new BstSet<>();
boolean seen1 = false;
boolean seen2 = false;
for (E e : this) {
if (!seen1 && c.compare(e, element1) == 0) seen1 = true;
if (seen1 && !seen2) {
subSet.add(e);
}
if (!seen2 && c.compare(e, element2) == 0) seen2 = true;
}
return subSet;
}
/**
* Grąžinamas aibės poaibis nuo elemento.
*
* @param element - Aibės elementas.
* @return Grąžinamas aibės poaibis nuo elemento.
*/
@Override
public Set<E> tailSet(E element) {
Set<E> tailSet = new BstSet<>();
boolean seen = false;
for (E e : this) {
if (!seen && c.compare(e, element) == 0) seen = true;
if (seen) {
tailSet.add(e);
}
}
return tailSet;
}
public BstNode<E> getRoot() {
return root;
}
/**
* Grąžinamas tiesioginis iteratorius.
*
* @return Grąžinamas tiesioginis iteratorius.
*/
@Override
public Iterator<E> iterator() {
return new IteratorBst(true);
}
/**
* Grąžinamas atvirkštinis iteratorius.
*
* @return Grąžinamas atvirkštinis iteratorius.
*/
@Override
public Iterator<E> descendingIterator() {
return new IteratorBst(false);
}
/**
* Vidinė objektų kolekcijos iteratoriaus klasė. Iteratoriai: didėjantis ir
* mažėjantis. Kolekcija iteruojama kiekvieną elementą aplankant vieną kartą
* vidine (angl. inorder) tvarka. Visi aplankyti elementai saugomi steke.
* Stekas panaudotas java.util paketo, bet galima susikurti nuosavą.
*/
private class IteratorBst implements Iterator<E> {
private final Stack<BstNode<E>> stack = new Stack<>();
// Nurodo iteravimo kolekcija kryptį, true - didėjimo tvarka, false - mažėjimo
private final boolean ascending;
// Reikalinga remove() metodui.
private BstNode<E> lastInStack;
private BstNode<E> last;
IteratorBst(boolean ascendingOrder) {
this.ascending = ascendingOrder;
this.toStack(root);
}
@Override
public boolean hasNext() {
return !stack.empty();
}
@Override
public E next() {// Jei stekas tuščias
if (stack.empty()) {
lastInStack = root;
last = null;
return null;
} else {
// Grąžinamas paskutinis į steką patalpintas elementas
BstNode<E> n = stack.pop();
// Atsimenamas paskutinis grąžintas elementas, o taip pat paskutinis steke esantis elementas.
// Reikia remove() metodui
lastInStack = stack.isEmpty() ? root : stack.peek();
last = n;
BstNode<E> node = (ascending) ? n.right : n.left;
// Dešiniajame n pomedyje ieškoma minimalaus elemento,
// o visi paieškos kelyje esantys elementai talpinami į steką
toStack(node);
return n.element;
}
}
@Override
public void remove() {
root = removeRecursive(lastInStack.element, root);
}
private void toStack(BstNode<E> n) {
while (n != null) {
stack.push(n);
n = (ascending) ? n.left : n.right;
}
}
}
/**
* Vidinė kolekcijos mazgo klasė
*
* @param <N> mazgo elemento duomenų tipas
*/
public static class BstNode<N> {
// Elementas
public N element;
// Rodyklė į kairįjį pomedį
public BstNode<N> left;
// Rodyklė į dešinįjį pomedį
public BstNode<N> right;
protected BstNode() {
}
protected BstNode(N element) {
this.element = element;
this.left = null;
this.right = null;
}
}
}

View File

@ -0,0 +1,118 @@
package edu.ktu.ds.lab2.utils;
import java.util.Comparator;
/**
* Klasė paveldi klasę BstSet ir perdengia add metodą iteracine realizacija
*
* @param <E>
* @author darius
*/
public class BstSetIterative<E extends Comparable<E>> extends BstSet<E> implements SortedSet<E> {
public BstSetIterative() {
super();
}
public BstSetIterative(Comparator<? super E> c) {
super(c);
}
/**
* Aibė papildoma nauju elementu. Papildymas atliekamas iteracijos į gylį
*
* @param element
*/
@Override
public void add(E element) {
if (element == null) {
throw new IllegalArgumentException("Element is null in add(E element)");
}
if (root == null) {
root = new BstNode<E>(element);
} else {
BstNode<E> current = root;
BstNode<E> parent = null;
while (current != null) {
parent = current;
int cmp = c.compare(element, current.element);
if (cmp < 0) {
current = current.left;
} else if (cmp > 0) {
current = current.right;
} else {
return;
}
}
int cmp = c.compare(element, parent.element);
if (cmp < 0) {
parent.left = new BstNode<E>(element);
} else if (cmp > 0) {
parent.right = new BstNode<E>(element);
}
}
size++;
}
/**
* Pašalinamas elementas aibės.
*
* @param element - Aibės elementas.
*/
@Override
public void remove(E element) {
if (element == null) {
throw new IllegalArgumentException("Element is null in remove(E element)");
}
if (root == null) return;
BstNode<E> current = root;
BstNode<E> parent = null;
while (current != null) {
int cmp = c.compare(element, current.element);
if (cmp == 0) break;
parent = current;
if (cmp < 0) {
current = current.left;
} else { //if (cmp > 0) {
current = current.right;
}
}
if (current == null) {
return;
} else if (current.right != null && current.left != null) {
BstNode<E> rightMinimumParent = null;
BstNode<E> rightMinimum = current.right;
while (rightMinimum.left != null) {
rightMinimumParent = rightMinimum;
rightMinimum = rightMinimum.left;
}
if (rightMinimumParent != null) {
rightMinimumParent.left = rightMinimum.right;
} else {
current.right = rightMinimum.right;
}
current.element = rightMinimum.element;
} else {
BstNode<E> newCurrent = current.left == null ? current.right : current.left;
if (parent == null) {
root = newCurrent;
} else if (parent.left == current) {
parent.left = newCurrent;
} else {
parent.right = newCurrent;
}
}
size--;
}
}

View File

@ -0,0 +1,174 @@
package edu.ktu.ds.lab2.utils;
import java.io.*;
import java.time.LocalDate;
import java.util.Arrays;
/*
* Klasė yra skirta patogiam duomenų paėmimui klaviatūros bei
* efektyviam rezultatų pateikimui į sout ir serr srautus.
* Visi metodai yra statiniai ir skirti vienam duomenų tipui.
* studentai savarankiškai paruošia metodus dėl short ir byte skaičių tipų.
*
* @author eimutis
*/
public class Ks { // KTU system - imituojama Javos System klasė
private static final BufferedReader keyboard
= new BufferedReader(new InputStreamReader(System.in));
private static String dataFolder = "data";
static public String giveString(String prompt) {
Ks.ou(prompt);
try {
return keyboard.readLine();
} catch (IOException e) {
Ks.ern("Neveikia klaviatūros srautas, darbas baigtas");
System.exit(0);
}
return "";
}
static public long giveLong(String prompt) {
while (true) {
String s = giveString(prompt);
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
Ks.ern("Neteisingas skaičiaus formatas, pakartokite");
}
}
}
static public long giveLong(String prompt, long bound1, long bound2) {
while (true) {
long a = giveLong(prompt + " tarp ribų [" + bound1 + ":" + bound2 + "]=");
if (a < bound1) {
Ks.ern("Skaičius mažesnis nei leistina, pakartokite");
} else if (a > bound2) {
Ks.ern("Skaičius didesnis nei leistina, pakartokite");
} else {
return a;
}
}
}
static public int giveInt(String prompt) {
while (true) {
long a = giveLong(prompt);
if (a < Integer.MIN_VALUE) {
Ks.ern("Skaičius mažesnis nei Integer.MIN_VALUE"
+ ", pakartokite");
} else if (a > Integer.MAX_VALUE) {
Ks.ern("Skaičius didesnis nei Integer.MAX_VALUE"
+ ", pakartokite");
} else {
return (int) a;
}
}
}
static public int giveInt(String prompt, int bound1, int bound2) {
return (int) giveLong(prompt, bound1, bound2);
}
static public double giveDouble(String prompt) {
while (true) {
String s = giveString(prompt);
try {
return Double.parseDouble(s);
} catch (NumberFormatException e) {
if (s.contains(",")) {
Ks.ern("Vietoje kablelio naudokite tašką"
+ ", pakartokite");
} else {
Ks.ern("Neteisingas skaičiaus formatas"
+ ", pakartokite");
}
}
}
}
static public double giveDouble(String prompt, double bound1, double bound2) {
while (true) {
double a = giveDouble(prompt + " tarp ribų [" + bound1 + ":" + bound2 + "]=");
if (a < bound1) {
Ks.ern("Skaičius mažesnis nei leistina, pakartokite");
} else if (a > bound2) {
Ks.ern("Skaičius didesnis nei leistina, pakartokite");
} else {
return a;
}
}
}
static public String giveFileName() {
File dir = new File(dataFolder);
dir.mkdir();
oun("Jums prieinami failai " + Arrays.toString(dir.list()));
return giveString("Nurodykite pasirinktą duomenų failo vardą: ");
}
static public String getDataFolder() {
return dataFolder;
}
static public void setDataFolder(String folderName) {
dataFolder = folderName;
}
private static final PrintStream sout = System.out;
private static final PrintStream serr = System.out;
private static int lineNr;
private static int errorNr;
private static final boolean formatStartOfLine = true;
static public void ou(Object obj) {
if (formatStartOfLine) {
sout.printf("%2d| %s", ++lineNr, obj);
} else {
sout.println(obj);
}
}
static public void oun(Object obj) {
if (formatStartOfLine) {
sout.printf("%2d| %s\n", ++lineNr, obj);
} else {
sout.println(obj);
}
}
static public void ounn(Object obj) { // *****nauja
if (formatStartOfLine) {
sout.printf("%2d|\n", ++lineNr);
sout.printf("%s\n", obj);
} else {
sout.println(obj);
}
}
static public void out(Object obj) {
sout.print(obj);
}
static public void ouf(String format, Object... args) {
sout.printf(format, args);
}
static public void er(Object obj) {
serr.printf("***Klaida %d: %s", ++errorNr, obj);
}
static public void ern(Object obj) {
serr.printf("***Klaida %d: %s\n", ++errorNr, obj);
}
static public void erf(String format, Object... args) {
serr.printf(format, args);
}
static public LocalDate getDate() {
return LocalDate.now();
}
}

View File

@ -0,0 +1,16 @@
package edu.ktu.ds.lab2.utils;
/** @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra
*
* Tai yra interfeisas, kurį turi tenkinti KTU studentų kuriamos duomenų klasės
* Metodai užtikrina patogų duomenų suformavimą String eilučių
******************************************************************************/
public interface Parsable<T> extends Comparable<T> {
/**
* Suformuoja objektą eilutės
*
* @param dataString
*/
void parse(String dataString);
}

View File

@ -0,0 +1,77 @@
package edu.ktu.ds.lab2.utils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.Optional;
import java.util.function.Function;
public class ParsableAvlSet<E extends Parsable<E>> extends AvlSet<E> implements ParsableSortedSet<E> {
private final Function<String, E> createFunction; // funkcija bazinio objekto kūrimui
/**
* Konstruktorius su funkcija bazinio objekto kūrimui
*
* @param createFunction
*/
public ParsableAvlSet(Function<String, E> createFunction) {
super();
this.createFunction = createFunction;
}
/**
* Konstruktorius su funkcija bazinio objekto kūrimui ir komparatoriumi
*
* @param createFunction
* @param c
*/
public ParsableAvlSet(Function<String, E> createFunction, Comparator<? super E> c) {
super(c);
this.createFunction = createFunction;
}
/**
* Sukuria elementą String eilutės ir įdeda į pabaigą
*
* @param dataString
*/
@Override
public void add(String dataString) {
add(createElement(dataString));
}
/**
* Suformuoja sąrašą filePath failo
*
* @param filePath
*/
@Override
public void load(String filePath) {
if (filePath == null || filePath.length() == 0) {
return;
}
clear();
try (BufferedReader fReader = Files.newBufferedReader(Paths.get(filePath), Charset.defaultCharset())) {
fReader.lines()
.map(String::trim)
.filter(line -> !line.isEmpty())
.forEach(this::add);
} catch (FileNotFoundException e) {
Ks.ern("Duomenų failas " + filePath + " nerastas");
} catch (IOException e) {
Ks.ern("Failo " + filePath + " skaitymo klaida");
}
}
protected E createElement(String data) {
return Optional.ofNullable(createFunction)
.map(f -> f.apply(data))
.orElseThrow(() -> new IllegalStateException("Nenustatyta aibės elementų kūrimo funkcija"));
}
}

View File

@ -0,0 +1,78 @@
package edu.ktu.ds.lab2.utils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.Optional;
import java.util.function.Function;
public class ParsableBstSet<E extends Parsable<E>> extends BstSet<E>
implements ParsableSortedSet<E> {
private final Function<String, E> createFunction; // funkcija bazinio objekto kūrimui
/**
* Konstruktorius su funkcija bazinio objekto kūrimui
*
* @param createFunction
*/
public ParsableBstSet(Function<String, E> createFunction) {
super();
this.createFunction = createFunction;
}
/**
* Konstruktorius su funkcija bazinio objekto kūrimui ir komparatoriumi
*
* @param createFunction
* @param c
*/
public ParsableBstSet(Function<String, E> createFunction, Comparator<? super E> c) {
super(c);
this.createFunction = createFunction;
}
/**
* Sukuria elementą String ir įdeda į pabaigą
*
* @param dataString
*/
@Override
public void add(String dataString) {
super.add(createElement(dataString));
}
/**
* Suformuoja sąrašą filePath failo
*
* @param filePath
*/
@Override
public void load(String filePath) {
if (filePath == null || filePath.length() == 0) {
return;
}
clear();
try (BufferedReader fReader = Files.newBufferedReader(Paths.get(filePath), Charset.defaultCharset())) {
fReader.lines()
.map(String::trim)
.filter(line -> !line.isEmpty())
.forEach(this::add);
} catch (FileNotFoundException e) {
Ks.ern("Tinkamas duomenų failas " + filePath + " nerastas");
} catch (IOException e) {
Ks.ern("Failo " + filePath + " skaitymo klaida");
}
}
protected E createElement(String data) {
return Optional.ofNullable(createFunction)
.map(f -> f.apply(data))
.orElseThrow(() -> new IllegalStateException("Nenustatyta aibės elementų kūrimo funkcija"));
}
}

View File

@ -0,0 +1,10 @@
package edu.ktu.ds.lab2.utils;
public interface ParsableSortedSet<E> extends SortedSet<E> {
void add(String dataString);
void load(String fName);
Object clone() throws CloneNotSupportedException;
}

Some files were not shown because too many files have changed in this diff Show More