1
0
This commit is contained in:
Rokas Puzonas 2022-12-13 22:32:03 +02:00 committed by GitHub
parent 057b52e3bd
commit cba5fe2d31
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 84471 additions and 0 deletions

View File

@ -0,0 +1,23 @@
<?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_11">
<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/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/target/generated-sources/annotations" isTestSource="false" generated="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,38 @@
abatis
aahs
abdicate
aal
abduced
abator
abbots
abducing
abba
abbas
abbey
abdomen
abbe
abbess
aahed
aa
abbatial
abbesses
abattoir
abbeys
aahing
abaxile
abdomens
abbacy
abduces
abatises
abaxial
abbacies
abduce
abdomina
abducens
abators
abducent
abattis
aah
abbot
abbotcy
abbes

View File

@ -0,0 +1,3 @@
Renault Laguna 2001 115900 7500.0
Honda Civic 2007 36400 8500.3
Renault Laguna 2002 115900 7500.0

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,258 @@
@startuml
title __LAB3_MAISOSLENTELES's Class Diagram__\n
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.Benchmark {
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.Car {
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.CarsGenerator {
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.DemoExecution {
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.ManualTest {
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType {
}
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType_B1 {
}
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType_B2 {
}
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType_B3 {
}
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType {
}
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType_B1 {
}
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType_B2 {
}
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType_B3 {
}
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_putMap_jmhTest {
}
}
}
namespace edu.ktu.ds.lab3.demo {
namespace jmh_generated {
class edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_removeCarMap_jmhTest {
}
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.KsGui {
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.MainWindow {
}
}
namespace edu.ktu.ds.lab3.gui {
abstract class edu.ktu.ds.lab3.gui.MainWindowMenu {
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.Panels {
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.Table {
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.TableModel {
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.ValidationException {
}
}
namespace edu.ktu.ds.lab3.utils {
interface edu.ktu.ds.lab3.utils.EvaluableMap {
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.HashManager {
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.HashMap {
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.HashMapOa {
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.Ks {
}
}
namespace edu.ktu.ds.lab3.utils {
interface edu.ktu.ds.lab3.utils.Map {
}
}
namespace edu.ktu.ds.lab3.utils {
interface edu.ktu.ds.lab3.utils.Parsable {
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.ParsableHashMap {
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.ParsableHashMapOa {
}
}
namespace edu.ktu.ds.lab3.utils {
interface edu.ktu.ds.lab3.utils.ParsableMap {
}
}
edu.ktu.ds.lab3.demo.Car .up.|> edu.ktu.ds.lab3.utils.Parsable
edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType -up-|> edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType_B3
edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType_B1 -up-|> edu.ktu.ds.lab3.demo.Benchmark.FullMap
edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType_B2 -up-|> edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType_B1
edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType_B3 -up-|> edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_FullMap_jmhType_B2
edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType -up-|> edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType_B3
edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType_B1 -up-|> edu.ktu.ds.lab3.demo.Benchmark
edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType_B2 -up-|> edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType_B1
edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType_B3 -up-|> edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_jmhType_B2
edu.ktu.ds.lab3.gui.MainWindow .up.|> java.awt.event.ActionListener
edu.ktu.ds.lab3.gui.MainWindow -up-|> javax.swing.JFrame
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.demo.CarsGenerator : carsGenerator
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.utils.HashManager.HashType : ht
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.MainWindowMenu : mainWindowMenu
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.Panels : panButtons
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.Panels : panParam1
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.Panels : panParam2
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.Table : table
edu.ktu.ds.lab3.gui.MainWindowMenu .up.|> java.awt.event.ActionListener
edu.ktu.ds.lab3.gui.MainWindowMenu -up-|> javax.swing.JMenuBar
edu.ktu.ds.lab3.gui.Panels -up-|> javax.swing.JPanel
edu.ktu.ds.lab3.gui.Table -up-|> javax.swing.JTable
edu.ktu.ds.lab3.gui.TableModel -up-|> javax.swing.table.AbstractTableModel
edu.ktu.ds.lab3.utils.HashMap .up.|> edu.ktu.ds.lab3.utils.EvaluableMap
edu.ktu.ds.lab3.utils.HashMap o-- edu.ktu.ds.lab3.utils.HashManager.HashType : ht
edu.ktu.ds.lab3.utils.HashMapOa .up.|> edu.ktu.ds.lab3.utils.EvaluableMap
edu.ktu.ds.lab3.utils.HashMapOa o-- edu.ktu.ds.lab3.utils.HashManager.HashType : ht
edu.ktu.ds.lab3.utils.HashMapOa o-- edu.ktu.ds.lab3.utils.HashMapOa.OpenAddressingType : oaType
edu.ktu.ds.lab3.utils.ParsableHashMap .up.|> edu.ktu.ds.lab3.utils.ParsableMap
edu.ktu.ds.lab3.utils.ParsableHashMap -up-|> edu.ktu.ds.lab3.utils.HashMap
edu.ktu.ds.lab3.utils.ParsableHashMapOa .up.|> edu.ktu.ds.lab3.utils.ParsableMap
edu.ktu.ds.lab3.utils.ParsableHashMapOa -up-|> edu.ktu.ds.lab3.utils.HashMapOa
right footer
PlantUML diagram generated by SketchIt! (https://bitbucket.org/pmesmeur/sketch.it)
For more information about this tool, please contact philippe.mesmeur@gmail.com
endfooter
@enduml

View File

@ -0,0 +1,128 @@
@startuml
title __DEMO's Class Diagram__\n
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.Benchmark {
+ elementCount : int
~ cars : List<Car>
~ ids : List<String>
+ generateIdsAndCars()
{static} + main()
+ putMap()
{static} + putMappings()
+ removeCarMap()
{static} ~ generateCars()
{static} ~ generateIds()
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.Benchmark.FullMap {
~ cars : List<Car>
~ carsMap : HashMap<String, Car>
~ ids : List<String>
+ fillCarMap()
+ generateIdsAndCars()
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.Car {
{static} - currentYear : int
- make : String
{static} - maxPrice : double
- mileage : int
{static} - minPrice : double
{static} - minYear : int
- model : String
- price : double
- year : int
+ Car()
+ Car()
+ Car()
+ Car()
+ equals()
+ getMake()
+ getMileage()
+ getModel()
+ getPrice()
+ getYear()
+ hashCode()
+ parse()
+ setMileage()
+ setPrice()
+ toString()
- validate()
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.Car.Builder {
{static} - MODELS : String[][]
{static} - RANDOM : Random
- make : String
- mileage : int
- model : String
- price : double
- year : int
+ build()
+ buildRandom()
+ make()
+ mileage()
+ model()
+ price()
+ year()
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.CarsGenerator {
{static} - ID_CODE : String
- cars : Queue<Car>
- keys : Queue<String>
{static} - serNr : int
{static} + generateId()
{static} + generateShuffleCars()
{static} + generateShuffleIds()
+ generateShuffleIdsAndCars()
+ getCar()
+ getCarId()
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.DemoExecution {
{static} + main()
}
}
namespace edu.ktu.ds.lab3.demo {
class edu.ktu.ds.lab3.demo.ManualTest {
{static} + executeTest()
{static} + main()
{static} - executeCarMapOaTests()
{static} - executeCarMapTests()
}
}
edu.ktu.ds.lab3.demo.Benchmark +-down- edu.ktu.ds.lab3.demo.Benchmark.FullMap
edu.ktu.ds.lab3.demo.Car .up.|> edu.ktu.ds.lab3.utils.Parsable
edu.ktu.ds.lab3.demo.Car +-down- edu.ktu.ds.lab3.demo.Car.Builder
right footer
PlantUML diagram generated by SketchIt! (https://bitbucket.org/pmesmeur/sketch.it)
For more information about this tool, please contact philippe.mesmeur@gmail.com
endfooter
@enduml

View File

@ -0,0 +1,154 @@
@startuml
title __GUI's Class Diagram__\n
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.KsGui {
{static} - formatStartOfLine : boolean
{static} - lineNr : int
{static} + ou()
{static} + ou()
{static} + oun()
{static} + oun()
{static} + ounArgs()
{static} + ounerr()
{static} + ounerr()
{static} + ounerr()
{static} + setFormatStartOfLine()
{static} - getStartOfLine()
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.MainWindow {
{static} - MESSAGES : ResourceBundle
{static} - NUMBER_OF_BUTTONS : int
{static} - TF_WIDTH : int
- cmbCollisionTypes : JComboBox<String>
- cmbHashFunctions : JComboBox<String>
- colWidth : int
- initialCapacity : int
- loadFactor : float
- map : ParsableMap<String, Car>
- panEast : JPanel
- panParam12 : JPanel
- panParam12Events : JPanel
- scrollEast : JScrollPane
- scrollEvents : JScrollPane
- scrollParam12 : JScrollPane
- scrollTable : JScrollPane
- sizeOfGenSet : int
- sizeOfInitialSubSet : int
- taEvents : JTextArea
- taInput : JTextArea
+ MainWindow()
+ actionPerformed()
{static} + createAndShowGUI()
+ mapGeneration()
+ mapPut()
- appearance()
- createMap()
- handleButtons()
- initComponents()
- readMapParameters()
- updateHashtableParameters()
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.MainWindow.NotNegativeNumberVerifier {
+ verify()
}
}
namespace edu.ktu.ds.lab3.gui {
abstract class edu.ktu.ds.lab3.gui.MainWindowMenu {
{static} - MESSAGES : ResourceBundle
+ MainWindowMenu()
{abstract} + actionPerformed()
- initComponents()
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.Panels {
{static} - SPACING : int
- btns : List<JButton>
- tfTexts : List<String>
- tfs : List<JTextField>
+ Panels()
+ Panels()
+ getButtons()
+ getParametersOfTable()
+ getTfOfTable()
- initGridOfButtons()
- initTableOfParameters()
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.Table {
{static} + ARROW : String
+ prepareRenderer()
+ setModel()
- appearance()
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.TableModel {
- delimiter : String
- maxChainSize : int
- table : String[][]
+ TableModel()
+ getColumnCount()
+ getColumnName()
+ getRowCount()
+ getValueAt()
- split()
}
}
namespace edu.ktu.ds.lab3.gui {
class edu.ktu.ds.lab3.gui.ValidationException {
- value : String
+ ValidationException()
+ ValidationException()
+ getValue()
}
}
edu.ktu.ds.lab3.gui.MainWindow .up.|> java.awt.event.ActionListener
edu.ktu.ds.lab3.gui.MainWindow -up-|> javax.swing.JFrame
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.demo.CarsGenerator : carsGenerator
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.utils.HashManager.HashType : ht
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.MainWindowMenu : mainWindowMenu
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.Panels : panButtons
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.Panels : panParam1
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.Panels : panParam2
edu.ktu.ds.lab3.gui.MainWindow o-- edu.ktu.ds.lab3.gui.Table : table
edu.ktu.ds.lab3.gui.MainWindow +-down- edu.ktu.ds.lab3.gui.MainWindow.NotNegativeNumberVerifier
edu.ktu.ds.lab3.gui.MainWindow.NotNegativeNumberVerifier -up-|> javax.swing.InputVerifier
edu.ktu.ds.lab3.gui.MainWindowMenu .up.|> java.awt.event.ActionListener
edu.ktu.ds.lab3.gui.MainWindowMenu -up-|> javax.swing.JMenuBar
edu.ktu.ds.lab3.gui.Panels -up-|> javax.swing.JPanel
edu.ktu.ds.lab3.gui.Table -up-|> javax.swing.JTable
edu.ktu.ds.lab3.gui.TableModel -up-|> javax.swing.table.AbstractTableModel
right footer
PlantUML diagram generated by SketchIt! (https://bitbucket.org/pmesmeur/sketch.it)
For more information about this tool, please contact philippe.mesmeur@gmail.com
endfooter
@enduml

View File

@ -0,0 +1,264 @@
@startuml
title __UTILS's Class Diagram__\n
namespace edu.ktu.ds.lab3.utils {
interface edu.ktu.ds.lab3.utils.EvaluableMap {
{abstract} + getLastUpdated()
+ getMaxChainSize()
{abstract} + getNumberOfOccupied()
{abstract} + getRehashesCounter()
{abstract} + getTableCapacity()
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.HashManager {
{static} + hash()
}
}
namespace edu.ktu.ds.lab3.utils {
enum HashType {
DIVISION
JCF
JCF7
MULTIPLICATION
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.HashMap {
{static} + DEFAULT_HASH_TYPE : HashType
{static} + DEFAULT_INITIAL_CAPACITY : int
{static} + DEFAULT_LOAD_FACTOR : float
# chainsCounter : int
# lastUpdatedChain : int
# loadFactor : float
# maxChainSize : int
# rehashesCounter : int
# size : int
# table : Node<K, V>[]
+ HashMap()
+ HashMap()
+ HashMap()
+ HashMap()
+ HashMap()
+ clear()
+ contains()
+ containsValue()
+ get()
+ getLastUpdated()
+ getMaxChainSize()
+ getNumberOfOccupied()
+ getRehashesCounter()
+ getTableCapacity()
+ isEmpty()
+ put()
+ remove()
+ replace()
+ size()
+ toString()
- getInChain()
- rehash()
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.HashMap.Node {
# next : Node<K, V>
+ toString()
# Node()
# Node()
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.HashMapOa {
{static} + DEFAULT_HASH_TYPE : HashType
{static} + DEFAULT_INITIAL_CAPACITY : int
{static} + DEFAULT_LOAD_FACTOR : float
{static} + DEFAULT_OPEN_ADDRESSING_TYPE : OpenAddressingType
# lastUpdated : int
# loadFactor : float
# numberOfOccupied : int
# rehashesCounter : int
# size : int
# table : Entry<K, V>[]
- DELETED : Entry<K, V>
+ HashMapOa()
+ HashMapOa()
+ HashMapOa()
+ HashMapOa()
+ HashMapOa()
+ clear()
+ contains()
+ containsValue()
+ get()
+ getLastUpdated()
+ getNumberOfOccupied()
+ getRehashesCounter()
+ getTableCapacity()
+ isEmpty()
+ put()
+ remove()
+ replace()
+ size()
+ toString()
- calculatePosition()
- findPosition()
- rehash()
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.HashMapOa.Entry {
+ toString()
# Entry()
# Entry()
}
}
namespace edu.ktu.ds.lab3.utils {
enum OpenAddressingType {
DOUBLE_HASHING
LINEAR
QUADRATIC
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.Ks {
{static} - dataFolder : String
{static} - errorNr : int
{static} - formatStartOfLine : boolean
{static} - keyboard : BufferedReader
{static} - lineNr : int
{static} - serr : PrintStream
{static} - sout : PrintStream
{static} + er()
{static} + erf()
{static} + ern()
{static} + getDataFolder()
{static} + giveDouble()
{static} + giveDouble()
{static} + giveFileName()
{static} + giveInt()
{static} + giveInt()
{static} + giveLong()
{static} + giveLong()
{static} + giveString()
{static} + ou()
{static} + ouf()
{static} + oufln()
{static} + oun()
{static} + ounn()
{static} + out()
{static} + printMapModel()
{static} + setDataFolder()
{static} - split()
{static} - summaryStatistics()
}
}
namespace edu.ktu.ds.lab3.utils {
interface edu.ktu.ds.lab3.utils.Map {
{abstract} + clear()
{abstract} + contains()
{abstract} + containsValue()
{abstract} + get()
{abstract} + isEmpty()
{abstract} + put()
{abstract} + remove()
{abstract} + replace()
{abstract} + size()
}
}
namespace edu.ktu.ds.lab3.utils {
interface edu.ktu.ds.lab3.utils.Parsable {
{abstract} + parse()
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.ParsableHashMap {
- keyCreateFunction : Function<String, K>
- valueCreateFunction : Function<String, V>
+ ParsableHashMap()
+ ParsableHashMap()
+ getMapModel()
+ load()
+ println()
+ put()
+ save()
{static} - create()
}
}
namespace edu.ktu.ds.lab3.utils {
class edu.ktu.ds.lab3.utils.ParsableHashMapOa {
- keyCreateFunction : Function<String, K>
- valueCreateFunction : Function<String, V>
+ ParsableHashMapOa()
+ ParsableHashMapOa()
+ getMapModel()
+ load()
+ println()
+ put()
+ save()
{static} - create()
}
}
namespace edu.ktu.ds.lab3.utils {
interface edu.ktu.ds.lab3.utils.ParsableMap {
{abstract} + getMapModel()
{abstract} + load()
{abstract} + println()
{abstract} + put()
{abstract} + save()
}
}
edu.ktu.ds.lab3.utils.HashManager +-down- edu.ktu.ds.lab3.utils.HashManager.HashType
edu.ktu.ds.lab3.utils.HashMap .up.|> edu.ktu.ds.lab3.utils.EvaluableMap
edu.ktu.ds.lab3.utils.HashMap o-- edu.ktu.ds.lab3.utils.HashManager.HashType : ht
edu.ktu.ds.lab3.utils.HashMap +-down- edu.ktu.ds.lab3.utils.HashMap.Node
edu.ktu.ds.lab3.utils.HashMap.Node o-- K : key
edu.ktu.ds.lab3.utils.HashMap.Node o-- V : value
edu.ktu.ds.lab3.utils.HashMapOa .up.|> edu.ktu.ds.lab3.utils.EvaluableMap
edu.ktu.ds.lab3.utils.HashMapOa o-- edu.ktu.ds.lab3.utils.HashManager.HashType : ht
edu.ktu.ds.lab3.utils.HashMapOa o-- edu.ktu.ds.lab3.utils.HashMapOa.OpenAddressingType : oaType
edu.ktu.ds.lab3.utils.HashMapOa +-down- edu.ktu.ds.lab3.utils.HashMapOa.Entry
edu.ktu.ds.lab3.utils.HashMapOa +-down- edu.ktu.ds.lab3.utils.HashMapOa.OpenAddressingType
edu.ktu.ds.lab3.utils.HashMapOa.Entry o-- K : key
edu.ktu.ds.lab3.utils.HashMapOa.Entry o-- V : value
edu.ktu.ds.lab3.utils.ParsableHashMap .up.|> edu.ktu.ds.lab3.utils.ParsableMap
edu.ktu.ds.lab3.utils.ParsableHashMap -up-|> edu.ktu.ds.lab3.utils.HashMap
edu.ktu.ds.lab3.utils.ParsableHashMapOa .up.|> edu.ktu.ds.lab3.utils.ParsableMap
edu.ktu.ds.lab3.utils.ParsableHashMapOa -up-|> edu.ktu.ds.lab3.utils.HashMapOa
right footer
PlantUML diagram generated by SketchIt! (https://bitbucket.org/pmesmeur/sketch.it)
For more information about this tool, please contact philippe.mesmeur@gmail.com
endfooter
@enduml

BIN
Lab3_MaisosLenteles/ktu.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

175
Lab3_MaisosLenteles/pom.xml Normal file
View File

@ -0,0 +1,175 @@
<!--
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>lab3</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Lab3</name>
<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>11</source>
<target>11</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,100 @@
package edu.ktu.ds.lab3.demo;
import edu.ktu.ds.lab3.utils.HashManager;
import edu.ktu.ds.lab3.utils.HashMap;
import edu.ktu.ds.lab3.utils.HashMapOa;
import org.openjdk.jmh.annotations.*;
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.Collections;
import java.util.HashSet;
import java.util.Random;
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 {
@Param({"10000", "20000", "40000", "80000", "160000"})
public int elementCount;
//@Param({"division", "multiplication", "JCF"})
public String hashTypeStr = "division";
HashMap<Integer, Integer> hashMap;
HashMapOa<Integer, Integer> hashMapOa;
ArrayList<Integer> keys;
@Setup(Level.Iteration)
public void generateIdsAndCars() throws Exception {
HashManager.HashType hashType = null;
switch (hashTypeStr) {
case "division":
hashType = HashManager.HashType.DIVISION;
break;
case "multiplication":
hashType = HashManager.HashType.MULTIPLICATION;
break;
case "JCF7":
hashType = HashManager.HashType.JCF7;
break;
case "JCF":
hashType = HashManager.HashType.JCF;
break;
default:
throw new Exception("Invalid hash type");
};
HashMap.DEFAULT_HASH_TYPE = hashType;
HashMapOa.DEFAULT_HASH_TYPE = hashType;
Random r = new Random();
keys = new ArrayList<>();
int keyCount = 0;
while (keyCount < elementCount) {
int key = r.nextInt(elementCount*2);
if (!keys.contains(key)) {
keys.add(key);
keyCount++;
}
}
hashMap = new HashMap<>();
hashMapOa = new HashMapOa<>();
for (Integer key : keys) {
int value = r.nextInt(elementCount);
hashMap.put(key, value);
hashMapOa.put(key, value);
}
Collections.shuffle(keys, r);
}
@org.openjdk.jmh.annotations.Benchmark
public void hashMapRemove() {
for (Integer key : keys) {
hashMap.remove(key);
}
}
@org.openjdk.jmh.annotations.Benchmark
public void hashMapOaRemove() {
for (Integer key : keys) {
hashMapOa.remove(key);
}
}
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,194 @@
package edu.ktu.ds.lab3.demo;
import edu.ktu.ds.lab3.utils.Ks;
import edu.ktu.ds.lab3.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 String make = "";
private String model = "";
private int year = -1;
private int mileage = -1;
private double price = -1.0;
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;
validate();
}
public Car(String dataString) {
this.parse(dataString);
validate();
}
public Car(Builder builder) {
this.make = builder.make;
this.model = builder.model;
this.year = builder.year;
this.mileage = builder.mileage;
this.price = builder.price;
validate();
}
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();
mileage = scanner.nextInt();
price = scanner.nextDouble();
} catch (InputMismatchException e) {
Ks.ern("Blogas duomenų formatas -> " + dataString);
} catch (NoSuchElementException e) {
Ks.ern("Trūksta duomenų -> " + dataString);
}
}
@Override
public String toString() {
return 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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return year == car.year &&
mileage == car.mileage &&
Double.compare(car.price, price) == 0 &&
Objects.equals(make, car.make) &&
Objects.equals(model, car.model);
}
@Override
public int hashCode() {
return Objects.hash(make, model, year, mileage, price);
}
// Car klases objektų gamintojas
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,85 @@
package edu.ktu.ds.lab3.demo;
import edu.ktu.ds.lab3.gui.ValidationException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CarsGenerator {
private static final String ID_CODE = "TA"; // ***** Nauja
private static int serNr = 100; // ***** Nauja
private Queue<String> keys;
private Queue<Car> cars;
/**
* Generuojama Automobilių ir raktų eilė. Šis metodas naudojamas grafinėje sąsajoje
*
* @param setSize Sugeneruotos automobilių ir raktų eilių dydžiai
* @throws ValidationException
*/
public void generateShuffleIdsAndCars(int setSize) throws ValidationException {
keys = generateShuffleIds(setSize);
cars = generateShuffleCars(setSize);
}
/**
* Gražinamas vienas elementas (Automobilis) sugeneruotos Automobilių eilės.
* Kai elementai baigiasi sugeneruojama nuosava situacija ir išmetamas pranešimas.
* Šis metodas naudojamas grafinėje sąsajoje
*
* @return Automobilis
*/
public Car getCar() {
if (cars == null) {
throw new ValidationException("carsNotGenerated");
}
if (cars.isEmpty()) {
throw new ValidationException("allSetStoredToMap");
}
return cars.poll();
}
/**
* Grąžinamas vienas raktas (ID) sugeneruotos raktų eilės.
* Kai raktai baigiasi sugeneruojama nuosava situacija (exception) ir išmetamas pranešimas.
* Šis metodas naudojamas grafinėje sąsajoje
*
* @return raktas
*/
public String getCarId() {
if (keys == null) {
throw new ValidationException("carsIdsNotGenerated");
}
if (keys.isEmpty()) {
throw new ValidationException("allKeysStoredToMap");
}
return keys.poll();
}
public static Queue<Car> generateShuffleCars(int size) {
LinkedList<Car> cars = IntStream.range(0, size)
.mapToObj(i -> new Car.Builder().buildRandom())
.collect(Collectors.toCollection(LinkedList::new));
Collections.shuffle(cars);
return cars;
}
public static Queue<String> generateShuffleIds(int size) {
LinkedList<String> keys = IntStream.range(0, size)
.mapToObj(i -> generateId())
.collect(Collectors.toCollection(LinkedList::new));
Collections.shuffle(keys);
return keys;
}
public static String generateId() {
return ID_CODE + (serNr++);
}
}

View File

@ -0,0 +1,16 @@
package edu.ktu.ds.lab3.demo;
import edu.ktu.ds.lab3.gui.MainWindow;
import java.util.Locale;
/*
* Darbo atlikimo tvarka - čia yra Swing gui pradinė klasė.
*/
public class DemoExecution {
public static void main(String[] args) {
Locale.setDefault(Locale.US); // Suvienodiname skaičių formatus
MainWindow.createAndShowGUI();
}
}

View File

@ -0,0 +1,91 @@
package edu.ktu.ds.lab3.demo;
import edu.ktu.ds.lab3.utils.*;
import java.util.Locale;
import static edu.ktu.ds.lab3.utils.HashMap.DEFAULT_INITIAL_CAPACITY;
import static edu.ktu.ds.lab3.utils.HashMap.DEFAULT_LOAD_FACTOR;
public class ManualTest {
public static void main(String[] args) {
Locale.setDefault(Locale.US); // suvienodiname skaičių formatus
executeTest();
}
public static void executeTest() {
Car car1 = new Car("Renault", "Laguna", 1997, 50000, 1700);
Car car2 = new Car("Renault", "Megane", 2001, 20000, 3500);
Car car3 = new Car("Toyota", "Corolla", 2001, 20000, 8500.8);
Car car4 = new Car("Renault Laguna 2001 115900 7500");
Car car5 = new Car.Builder().buildRandom();
Car car6 = new Car("Honda Civic 2007 36400 8500.3");
Car car7 = new Car("Renault Laguna 2001 115900 7500");
// Atvaizdžio raktų masyvas
String[] carsIds = {"TA156", "TA102", "TA178", "TA126", "TA105", "TA106", "TA107", "TA108"};
// Atvaizdžio reikšmių masyvas
Car[] cars = {car1, car2, car3, car4, car5, car6, car7};
executeCarMapTests(carsIds, cars);
executeCarMapOaTests(carsIds, cars);
}
private static void executeCarMapTests(String[] carsIds, Car[] cars) {
ParsableMap<String, Car> carsMap = new ParsableHashMap<>(
String::new,
Car::new,
DEFAULT_INITIAL_CAPACITY,
DEFAULT_LOAD_FACTOR,
HashManager.HashType.DIVISION
);
for (int id = 0; id < cars.length; id++) {
carsMap.put(carsIds[id], cars[id]);
}
Ks.oun("Porų išsidėstymas atvaizdyje pagal raktus:");
carsMap.println("");
Ks.oun("Ar egzistuoja pora atvaizdyje?");
Ks.oun(carsMap.contains(carsIds[6]));
Ks.oun(carsMap.contains(carsIds[7]));
Ks.oun("Porų išsidėstymas atvaizdyje pagal raktus. Vaizduojami tik raktai:");
carsMap.println("=");
Ks.oun("Atliekame porų paiešką atvaizdyje:");
Ks.oun(carsMap.get(carsIds[2]));
Ks.oun(carsMap.get(carsIds[7]));
Ks.oun("Išspausdiname atvaizdžio poras String eilute:");
Ks.ounn(carsMap);
}
private static void executeCarMapOaTests(String[] carsIds, Car[] cars) {
ParsableMap<String, Car> carsMapOa = new ParsableHashMapOa<>(
String::new,
Car::new,
DEFAULT_INITIAL_CAPACITY,
DEFAULT_LOAD_FACTOR,
HashManager.HashType.DIVISION,
HashMapOa.OpenAddressingType.LINEAR
);
for (int id = 0; id < cars.length; id++) {
carsMapOa.put(carsIds[id], cars[id]);
}
Ks.oun("Porų išsidėstymas atviros adresacijos atvaizdyje pagal raktus:");
carsMapOa.println("");
Ks.oun("Ar egzistuoja pora atviros adresacijos atvaizdyje?");
Ks.oun(carsMapOa.contains(carsIds[6]));
Ks.oun(carsMapOa.contains(carsIds[7]));
Ks.oun("Porų išsidėstymas atviros adresacijos atvaizdyje pagal raktus. Vaizduojami tik raktai:");
carsMapOa.println("=");
Ks.oun("Atliekame porų paiešką atviros adresacijos atvaizdyje:");
Ks.oun(carsMapOa.get(carsIds[2]));
Ks.oun(carsMapOa.get(carsIds[7]));
Ks.oun("Išspausdiname atviros adresacijos atvaizdžio poras String eilute:");
Ks.ounn(carsMapOa);
}
}

View File

@ -0,0 +1,72 @@
package edu.ktu.ds.lab3.gui;
import javax.swing.*;
import java.awt.*;
/**
* Klasė, skirta duomenų išvedimui į Swing GUI
*/
public class KsGui {
private static int lineNr;
private static boolean formatStartOfLine = true;
private static String getStartOfLine() {
return (formatStartOfLine) ? ++lineNr + "| " : "";
}
public static void setFormatStartOfLine(boolean formatStartOfLine) {
KsGui.formatStartOfLine = formatStartOfLine;
}
public static void ou(JTextArea ta, Object o) {
StringBuilder sb = new StringBuilder();
if (o instanceof Iterable) {
((Iterable) o).forEach(p -> sb.append(p).append(System.lineSeparator()));
} else {
sb.append(o.toString());
}
ta.append(sb.toString());
}
public static void oun(JTextArea ta, Object o) {
ou(ta, o);
ta.append(System.lineSeparator());
}
public static void ou(JTextArea ta, Object o, String msg) {
String startOfLine = getStartOfLine();
ta.append(startOfLine + msg + ": ");
oun(ta, o);
}
public static void oun(JTextArea ta, Object o, String msg) {
String startOfLine = getStartOfLine();
ta.append(startOfLine + msg + ": " + System.lineSeparator());
oun(ta, o);
}
public static void ounArgs(JTextArea ta, String format, Object... args) {
String startOfLine = getStartOfLine();
ta.append(startOfLine + String.format(format, args) + System.lineSeparator());
}
public static void ounerr(JTextArea ta, Exception e) {
ta.setBackground(Color.pink);
String startOfLine = getStartOfLine();
ta.append(startOfLine + e.getLocalizedMessage() + System.lineSeparator());
}
public static void ounerr(JTextArea ta, String msg) {
ta.setBackground(Color.pink);
String startOfLine = getStartOfLine();
ta.append(startOfLine + msg + System.lineSeparator());
}
public static void ounerr(JTextArea ta, String msg, String parameter) {
ta.setBackground(Color.pink);
String startOfLine = getStartOfLine();
ta.append(startOfLine + msg + ((parameter == null || parameter.isEmpty())
? "" : ": " + parameter) + System.lineSeparator());
}
}

View File

@ -0,0 +1,540 @@
package edu.ktu.ds.lab3.gui;
import edu.ktu.ds.lab3.demo.Car;
import edu.ktu.ds.lab3.demo.CarsGenerator;
import edu.ktu.ds.lab3.utils.*;
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.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Lab3 langas su Swing'u
* <pre>
* BorderLayout
* (Center) (East)
* |----------scrollTable----------|-scrollEast-|
* | | |
* | | |
* | | |
* | | |
* | table | |
* | | |
* | | |
* | |------------|
* | | panButtons |
* | | |
* |----------------panParam12Events------------|
* |-------scrollParam12---------|-scrollEvents-|
* |-----------|-----------|--------------------|
* | panParam1 | panParam2 | taEvents |
* |-----------|-----------|--------------------|
* (South)
* </pre>
*
* @author darius.matulis@ktu.lt
*/
public class MainWindow extends JFrame implements ActionListener {
private static final ResourceBundle MESSAGES = ResourceBundle.getBundle("edu.ktu.ds.lab3.gui.messages");
private static final int TF_WIDTH = 6;
private static final int NUMBER_OF_BUTTONS = 3;
private final JComboBox<String> cmbCollisionTypes = new JComboBox<>();
private final JComboBox<String> cmbHashFunctions = new JComboBox<>();
private final JTextArea taInput = new JTextArea();
private final Table table = new Table();
private final JScrollPane scrollTable = new JScrollPane(table);
private final JPanel panParam12 = new JPanel();
private final JScrollPane scrollParam12 = new JScrollPane(panParam12);
private final JPanel panParam12Events = new JPanel();
private final JTextArea taEvents = new JTextArea();
private final JScrollPane scrollEvents = new JScrollPane(taEvents);
private final JPanel panEast = new JPanel();
private final JScrollPane scrollEast = new JScrollPane(panEast);
private Panels panParam1, panParam2, panButtons;
private MainWindowMenu mainWindowMenu;
private HashManager.HashType ht = HashManager.HashType.DIVISION;
private ParsableMap<String, Car> map;
private int sizeOfInitialSubSet, sizeOfGenSet, colWidth, initialCapacity;
private float loadFactor;
private final CarsGenerator carsGenerator = new CarsGenerator();
private ArrayList<String> ids;
public MainWindow() {
initComponents();
}
private void initComponents() {
// Formuojamas mėlynos spalvos skydelis (dešinėje pusėje), užpildomi JComboBox'ai
Stream.of(MESSAGES.getString("cmbCollisionType1"),
MESSAGES.getString("cmbCollisionType2"),
MESSAGES.getString("cmbCollisionType3"),
MESSAGES.getString("cmbCollisionType4"))
.forEach(cmbCollisionTypes::addItem);
cmbCollisionTypes.addActionListener(this);
Stream.of(MESSAGES.getString("cmbHashFunction1"),
MESSAGES.getString("cmbHashFunction2"),
MESSAGES.getString("cmbHashFunction3"),
MESSAGES.getString("cmbHashFunction4"))
.forEach(cmbHashFunctions::addItem);
cmbHashFunctions.addActionListener(this);
// Formuojamas mygtukų tinklelis (mėlynas). Naudojama klasė Panels.
panButtons = new Panels(new String[]{
MESSAGES.getString("button1"),
MESSAGES.getString("button2"),
"Random remove"},
1, NUMBER_OF_BUTTONS);
panButtons.getButtons().forEach((btn) -> btn.addActionListener(this));
IntStream.of(1, 2).forEach(p -> panButtons.getButtons().get(p).setEnabled(false));
// Viskas sudedama į vieną (mėlynos spalvos) skydelį
panEast.setLayout(new BoxLayout(panEast, BoxLayout.Y_AXIS));
Stream.of(new JLabel(MESSAGES.getString("border1")),
cmbCollisionTypes,
new JLabel(MESSAGES.getString("border2")),
cmbHashFunctions,
new JLabel(MESSAGES.getString("border3")),
taInput,
panButtons)
.forEach(comp -> {
comp.setAlignmentX(JComponent.LEFT_ALIGNMENT);
panEast.add(Box.createRigidArea(new Dimension(0, 2)));
panEast.add(comp);
});
// Formuojama pirmoji parametrų lentelė (šviesiai žalia). Naudojama klasė Panels.
panParam1 = new Panels(
new String[]{
MESSAGES.getString("lblParam11"),
MESSAGES.getString("lblParam12"),
MESSAGES.getString("lblParam13"),
MESSAGES.getString("lblParam14"),
MESSAGES.getString("lblParam15"),
MESSAGES.getString("lblParam16"),
MESSAGES.getString("lblParam17")},
new String[]{
MESSAGES.getString("tfParam11"),
MESSAGES.getString("tfParam12"),
MESSAGES.getString("tfParam13"),
MESSAGES.getString("tfParam14"),
MESSAGES.getString("tfParam15"),
MESSAGES.getString("tfParam16"),
MESSAGES.getString("tfParam17")},
TF_WIDTH);
// .. tikrinami ivedami parametrai dėl teisingumo. Negali būti neigiami.
IntStream.of(0, 1, 2, 4).forEach(v -> panParam1.getTfOfTable().get(v).setInputVerifier(new NotNegativeNumberVerifier()));
// Tikrinamas įvedamas apkrovimo faktorius. Turi būti (0;1] ribose
panParam1.getTfOfTable().get(3).setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText().trim();
try {
float loadFactor = Float.parseFloat(text);
if (loadFactor <= 0.0 || loadFactor > 1.0) {
input.setBackground(Color.RED);
return false;
}
input.setBackground(Color.WHITE);
return true;
} catch (NumberFormatException e) {
input.setBackground(Color.RED);
return false;
}
}
});
// Formuojama antroji parametrų lentelė (gelsva). Naudojama klasė Panels
panParam2 = new Panels(
new String[]{
MESSAGES.getString("lblParam21"),
MESSAGES.getString("lblParam22"),
MESSAGES.getString("lblParam23"),
MESSAGES.getString("lblParam24"),
MESSAGES.getString("lblParam25"),
MESSAGES.getString("lblParam26"),
MESSAGES.getString("lblParam27")},
new String[]{
MESSAGES.getString("tfParam21"),
MESSAGES.getString("tfParam22"),
MESSAGES.getString("tfParam23"),
MESSAGES.getString("tfParam24"),
MESSAGES.getString("tfParam25"),
MESSAGES.getString("tfParam26"),
MESSAGES.getString("tfParam27")}, TF_WIDTH);
// Dviejų parametrų lentelių skydeliai sudedami į šviesiai pilką skydelį
Stream.of(panParam1, panParam2).forEach(panParam12::add);
// Toliau suformuojamas skydelis šviesiai pilko skydelio ir programos
// įvykių JTextArea
panParam12Events.setLayout(new BorderLayout());
panParam12Events.add(scrollParam12, BorderLayout.WEST);
panParam12Events.add(scrollEvents, BorderLayout.CENTER);
// Kad prijungiant tekstą prie JTextArea vaizdas visada nušoktų į apačią
scrollEvents.getVerticalScrollBar()
.addAdjustmentListener((AdjustmentEvent e) -> taEvents.select(taEvents.getCaretPosition() * taEvents.getFont().getSize(), 0));
// Suformuojamas bendras Lab3 langas su meniu
mainWindowMenu = new MainWindowMenu() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
Object command = ae.getSource();
KsGui.setFormatStartOfLine(true);
if (command.equals(mainWindowMenu.getMenu(0).getItem(0))) {
fileChooseMenu();
} else if (command.equals(mainWindowMenu.getMenu(0).getItem(1))) {
KsGui.ounerr(taEvents, 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(taEvents, e.getMessage());
} catch (Exception e) {
KsGui.ounerr(taEvents, MESSAGES.getString("systemError"));
e.printStackTrace(System.out);
}
}
private void fileChooseMenu() {
JFileChooser fc = new JFileChooser(".");
// 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) {
taEvents.setBackground(Color.white);
File file = fc.getSelectedFile();
mapGeneration(file.getAbsolutePath());
}
}
};
// Meniu juosta patalpinama šiame freime
setJMenuBar(mainWindowMenu);
setLayout(new BorderLayout());
add(scrollEast, BorderLayout.EAST);
add(scrollTable, BorderLayout.CENTER);
add(panParam12Events, BorderLayout.SOUTH);
appearance();
}
/**
* Kosmetika
*/
private void appearance() {
// Rėmeliai
panParam12.setBorder(new TitledBorder(MESSAGES.getString("border4")));
scrollTable.setBorder(new TitledBorder(MESSAGES.getString("border5")));
scrollEvents.setBorder(new TitledBorder(MESSAGES.getString("border6")));
scrollTable.getViewport().setBackground(Color.white);
panParam1.setBackground(new Color(204, 255, 204));// Šviesiai žalia
panParam2.setBackground(new Color(255, 255, 153));// Gelsva
panEast.setBackground(new Color(147, 204, 210));// Blyškiai mėlyna
panButtons.setBackground(new Color(147, 210, 192));
// Antra parametrų lentelė (gelsva) bus neredaguojama
panParam2.getTfOfTable().forEach((comp) -> comp.setEditable(false));
Stream.of(taInput, taEvents).forEach(comp -> {
comp.setBackground(Color.white);
comp.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 11));
});
taEvents.setEditable(false);
scrollEvents.setPreferredSize(new Dimension(350, 0));
}
@Override
public void actionPerformed(ActionEvent ae) {
KsGui.setFormatStartOfLine(true);
try {
System.gc();
System.gc();
System.gc();
taEvents.setBackground(Color.white);
Object source = ae.getSource();
if (source instanceof JButton) {
handleButtons(source);
} else {
boolean comboEquals = source.equals(cmbCollisionTypes) || source.equals(cmbHashFunctions);
if (source instanceof JComboBox && comboEquals) {
IntStream.of(1, 2).forEach(p -> panButtons.getButtons().get(p).setEnabled(false));
}
}
} catch (ValidationException e) {
KsGui.ounerr(taEvents, MESSAGES.getString(e.getMessage()), e.getValue());
} catch (UnsupportedOperationException e) {
KsGui.ounerr(taEvents, e.getMessage());
} catch (Exception e) {
KsGui.ounerr(taEvents, MESSAGES.getString("systemError"));
e.printStackTrace(System.out);
}
}
private void handleButtons(Object source) {
if (source.equals(panButtons.getButtons().get(0))) {
mapGeneration(null);
} else if (source.equals(panButtons.getButtons().get(1))) {
mapPut();
} else if (source.equals(panButtons.getButtons().get(2))) {
mapRemove();
}
}
public void mapGeneration(String filePath) {
// Išjungiami 2 ir 3 mygtukai
IntStream.of(1, 2).forEach(p -> panButtons.getButtons().get(p).setEnabled(false));
// Duomenų nuskaitymas parametrų lentelės (žalios)
readMapParameters();
// Sukuriamas tuščias atvaizdis priklausomai nuo kolizijų tipo
createMap();
// Jei failas nenurodytas - generuojami automobiliai ir talpinami atvaizdyje
if (filePath == null) {
carsGenerator.generateShuffleIdsAndCars(sizeOfGenSet);//, sizeOfInitialSubSet);
for (int i = 0; i < Math.min(sizeOfGenSet, sizeOfInitialSubSet); i++) {
String id = carsGenerator.getCarId();
map.put(
id, //raktas
carsGenerator.getCar() //reikšmė
);
ids.add(id);
}
KsGui.ounArgs(taEvents, MESSAGES.getString("mapPuts"), map.size());
IntStream.of(1, 2).forEach(p -> panButtons.getButtons().get(p).setEnabled(true));
} else { // Jei failas nurodytas skaitoma failo
map.load(filePath);
if (map.isEmpty()) {
KsGui.ounerr(taEvents, MESSAGES.getString("fileWasNotReadOrEmpty"), filePath);
} else {
KsGui.ou(taEvents, MESSAGES.getString("fileWasRead"), filePath);
}
}
// Atvaizdis rodomas lentelėje
table.setModel(
map.getMapModel(),
panParam1.getTfOfTable().get(5).getText(),
map.getMaxChainSize() == -1 ? 1 : map.getMaxChainSize(),
colWidth
);
// Atnaujinamai maišos lentelės parametrai (geltona lentelė)
updateHashtableParameters(false);
// Įjungiami 2 ir 3 mygtukai
IntStream.of(1, 2).forEach(p -> panButtons.getButtons().get(p).setEnabled(true));
}
public void mapPut() throws ValidationException {
Car car = carsGenerator.getCar();
String id = carsGenerator.getCarId();
map.put(
id, // Raktas
car // Reikšmė
);
table.setModel(
map.getMapModel(),
panParam1.getTfOfTable().get(5).getText(),
map.getMaxChainSize() == -1 ? 1 : map.getMaxChainSize(),
colWidth
);
updateHashtableParameters(true);
ids.add(id);
KsGui.oun(taEvents, id + "=" + car, MESSAGES.getString("mapPut"));
}
public void mapRemove() {
Random r = new Random();
int size = ids.size();
if (size == 0) return;
String id = ids.get(r.nextInt(size));
Car car = map.remove(id);
ids.remove(id);
table.setModel(
map.getMapModel(),
panParam1.getTfOfTable().get(5).getText(),
map.getMaxChainSize() == -1 ? 1 : map.getMaxChainSize(),
colWidth
);
updateHashtableParameters(true);
KsGui.oun(taEvents, "Remove " + id);
}
private void readMapParameters() {
int i = 0;
List<JTextField> tfs = panParam1.getTfOfTable();
String[] errorMessages = {"badSizeOfInitialSubSet", "badSizeOfGenSet",
"badInitialCapacity", "badLoadFactor", "badColumnWidth"};
//Patikrinimas dėl parametrų teisingumo
for (JTextField tf : tfs) {
if (tf.getInputVerifier() != null && !tf.getInputVerifier().verify(tf)) {
throw new ValidationException(errorMessages[i], tf.getText());
}
}
//Kai parametrai teisingi - juos nuskaitome
sizeOfInitialSubSet = Integer.parseInt(tfs.get(i++).getText());
sizeOfGenSet = Integer.parseInt(tfs.get(i++).getText());
initialCapacity = Integer.parseInt(tfs.get(i++).getText());
loadFactor = Float.parseFloat(tfs.get(i++).getText());
colWidth = Integer.parseInt(tfs.get(i).getText());
switch (cmbHashFunctions.getSelectedIndex()) {
case 0:
ht = HashManager.HashType.DIVISION;
break;
case 1:
ht = HashManager.HashType.MULTIPLICATION;
break;
case 2:
ht = HashManager.HashType.JCF7;
break;
case 3:
ht = HashManager.HashType.JCF;
break;
default:
ht = HashManager.HashType.DIVISION;
break;
}
}
private void createMap() {
switch (cmbCollisionTypes.getSelectedIndex()) {
case 0:
map = new ParsableHashMap<>(String::new, Car::new, initialCapacity, loadFactor, ht);
break;
case 1:
map = new ParsableHashMapOa<>(String::new, Car::new, initialCapacity, loadFactor, ht, HashMapOa.OpenAddressingType.LINEAR);
break;
case 2:
map = new ParsableHashMapOa<>(String::new, Car::new, initialCapacity, loadFactor, ht, HashMapOa.OpenAddressingType.QUADRATIC);
break;
case 3:
map = new ParsableHashMapOa<>(String::new, Car::new, initialCapacity, loadFactor, ht, HashMapOa.OpenAddressingType.DOUBLE_HASHING);
break;
default:
IntStream.of(1, 2).forEach(p -> panButtons.getButtons().get(p).setEnabled(false));
throw new ValidationException("notImplemented");
}
ids = new ArrayList<>();
}
/**
* Atnaujina parametrus antroje lentelėje. Taip pat tikrina ar pasikeitė
* parametro reikšmė nuo praeito karto. Jei pasikeitė - spalvina jo reikšmę
* raudonai
*
* @param colorize ar spalvinti parametrų reikšmes raudonai
*/
private void updateHashtableParameters(boolean colorize) {
String[] parameters = new String[]{
String.valueOf(map.size()),
String.valueOf(map.getTableCapacity()),
String.valueOf(map.getMaxChainSize()),
String.valueOf(map.getRehashesCounter()),
String.valueOf(map.getLastUpdated()),
// Užimtų maišos lentelės elementų skaičius %
String.format("%3.2f", (double) map.getNumberOfOccupied() / map.getTableCapacity() * 100) + "%"
// .. naujus parametrus tęsiame čia ..
};
for (int i = 0; i < parameters.length; i++) {
String str = panParam2.getTfOfTable().get(i).getText();
if (!str.equals(parameters[i]) && !str.equals(MESSAGES.getString("notExists")) && !str.equals("") && colorize) {
panParam2.getTfOfTable().get(i).setForeground(Color.RED);
} else {
panParam2.getTfOfTable().get(i).setForeground(Color.BLACK);
}
panParam2.getTfOfTable().get(i).setText(parameters[i].equals("-1") ? MESSAGES.getString("notExists") : parameters[i]);
}
}
/**
* Klasė, skirta JTextField objekte įvedamo skaičiaus tikrinimui. Tikrinama
* ar įvestas neneigiamas skaičius
*/
private static class NotNegativeNumberVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
try {
int result = Integer.parseInt(text);
input.setBackground(result >= 0 ? Color.WHITE : Color.RED);
return result >= 0;
} catch (NumberFormatException e) {
input.setBackground(Color.RED);
return false;
}
}
}
public static void createAndShowGUI() {
SwingUtilities.invokeLater(() -> {
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.setIconImage(new ImageIcon(MESSAGES.getString("icon")).getImage());
window.setTitle(MESSAGES.getString("title"));
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setPreferredSize(new Dimension(1300, 700));
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.lab3.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.lab3.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,150 @@
package edu.ktu.ds.lab3.gui;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Klasės objektu galima sukurti du skydelius: parametrų lentelę ir mygtukų
* tinklelį. Skydelyje 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<>();
private List<String> tfTexts = 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");
}
this.tfTexts = Arrays.stream(tfTexts).collect(Collectors.toList());
List<String> lblTextsList = Arrays.stream(lblTexts).collect(Collectors.toList());
if (lblTextsList.size() > this.tfTexts.size()) {
this.tfTexts = Stream.concat(Arrays.stream(tfTexts),
Arrays.stream(new String[lblTextsList.size() - this.tfTexts.size()])).collect(Collectors.toList());
}
initTableOfParameters(columnWidth, lblTextsList);
}
/**
* 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, Arrays.stream(btnNames).collect(Collectors.toList()));
}
private void initTableOfParameters(int columnWidth, List<String> lblTexts) {
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
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);
tfs.add(tf);
add(tf, c);
}
}
private void initGridOfButtons(int gridX, int gridY, List<String> btnNames) {
setLayout(new GridLayout(gridY, gridX, SPACING, SPACING));
int nameIndex = 0;
for (int i = 0; i < gridX; i++) {
for (int j = 0; j < gridY; j++) {
if (nameIndex >= btnNames.size()) {
break;
}
JButton button = new JButton(btnNames.get(nameIndex));
btns.add(button);
add(button);
nameIndex++;
}
}
}
/**
* Grąžinamas parametrų lentelės parametrų sąrašas
*
* @return Grąžinamas parametrų lentelės parametrų sąrašas
*/
public List<String> getParametersOfTable() {
tfTexts.clear();
tfs.forEach(tf -> tfTexts.add(tf.getText()));
return tfTexts;
}
/**
* Grąžinamas parametrų lentelės JTextField objektų sąrašas
*
* @return Grąžinamas parametrų lentelės JTextField objektų sąrašas
*/
public List<JTextField> getTfOfTable() {
return tfs;
}
/**
* Grąžinamas mygtukų tinklelio JButton objektų sąrašas
*
* @return Grąžinamas mygtukų tinklelio JButton objektų sąrašas
*/
public List<JButton> getButtons() {
return btns;
}
}

View File

@ -0,0 +1,83 @@
package edu.ktu.ds.lab3.gui;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.*;
/**
* Klasėje specifikuota maišos lentelės atvaizdavimui skirta lentelė.
*
* @author darius
*/
public class Table extends JTable {
public static final String ARROW = "\u2794";
public void setModel(String[][] tableContent, String delimiter, int maxChainSize, int colWidth) {
if (tableContent == null || delimiter == null) {
throw new IllegalArgumentException("Table content or delimiter is null");
}
if (maxChainSize < 0 || colWidth < 0) {
throw new IllegalArgumentException("Table column width or max chain size is <0: " + colWidth + ", " + maxChainSize);
}
setModel(new TableModel(tableContent, delimiter, maxChainSize));
appearance(colWidth);
}
private void appearance(int colWidth) {
setShowGrid(false);
// Celės stilius - pacentruojame
DefaultTableCellRenderer toCenter = new DefaultTableCellRenderer();
toCenter.setHorizontalAlignment(JLabel.CENTER);
for (int i = 0; i < getColumnCount(); i++) {
if (i == 0) {
getColumnModel().getColumn(i).setPreferredWidth(1);
// Nustatome nulinio stulpelio celių stilių
getColumnModel().getColumn(i).setCellRenderer(toCenter);
} else if (i % 2 != 0) {
getColumnModel().getColumn(i).setPreferredWidth(30);
// Nustatome stulpelių su rodyklėmis celių stilių
getColumnModel().getColumn(i).setCellRenderer(toCenter);
} else {
getColumnModel().getColumn(i).setMaxWidth(colWidth);
getColumnModel().getColumn(i).setMinWidth(colWidth);
}
}
// Lentelės antraštės
getTableHeader().setResizingAllowed(false);
getTableHeader().setReorderingAllowed(false);
getTableHeader().setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 13));
setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 13));
// Išcentruojamos antraštės
((DefaultTableCellRenderer) getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
// Nustatomas tooltips'ų rodymas
String value = (String) getValueAt(row, column);
if (c instanceof JComponent) {
JComponent jc = (JComponent) c;
jc.setToolTipText(value);
}
// Morkine spalva nuspalvinamos celės, kuriose kas nors įrašyta, išskyrus rodyklę
if (value != null && !value.equals("") && !value.equals(ARROW)) {
c.setBackground(Color.ORANGE);
} //Baltai - likusias celes
else {
c.setBackground(Color.WHITE);
}
int rendererWidth = c.getPreferredSize().width;
TableColumn tableColumn = getColumnModel().getColumn(column);
tableColumn.setPreferredWidth(Math.max(rendererWidth + getIntercellSpacing().width, tableColumn.getPreferredWidth()));
return c;
}
}

View File

@ -0,0 +1,56 @@
package edu.ktu.ds.lab3.gui;
import javax.swing.table.AbstractTableModel;
/**
* Swing lentelės modelio klasė
*/
public class TableModel extends AbstractTableModel {
private final String delimiter;
private final String[][] table;
private final int maxChainSize;
public TableModel(String[][] table, String delimiter, int maxChainSize) {
this.table = table;
this.delimiter = delimiter;
this.maxChainSize = maxChainSize;
}
@Override
public Object getValueAt(int row, int col) {
if (row < table.length && col < table[row].length && table[row][col] != null) {
return split(table[row][col], delimiter);
}
return null;
}
@Override
public String getColumnName(int col) {
if (col == 0) {
return "#";
}
if (col % 2 == 0) {
return "(" + (col / 2 - 1) + ")";
}
return "";
}
@Override
public int getColumnCount() {
return maxChainSize * 2 + 1;
}
@Override
public int getRowCount() {
return table.length;
}
private String split(String s, String delimiter) {
int k = s.indexOf(delimiter);
if (k <= 0) {
return s;
}
return s.substring(0, k);
}
}

View File

@ -0,0 +1,24 @@
package edu.ktu.ds.lab3.gui;
/**
* Nuosava situacija, panaudota dialogo struktūrose įvedamų parametrų
* tikrinimui.
*/
public class ValidationException extends RuntimeException {
// Situacijos reikšmė
private final String value;
public ValidationException(String message) {
this(message, "");
}
public ValidationException(String message, String value) {
super(message);
this.value = value;
}
public String getValue() {
return value;
}
}

View File

@ -0,0 +1,48 @@
package edu.ktu.ds.lab3.utils;
/**
* Interfeisu aprašomas maišos lentelės charakteristikas skaičiuojantis
* Atvaizdžio ADT
*
* @param <K> raktas
* @param <V> reikšmė
*/
public interface EvaluableMap<K, V> extends Map<K, V> {
/**
* Grąžina maksimalų grandinėlės ilgį.
*
* @return Maksimalus grandinėlės ilgis.
*/
default int getMaxChainSize(){
return -1;
}
/**
* Grąžina maišos lentelę formuojant įvykusių permaišymų kiekį.
*
* @return Permaišymų kiekis.
*/
int getRehashesCounter();
/**
* Grąžina maišos lentelės talpą.
*
* @return Maišos lentelės talpa.
*/
int getTableCapacity();
/**
* Grąžina paskutinio papildyto maišos lentelės masyvo elemento indeksą.
*
* @return Paskutinio papildyto maišos lentelės masyvo elemento indeksą.
*/
int getLastUpdated();
/**
* Grąžina maišos lentelės masyvo užimtų elementų kiekį.
*
* @return maišos lentelės masyvo užimtų elementų kiekį.
*/
int getNumberOfOccupied();
}

View File

@ -0,0 +1,30 @@
package edu.ktu.ds.lab3.utils;
public class HashManager {
public enum HashType {
DIVISION,
MULTIPLICATION,
JCF7, //Java Collections Framework 7
JCF //Java Collections Framework 8/11/17
}
public static int hash(int hashcode, int tableLength, HashType hashType) {
switch (hashType) {
case DIVISION:
return Math.abs(hashcode) % tableLength;
case MULTIPLICATION:
double k = (Math.sqrt(5) - 1) / 2;
return (int) (((k * Math.abs(hashcode)) % 1) * tableLength);
case JCF7:
hashcode ^= (hashcode >>> 20) ^ (hashcode >>> 12);
hashcode = hashcode ^ (hashcode >>> 7) ^ (hashcode >>> 4);
return hashcode & (tableLength - 1);
case JCF:
hashcode = hashcode ^ (hashcode >>> 16);
return hashcode & (tableLength - 1);
default:
throw new IllegalArgumentException("HashType is unknown");
}
}
}

View File

@ -0,0 +1,361 @@
package edu.ktu.ds.lab3.utils;
import java.util.Arrays;
/**
* Porų ("maping'ų") raktas-reikšmė objektų kolekcijos - atvaizdžio realizacija
* maišos lentele, kolizijas sprendžiant atskirų grandinėlių (angl. separate
* chaining) metodu. Neužmirškite, jei poros raktas - nuosavos klasės objektas,
* pvz. klasės Car objektas, klasėje būtina perdengti metodus equals(Object o)
* ir hashCode().
*
* @param <K> atvaizdžio raktas
* @param <V> atvaizdžio reikšmė
* @author darius.matulis@ktu.lt
* @Užduotis Peržiūrėkite ir išsiaiškinkite pateiktus metodus.
*/
public class HashMap<K, V> implements EvaluableMap<K, V> {
public static final int DEFAULT_INITIAL_CAPACITY = 8;
public static final float DEFAULT_LOAD_FACTOR = 0.75f;
public static HashManager.HashType DEFAULT_HASH_TYPE = HashManager.HashType.DIVISION;
// Maišos lentelė
protected Node<K, V>[] table;
// Lentelėje esančių raktas-reikšmė porų kiekis
protected int size = 0;
// Apkrovimo faktorius
protected float loadFactor;
// Maišos metodas
protected HashManager.HashType ht;
//--------------------------------------------------------------------------
// Maišos lentelės įvertinimo parametrai
//--------------------------------------------------------------------------
// Maksimalus suformuotos maišos lentelės grandinėlės ilgis
protected int maxChainSize = 0;
// Permaišymų kiekis
protected int rehashesCounter = 0;
// Paskutinės patalpintos poros grandinėlės indeksas maišos lentelėje
protected int lastUpdatedChain = 0;
// Lentelės grandinėlių skaičius
protected int chainsCounter = 0;
/* Klasėje sukurti 4 perkloti konstruktoriai, nustatantys atskirus maišos
* lentelės parametrus. Jei kuris nors parametras nėra nustatomas -
* priskiriama standartinė reikšmė.
*/
public HashMap() {
this(DEFAULT_HASH_TYPE);
}
public HashMap(HashManager.HashType ht) {
this(DEFAULT_INITIAL_CAPACITY, ht);
}
public HashMap(int initialCapacity, HashManager.HashType ht) {
this(initialCapacity, DEFAULT_LOAD_FACTOR, ht);
}
public HashMap(float loadFactor, HashManager.HashType ht) {
this(DEFAULT_INITIAL_CAPACITY, loadFactor, ht);
}
public HashMap(int initialCapacity, float loadFactor, HashManager.HashType ht) {
if (initialCapacity <= 0) {
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
}
if ((loadFactor <= 0.0) || (loadFactor > 1.0)) {
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
}
this.table = new Node[initialCapacity];
this.loadFactor = loadFactor;
this.ht = ht;
}
/**
* Patikrinama ar atvaizdis yra tuščias.
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* Grąžinamas atvaizdyje esančių porų kiekis.
*
* @return Grąžinamas atvaizdyje esančių porų kiekis.
*/
@Override
public int size() {
return size;
}
/**
* Išvalomas atvaizdis.
*/
@Override
public void clear() {
Arrays.fill(table, null);
size = 0;
lastUpdatedChain = 0;
maxChainSize = 0;
rehashesCounter = 0;
chainsCounter = 0;
}
/**
* Patikrinama ar pora egzistuoja atvaizdyje.
*
* @param key raktas.
* @return Patikrinama ar pora egzistuoja atvaizdyje.
*/
@Override
public boolean contains(K key) {
if (key == null) {
throw new IllegalArgumentException("Key is null in contains(K key)");
}
return get(key) != null;
}
/**
* Atvaizdis papildomas nauja pora.
*
* @param key raktas,
* @param value reikšmė.
* @return Atvaizdis papildomas nauja pora.
*/
@Override
public V put(K key, V value) {
if (key == null || value == null) {
throw new IllegalArgumentException("Key or value is null in put(K key, V value)");
}
int index = HashManager.hash(key.hashCode(), table.length, ht);
if (table[index] == null) {
chainsCounter++;
}
Node<K, V> node = getInChain(key, table[index]);
if (node == null) {
table[index] = new Node<>(key, value, table[index]);
size++;
if (size > table.length * loadFactor) {
rehash();
} else {
lastUpdatedChain = index;
}
} else {
node.value = value;
lastUpdatedChain = index;
}
return value;
}
/**
* Grąžinama atvaizdžio poros reikšmė.
*
* @param key raktas.
* @return Grąžinama atvaizdžio poros reikšmė.
*/
@Override
public V get(K key) {
if (key == null) {
throw new IllegalArgumentException("Key is null in get(K key)");
}
int index = HashManager.hash(key.hashCode(), table.length, ht);
Node<K, V> node = getInChain(key, table[index]);
return node == null ? null : node.value;
}
/**
* Pora pašalinama atvaizdžio.
*
* @param key Pora pašalinama atvaizdžio.
* @return value reikšmė.
*/
@Override
public V remove(K key) {
int index = HashManager.hash(key.hashCode(), table.length, ht);
Node<K, V> node = getInChain(key, table[index]);
if (node == null) return null;
if (node == table[index]) {
table[index] = node.next;
} else {
Node<K, V> prevNode = table[index];
while (prevNode.next != node) {
prevNode.next = prevNode.next;
}
prevNode.next = node.next;
}
lastUpdatedChain = index;
size--;
if (table[index] == null) {
chainsCounter--;
}
// Max chain size asimptoninis sudetingumas yra O(n)
/*maxChainSize = 0;
for (int i = 0; i < table.length; i++) {
int chainSize = 0;
for (Node<K, V> n = table[i]; n != null; n = n.next) {
chainSize++;
}
maxChainSize = Math.max(maxChainSize, chainSize);
}*/
return node.value;
}
/**
* Permaišymas
*/
private void rehash() {
HashMap<K, V> newMap = new HashMap<>(table.length * 2, loadFactor, ht);
for (int i = 0; i < table.length; i++) {
while (table[i] != null) {
newMap.put(table[i].key, table[i].value);
table[i] = table[i].next;
}
}
table = newMap.table;
maxChainSize = newMap.maxChainSize;
chainsCounter = newMap.chainsCounter;
lastUpdatedChain = newMap.lastUpdatedChain;
rehashesCounter++;
}
/**
* Paieška vienoje grandinėlėje
*
* @param key
* @param node
* @return
*/
private Node<K, V> getInChain(K key, Node<K, V> node) {
if (key == null) {
throw new IllegalArgumentException("Key is null in getInChain(K key, Node node)");
}
int chainSize = 0;
for (Node<K, V> n = node; n != null; n = n.next) {
chainSize++;
if (n.key.equals(key)) {
return n;
}
}
maxChainSize = Math.max(maxChainSize, chainSize + 1);
return null;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (Node<K, V> node : table) {
if (node != null) {
for (Node<K, V> n = node; n != null; n = n.next) {
result.append(n).append(System.lineSeparator());
}
}
}
return result.toString();
}
public boolean replace(K key, V oldValue, V newValue) {
int index = HashManager.hash(key.hashCode(), table.length, ht);
Node<K, V> node = getInChain(key, table[index]);
if (node == null || node.value != oldValue) return false;
node.value = newValue;
return true;
}
public boolean containsValue(Object value) {
for (int i = 0; i < table.length; i++) {
for (Node<K, V> node = table[i]; node != null; node = node.next) {
if (node.value.equals(value)) {
return true;
}
}
}
return false;
}
/**
* Grąžina maksimalų grandinėlės ilgį.
*
* @return Maksimalus grandinėlės ilgis.
*/
@Override
public int getMaxChainSize() {
return maxChainSize;
}
/**
* Grąžina formuojant maišos lentelę įvykusių permaišymų kiekį.
*
* @return Permaišymų kiekis.
*/
@Override
public int getRehashesCounter() {
return rehashesCounter;
}
/**
* Grąžina maišos lentelės talpą.
*
* @return Maišos lentelės talpa.
*/
@Override
public int getTableCapacity() {
return table.length;
}
/**
* Grąžina paskutinės papildytos grandinėlės indeksą.
*
* @return Paskutinės papildytos grandinėlės indeksas.
*/
@Override
public int getLastUpdated() {
return lastUpdatedChain;
}
/**
* Grąžina grandinėlių kiekį.
*
* @return Grandinėlių kiekis.
*/
@Override
public int getNumberOfOccupied() {
return chainsCounter;
}
protected static class Node<K, V> {
// Raktas
protected K key;
// Reikšmė
protected V value;
// Rodyklė į sekantį grandinėlės mazgą
protected Node<K, V> next;
protected Node() {
}
protected Node(K key, V value, Node<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
@Override
public String toString() {
return key + "=" + value;
}
}
}

View File

@ -0,0 +1,320 @@
/*
* 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.lab3.utils;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author Darius
*/
public class HashMapOa<K, V> implements EvaluableMap<K, V> {
public enum OpenAddressingType {
LINEAR,
QUADRATIC,
DOUBLE_HASHING
}
public static final int DEFAULT_INITIAL_CAPACITY = 8;
public static final float DEFAULT_LOAD_FACTOR = 0.75f;
public static HashManager.HashType DEFAULT_HASH_TYPE = HashManager.HashType.DIVISION;
public static final OpenAddressingType DEFAULT_OPEN_ADDRESSING_TYPE = OpenAddressingType.QUADRATIC;
// Maišos lentelė
protected Entry<K, V>[] table;
// Lentelėje esančių raktas-reikšmė porų kiekis
protected int size = 0;
// Apkrovimo faktorius
protected float loadFactor;
// Maišos metodas
protected HashManager.HashType ht;
//--------------------------------------------------------------------------
// Maišos lentelės įvertinimo parametrai
//--------------------------------------------------------------------------
// Permaišymų kiekis
protected int rehashesCounter = 0;
// Paskutinio papildyto masyvo elemento indeksas maišos lentelėje
protected int lastUpdated = 0;
// Lentelėje užimtų elementų skaičius
protected int numberOfOccupied = 0;
private final Entry<K, V> DELETED = new Entry<>();
private final OpenAddressingType oaType;
public HashMapOa() {
this(DEFAULT_HASH_TYPE);
}
public HashMapOa(HashManager.HashType ht) {
this(DEFAULT_INITIAL_CAPACITY, ht);
}
public HashMapOa(int initialCapacity, HashManager.HashType ht) {
this(initialCapacity, DEFAULT_LOAD_FACTOR, ht, DEFAULT_OPEN_ADDRESSING_TYPE);
}
public HashMapOa(float loadFactor, HashManager.HashType ht) {
this(DEFAULT_INITIAL_CAPACITY, loadFactor, ht, DEFAULT_OPEN_ADDRESSING_TYPE);
}
public HashMapOa(int initialCapacity, float loadFactor, HashManager.HashType ht, OpenAddressingType oaType) {
if (initialCapacity <= 0) {
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
}
if ((loadFactor <= 0.0) || (loadFactor > 1.0)) {
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
}
this.table = new Entry[initialCapacity];
this.loadFactor = loadFactor;
this.ht = ht;
this.oaType = oaType;
}
/**
* Patikrinama ar atvaizdis yra tuščias.
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* Grąžinamas atvaizdyje esančių porų kiekis.
*
* @return Grąžinamas atvaizdyje esančių porų kiekis.
*/
@Override
public int size() {
return size;
}
/**
* Išvalomas atvaizdis.
*/
@Override
public void clear() {
Arrays.fill(table, null);
size = 0;
lastUpdated = 0;
rehashesCounter = 0;
numberOfOccupied = 0;
}
@Override
public boolean contains(K key) {
if (key == null) {
throw new IllegalArgumentException("Key is null in contains(K key)");
}
return get(key) != null;
}
@Override
public V put(K key, V value) {
if (key == null || value == null) {
throw new IllegalArgumentException("Key or value is null in put(K key, V value)");
}
int position = findPosition(key, true);
if (position == -1) {
rehash();
return put(key, value);
}
if (table[position] == null || DELETED.equals(table[position])) {
table[position] = new Entry(key, value);
size++;
if (size > table.length * loadFactor) {
rehash();
} else {
numberOfOccupied++;
lastUpdated = position;
}
} else {
table[position].value = value;
lastUpdated = position;
}
return value;
}
@Override
public V get(K key) {
if (key == null) {
throw new IllegalArgumentException("Key is null in get(K key)");
}
int position = findPosition(key, false);
if (position != -1 && table[position] != null && table[position] != DELETED) {
return table[position].value;
}
return null;
}
@Override
public V remove(K key) {
if (key == null) {
throw new IllegalArgumentException("Key is null in get(K key)");
}
int position = findPosition(key, false);
if (position == -1 || table[position] == null) return null;
V value = table[position].value;
if (value == null || value == DELETED) return null;
table[position] = DELETED;
lastUpdated = position;
numberOfOccupied--;
size--;
return value;
}
@Override
public String toString() {
return Arrays.stream(table)
.filter(entry -> entry != null && !DELETED.equals(entry))
.map(Entry::toString)
.collect(Collectors.joining(System.lineSeparator()));
}
private void rehash() {
HashMapOa<K, V> newMap = new HashMapOa<>(table.length * 2, loadFactor, ht, oaType);
Arrays.stream(table).filter(Objects::nonNull).forEach(kvEntry -> newMap.put(kvEntry.key, kvEntry.value));
table = newMap.table;
numberOfOccupied = newMap.numberOfOccupied;
lastUpdated = newMap.lastUpdated;
rehashesCounter++;
}
private int findPosition(K key, boolean stopAtDeleted) {
int index = HashManager.hash(key.hashCode(), table.length, ht);
int position = index;
for (int i = 0; i < table.length; i++) {
if (table[position] == null) {
return position;
}
if (DELETED.equals(table[position]) && stopAtDeleted) {
return position;
}
if (!DELETED.equals(table[position]) && table[position].key.equals(key)) {
return position;
}
position = calculatePosition(index, i, key);
}
return -1;
}
private int calculatePosition(int index, int i, K key) {
switch (oaType) {
case LINEAR:
return (index + i + 1) % table.length;
case QUADRATIC:
return (index + (i + 1) * (i + 1)) % table.length;
case DOUBLE_HASHING:
return (index + i * (7 - Math.abs(key.hashCode()) % 7)) % table.length;
}
return index;
}
/**
* Grąžina formuojant maišos lentelę įvykusių permaišymų kiekį.
*
* @return Permaišymų kiekis.
*/
@Override
public int getRehashesCounter() {
return rehashesCounter;
}
/**
* Grąžina maišos lentelės talpą.
*
* @return Maišos lentelės talpa.
*/
@Override
public int getTableCapacity() {
return table.length;
}
/**
* Grąžina paskutinio papildyto maišos lentelės masyvo elemento indeksą.
*
* @return Paskutinio papildyto maišos lentelės masyvo elemento indeksą.
*/
@Override
public int getLastUpdated() {
return lastUpdated;
}
/**
* Grąžina užimtų maišos lentelės masyvo elementų kiekį.
*
* @return Užimtų maišos lentelės masyvo elementų kiekis
*/
@Override
public int getNumberOfOccupied() {
return numberOfOccupied;
}
public boolean replace(K key, V oldValue, V newValue) {
if (key == null) {
throw new IllegalArgumentException("Key is null in get(K key)");
}
int position = findPosition(key, false);
if (position == -1) return false;
V value = table[position].value;
if (!(value.equals(oldValue) || (value == DELETED && oldValue == null))) return false;
table[position].value = newValue;
lastUpdated = position;
numberOfOccupied--;
size--;
return true;
}
public boolean containsValue(Object value) {
for (Entry<K, V> entry : table) {
if (entry.value.equals(value)) {
return true;
}
}
return false;
}
protected static class Entry<K, V> {
// Raktas
protected K key;
// Reikšmė
protected V value;
protected Entry() {
}
protected Entry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return key + "=" + value;
}
}
}

View File

@ -0,0 +1,218 @@
package edu.ktu.ds.lab3.utils;
import java.io.*;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static edu.ktu.ds.lab3.gui.Table.ARROW;
import static java.util.stream.Collectors.summarizingInt;
/**
* 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) {
if (formatStartOfLine) {
sout.printf("%s\n", obj);
} else {
sout.println(obj);
}
}
static public void oufln(String format, Object... args) {
sout.printf(format, args);
sout.println();
}
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);
}
public static void printMapModel(String delimiter, String[][] mapModel) {
java.util.Map<Boolean, IntSummaryStatistics> mappingsStatistics = summaryStatistics(mapModel, delimiter);
for (String[] row : mapModel) {
for (int j = 0; j < row.length; j++) {
String format;
if (j == 0) { // pirmas stulpelis, pvz: [ 0 ]
format = "%" + (mappingsStatistics.get(Boolean.FALSE).getMax() + 1) + "s";
} else { // likę stulpeliai
format = j % 2 == 1 ? "%-2s" : "%-" + (mappingsStatistics.get(Boolean.TRUE).getMax() + 1) + "s";
}
String value = row[j];
Ks.ouf(format, (value == null ? "" : split(value, delimiter) + " "));
}
Ks.oufln("");
}
}
private static Map<Boolean, IntSummaryStatistics> summaryStatistics(String[][] mapModel, String delimiter) {
Function<String, Boolean> groupingFunction = s -> !s.equals(ARROW) && !s.startsWith("[") && !s.endsWith("]");
return Arrays
.stream(mapModel)
.flatMap(Arrays::stream)
.map(s -> split(s, delimiter))
.collect(Collectors.groupingBy(groupingFunction, summarizingInt(String::length)));
}
private static String split(String s, String delimiter) {
int k = s.indexOf(delimiter);
if (k <= 0) {
return s;
}
return s.substring(0, k);
}
}

View File

@ -0,0 +1,82 @@
package edu.ktu.ds.lab3.utils;
/**
* Interfeisu aprašomas Atvaizdžio ADT.
*
* @param <K> Atvaizdžio poros raktas
* @param <V> Atvaizdžio poros reikšmė
*/
public interface Map<K, V> {
/**
* Patikrinama ar atvaizdis yra tuščias.
*
* @return true, jei tuščias
*/
boolean isEmpty();
/**
* Grąžinamas atvaizdyje esančių porų kiekis.
*
* @return Grąžinamas atvaizdyje esančių porų kiekis.
*/
int size();
/**
* Išvalomas atvaizdis.
*/
void clear();
/**
* Atvaizdis papildomas nauja pora.
*
* @param key raktas,
* @param value reikšmė.
* @return Grąžinama atvaizdžio poros reikšmė.
*/
V put(K key, V value);
/**
* Grąžinama atvaizdžio poros reikšmė.
*
* @param key raktas.
* @return Grąžinama atvaizdžio poros reikšmė.
*/
V get(K key);
/**
* atvaizdžio pašalinama pora.
*
* @param key raktas.
* @return Grąžinama pašalinta atvaizdžio poros reikšmė.
*/
V remove(K key);
/**
* Patikrinama ar atvaizdyje egzistuoja pora su raktu key.
*
* @param key raktas.
* @return true, jei atvaizdyje egzistuoja pora su raktu key, kitu atveju - false
*/
boolean contains(K key);
/**
* Pakeičia atvaizdyje egzistuojantį raktą ir atitinkančią reikšmę naują reikšme ir grąžina true.
* Jei raktas neegzistuoja atvaizdyje, ar jo reikšmė neatitinka metodo argumente nurodytos senosios reikšmės,
* pakeitimas nevykdomas ir gražinama false.
*
* @param key raktas.
* @param oldValue sena reikšmė.
* @param newValue nauja reikšmė.
* @return true, jei pakeitimas įvyko
*/
boolean replace(K key, V oldValue, V newValue);
/**
* Patikrinama ar atvaizdyje egzistuoja vienas ar daugiau raktų metodo argumente nurodytai reikšmei
*
* @param value reikšmė.
* @return true, jei atvaizdyje egzistuoja vienas ar daugiau raktų metodo argumente nurodytai reikšmei
*/
boolean containsValue(Object value);
}

View File

@ -0,0 +1,17 @@
package edu.ktu.ds.lab3.utils;
/**
* @author Eimutis Karčiauskas, KTU IF Programų inžinerijos katedra
* <p>
* 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> {
/**
* Suformuoja objektą teksto eilutės
*
* @param dataString
*/
void parse(String dataString);
}

View File

@ -0,0 +1,140 @@
package edu.ktu.ds.lab3.utils;
import edu.ktu.ds.lab3.demo.CarsGenerator;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import static edu.ktu.ds.lab3.gui.Table.ARROW;
public class ParsableHashMap<K, V extends Parsable<V>> extends HashMap<K, V> implements ParsableMap<K, V> {
private final Function<String, K> keyCreateFunction; // funkcija bazinio rakto objekto kūrimui
private final Function<String, V> valueCreateFunction; // funkcija bazinio reikšmės objekto kūrimui
/**
* Konstruktorius su funkcija bazinių rakto ir reikšmės objektų kūrimui
*
* @param keyCreateFunction
* @param valueCreateFunction
* @param ht
*/
public ParsableHashMap(Function<String, K> keyCreateFunction,
Function<String, V> valueCreateFunction,
HashManager.HashType ht) {
this(keyCreateFunction, valueCreateFunction, DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, ht);
}
/**
* Konstruktorius su funkcija bazinių rakto ir reikšmės objektų kūrimui
*
* @param keyCreateFunction
* @param valueCreateFunction
* @param initialCapacity
* @param loadFactor
* @param ht
*/
public ParsableHashMap(Function<String, K> keyCreateFunction,
Function<String, V> valueCreateFunction,
int initialCapacity,
float loadFactor,
HashManager.HashType ht) {
super(initialCapacity, loadFactor, ht);
this.keyCreateFunction = keyCreateFunction;
this.valueCreateFunction = valueCreateFunction;
}
@Override
public V put(String key, String value) {
return super.put(
create(keyCreateFunction, key, "Nenustatyta raktų kūrimo funkcija"),
create(valueCreateFunction, value, "Nenustatyta reikšmių kūrimo funkcija")
);
}
/**
* Suformuoja atvaizdį 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), StandardCharsets.UTF_8)) {
fReader.lines()
.map(String::trim)
.filter(line -> !line.isEmpty())
.forEach(line -> put(CarsGenerator.generateId(), line));
} catch (FileNotFoundException e) {
Ks.ern("Tinkamas duomenų failas nerastas: " + e.getLocalizedMessage());
} catch (IOException | UncheckedIOException e) {
Ks.ern("Failo skaitymo klaida: " + e.getLocalizedMessage());
}
}
/**
* Išsaugoja sąrašą faile fName tekstiniu formatu tinkamu vėlesniam
* skaitymui
*
* @param filePath
*/
@Override
public void save(String filePath) {
throw new UnsupportedOperationException("Atvaizdžio išsaugojimas.. šiuo metu nepalaikomas");
}
/**
* Atvaizdis spausdinamas į Ks.ouf("")
*
* @param delimiter Atvaizdžio poros toString() eilutės kirtiklis
*/
@Override
public void println(String delimiter) {
if (super.isEmpty()) {
Ks.oun("Atvaizdis yra tuščias");
return;
}
Ks.oufln("****** Atvaizdis ******");
Ks.printMapModel(delimiter, getMapModel());
Ks.oufln("****** Bendras porų kiekis yra " + super.size());
}
@Override
public String[][] getMapModel() {
String[][] result = new String[table.length][];
int count = 0;
for (Node<K, V> n : table) {
List<String> list = new ArrayList<>();
list.add("[ " + count + " ]");
while (n != null) {
list.add(ARROW);
list.add(n.toString());
n = n.next;
}
result[count] = list.toArray(new String[0]);
count++;
}
return result;
}
private static <T, R> R create(Function<T, R> function, T data, String errorMessage) {
return Optional.ofNullable(function)
.map(f -> f.apply(data))
.orElseThrow(() -> new IllegalStateException(errorMessage));
}
}

View File

@ -0,0 +1,141 @@
package edu.ktu.ds.lab3.utils;
import edu.ktu.ds.lab3.demo.CarsGenerator;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import static edu.ktu.ds.lab3.gui.Table.ARROW;
public class ParsableHashMapOa<K, V extends Parsable<V>> extends HashMapOa<K, V> implements ParsableMap<K, V> {
private final Function<String, K> keyCreateFunction; // funkcija bazinio rakto objekto kūrimui
private final Function<String, V> valueCreateFunction; // funkcija bazinio reikšmės objekto kūrimui
/**
* Konstruktorius su funkcija bazinių rakto ir reikšmės objektų kūrimui
*
* @param keyCreateFunction
* @param valueCreateFunction
* @param ht
*/
public ParsableHashMapOa(Function<String, K> keyCreateFunction,
Function<String, V> valueCreateFunction,
HashManager.HashType ht,
OpenAddressingType oaType) {
this(keyCreateFunction, valueCreateFunction, DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, ht, oaType);
}
/**
* Konstruktorius su funkcija bazinių rakto ir reikšmės objektų kūrimui
*
* @param keyCreateFunction
* @param valueCreateFunction
* @param initialCapacity
* @param loadFactor
* @param ht
*/
public ParsableHashMapOa(Function<String, K> keyCreateFunction,
Function<String, V> valueCreateFunction,
int initialCapacity,
float loadFactor,
HashManager.HashType ht,
OpenAddressingType oaType) {
super(initialCapacity, loadFactor, ht, oaType);
this.keyCreateFunction = keyCreateFunction;
this.valueCreateFunction = valueCreateFunction;
}
@Override
public V put(String key, String value) {
return super.put(
create(keyCreateFunction, key, "Nenustatyta raktų kūrimo funkcija"),
create(valueCreateFunction, value, "Nenustatyta reikšmių kūrimo funkcija")
);
}
/**
* Suformuoja atvaizdį 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), StandardCharsets.UTF_8)) {
fReader.lines()
.map(String::trim)
.filter(line -> !line.isEmpty())
.forEach(line -> put(CarsGenerator.generateId(), line));
} catch (FileNotFoundException e) {
Ks.ern("Tinkamas duomenų failas nerastas: " + e.getLocalizedMessage());
} catch (IOException | UncheckedIOException e) {
Ks.ern("Failo skaitymo klaida: " + e.getLocalizedMessage());
}
}
/**
* Išsaugoja sąrašą faile fName tekstiniu formatu tinkamu vėlesniam
* skaitymui
*
* @param filePath
*/
@Override
public void save(String filePath) {
throw new UnsupportedOperationException("Atvaizdžio išsaugojimas.. šiuo metu nepalaikomas");
}
/**
* Atvaizdis spausdinamas į Ks.ouf("")
*
* @param delimiter Atvaizdžio poros toString() eilutės kirtiklis
*/
@Override
public void println(String delimiter) {
if (super.isEmpty()) {
Ks.oun("Atvaizdis yra tuščias");
return;
}
Ks.oufln("****** Atvaizdis ******");
Ks.printMapModel(delimiter, getMapModel());
Ks.oufln("****** Bendras porų kiekis yra " + super.size());
}
@Override
public String[][] getMapModel() {
String[][] result = new String[table.length][];
int count = 0;
for (Entry<K, V> n : table) {
List<String> list = new ArrayList<>();
list.add("[ " + count + " ]");
if (n != null && n.key != null) {
list.add(ARROW);
list.add(n.toString());
}
result[count++] = list.toArray(new String[0]);
}
return result;
}
private static <T, R> R create(Function<T, R> function, T data, String errorMessage) {
return Optional.ofNullable(function)
.map(f -> f.apply(data))
.orElseThrow(() -> new IllegalStateException(errorMessage));
}
}

View File

@ -0,0 +1,26 @@
package edu.ktu.ds.lab3.utils;
/**
* @param <K>
* @param <V>
*/
public interface ParsableMap<K, V> extends EvaluableMap<K, V> {
V put(String key, String value);
void load(String filePath);
void save(String filePath);
void println(String delimiter);
/**
* Grąžina suformatuotą maišos lentelės turinį atvaizdavimui ekrane. Pvz.:
* [0] -> Pora1 -> Pora3
* [1] -> Pora4 -> Pora2
* ...
*
* @return Grąžina maišos lentelės turinį dvimačiu masyvu
*/
String[][] getMapModel();
}

View File

@ -0,0 +1,86 @@
title=KTU IF LD3. Mai\u0161os lentel\u0117s duomen\u0173 strukt\u016br\u0173 tiriamasis darbas
author=Autorius: Vardenis Pavardenis, IF-x/x\nemail: vardenis.pavardenis@ktu.edu\n\u012era\u0161ykite savo rekvizitus.
icon=ktu.png
# Meniu pavadinimai
menu1=Failas
menu2=Pagalba
menuItem11=Atidaryti..
menuItem12=I\u0161saugoti..
menuItem13=I\u0161eiti
menuItem21=Apie..
# R\u0117meli\u0173 pavadinimai
border1=Kolizij\u0173 sprendimo metodas:
border2=Mai\u0161os funkcija:
border3=Duomen\u0173 \u012fvedimas:
border4=Parametrai:
border5=Atvaizdis mai\u0161os lentel\u0117je:
border6=\u012evyki\u0173 \u017eurnalas:
# Mygtuk\u0173 pavadinimai
button1=Generuoti atvaizd\u012f
button2=Papildyti atvaizd\u012f i\u0161 aib\u0117s
button3=J\u016bs\u0173 sukurta funkcija
# Pirmos lentel\u0117s parametrai
lblParam11=Pradin\u0117 por\u0173 aib\u0117s imtis
lblParam12=Generuojamos por\u0173 aib\u0117s dydis
lblParam13=Pradinis mai\u0161os lentel\u0117s dydis
lblParam14=Apkrovimo faktorius (0,1]
lblParam15=Stulpelio plotis
lblParam16=Poros teksto kirtiklis
lblParam17=J\u016bs\u0173 parametras
tfParam11=10
tfParam12=100
tfParam13=8
tfParam14=0.75
tfParam15=180
tfParam16=
tfParam17=
# Antros lentel\u0117s parametrai
lblParam21=Por\u0173 kiekis mai\u0161os lentel\u0117je
lblParam22=Mai\u0161os lentel\u0117s dydis
lblParam23=Ilgiausia grandin\u0117l\u0117
lblParam24=Permai\u0161ym\u0173 kiekis
lblParam25=Paskutinio papildyto indeksas
lblParam26=Mai\u0161os lentel\u0117s u\u017epildymas
lblParam27=J\u016bs\u0173 parametras
tfParam21=0
tfParam22=0
tfParam23=0
tfParam24=0
tfParam25=0
tfParam26=0
tfParam27=
cmbCollisionType1=Atskiros grandin\u0117l\u0117s
cmbCollisionType2=Atv. adresacija. Tiesinis d\u0117stymas
cmbCollisionType3=Atv. adresacija. Kvadratinis d\u0117stymas
cmbCollisionType4=Atv. adresacija. Dviguba mai\u0161a
cmbHashFunction1=Dalyba
cmbHashFunction2=Daugyba
cmbHashFunction3=I\u0161 Java7 Collections Framework
cmbHashFunction4=I\u0161 Java8/11/17 Collections Framework
mapPuts=Atvaizdis papildytas por\u0173 skai\u010diumi: %s
mapPut=Atvaizdis papildytas pora i\u0161 sugeneruotos por\u0173 aib\u0117s
fileWasRead=Failas perskaitytas
fileWasNotReadOrEmpty=Failas neperskaitytas arba yra tu\u0161\u010dias
notExists=N\u0117ra
#errors
systemError=Sistemin\u0117 klaida. \u017di\u016br\u0117ti konsol\u0117je
badSizeOfInitialSubSet=Netinkama pradin\u0117 por\u0173 aib\u0117s imtis
badSizeOfGenSet=Netinkamas generuojamos por\u0173 aib\u0117s dydis
badInitialCapacity=Netinkamas pradinis mai\u0161os lentel\u0117s dydis
badLoadFactor=Netinkamas apkrovimo faktorius (0;1]
badColumnWidth=Netinkamas stulpelio plotis
notImplemented=Dar ne\u012fdiegta
carsNotGenerated=Automobiliai nesugeneruoti
carsIdsNotGenerated=Automobili\u0173 id nesugeneruoti
allSetStoredToMap=Visa sugeneruota aib\u0117 patalpinta atvaizdyje
allKeysStoredToMap=Visi sugeneruoti raktai i\u0161naudoti

View File

@ -0,0 +1,14 @@
package edu.ktu.ds.lab3.demo;
import org.junit.Assert;
import org.junit.Test;
public class ExampleTests {
@Test
public void assertExample() {
long expected = 4L;
long actual = 4L;
Assert.assertEquals(expected, actual);
}
}

View File

@ -0,0 +1,14 @@
@startuml
title __DEMO's Class Diagram__\n
right footer
PlantUML diagram generated by SketchIt! (https://bitbucket.org/pmesmeur/sketch.it)
For more information about this tool, please contact philippe.mesmeur@gmail.com
endfooter
@enduml

View File

@ -0,0 +1,2 @@
JMH S 30 edu.ktu.ds.lab3.demo.Benchmark S 66 edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_hashMapRemove_jmhTest S 13 hashMapRemove S 11 AverageTime E A 1 1 1 E E T 3 1 s E E T 3 1 s E E E E E E E M 1 12 elementCount 5 16 xAAMAADAwAAMAA== 16 yAAMAADAwAAMAA== 16 0AAMAADAwAAMAA== 16 4AAMAADAwAAMAA== 16 xAgNAADAwAAMAADA U 12 MICROSECONDS E E
JMH S 30 edu.ktu.ds.lab3.demo.Benchmark S 68 edu.ktu.ds.lab3.demo.jmh_generated.Benchmark_hashMapOaRemove_jmhTest S 15 hashMapOaRemove S 11 AverageTime E A 1 1 1 E E T 3 1 s E E T 3 1 s E E E E E E E M 1 12 elementCount 5 16 xAAMAADAwAAMAA== 16 yAAMAADAwAAMAA== 16 0AAMAADAwAAMAA== 16 4AAMAADAwAAMAA== 16 xAgNAADAwAAMAADA U 12 MICROSECONDS E E

View File

@ -0,0 +1,8 @@
dontinline,*.*_all_jmhStub
dontinline,*.*_avgt_jmhStub
dontinline,*.*_sample_jmhStub
dontinline,*.*_ss_jmhStub
dontinline,*.*_thrpt_jmhStub
inline,edu/ktu/ds/lab3/demo/Benchmark.generateIdsAndCars
inline,edu/ktu/ds/lab3/demo/Benchmark.hashMapOaRemove
inline,edu/ktu/ds/lab3/demo/Benchmark.hashMapRemove

View File

@ -0,0 +1,86 @@
title=KTU IF LD3. Mai\u0161os lentel\u0117s duomen\u0173 strukt\u016br\u0173 tiriamasis darbas
author=Autorius: Vardenis Pavardenis, IF-x/x\nemail: vardenis.pavardenis@ktu.edu\n\u012era\u0161ykite savo rekvizitus.
icon=ktu.png
# Meniu pavadinimai
menu1=Failas
menu2=Pagalba
menuItem11=Atidaryti..
menuItem12=I\u0161saugoti..
menuItem13=I\u0161eiti
menuItem21=Apie..
# R\u0117meli\u0173 pavadinimai
border1=Kolizij\u0173 sprendimo metodas:
border2=Mai\u0161os funkcija:
border3=Duomen\u0173 \u012fvedimas:
border4=Parametrai:
border5=Atvaizdis mai\u0161os lentel\u0117je:
border6=\u012evyki\u0173 \u017eurnalas:
# Mygtuk\u0173 pavadinimai
button1=Generuoti atvaizd\u012f
button2=Papildyti atvaizd\u012f i\u0161 aib\u0117s
button3=J\u016bs\u0173 sukurta funkcija
# Pirmos lentel\u0117s parametrai
lblParam11=Pradin\u0117 por\u0173 aib\u0117s imtis
lblParam12=Generuojamos por\u0173 aib\u0117s dydis
lblParam13=Pradinis mai\u0161os lentel\u0117s dydis
lblParam14=Apkrovimo faktorius (0,1]
lblParam15=Stulpelio plotis
lblParam16=Poros teksto kirtiklis
lblParam17=J\u016bs\u0173 parametras
tfParam11=10
tfParam12=100
tfParam13=8
tfParam14=0.75
tfParam15=180
tfParam16=
tfParam17=
# Antros lentel\u0117s parametrai
lblParam21=Por\u0173 kiekis mai\u0161os lentel\u0117je
lblParam22=Mai\u0161os lentel\u0117s dydis
lblParam23=Ilgiausia grandin\u0117l\u0117
lblParam24=Permai\u0161ym\u0173 kiekis
lblParam25=Paskutinio papildyto indeksas
lblParam26=Mai\u0161os lentel\u0117s u\u017epildymas
lblParam27=J\u016bs\u0173 parametras
tfParam21=0
tfParam22=0
tfParam23=0
tfParam24=0
tfParam25=0
tfParam26=0
tfParam27=
cmbCollisionType1=Atskiros grandin\u0117l\u0117s
cmbCollisionType2=Atv. adresacija. Tiesinis d\u0117stymas
cmbCollisionType3=Atv. adresacija. Kvadratinis d\u0117stymas
cmbCollisionType4=Atv. adresacija. Dviguba mai\u0161a
cmbHashFunction1=Dalyba
cmbHashFunction2=Daugyba
cmbHashFunction3=I\u0161 Java7 Collections Framework
cmbHashFunction4=I\u0161 Java8/11/17 Collections Framework
mapPuts=Atvaizdis papildytas por\u0173 skai\u010diumi: %s
mapPut=Atvaizdis papildytas pora i\u0161 sugeneruotos por\u0173 aib\u0117s
fileWasRead=Failas perskaitytas
fileWasNotReadOrEmpty=Failas neperskaitytas arba yra tu\u0161\u010dias
notExists=N\u0117ra
#errors
systemError=Sistemin\u0117 klaida. \u017di\u016br\u0117ti konsol\u0117je
badSizeOfInitialSubSet=Netinkama pradin\u0117 por\u0173 aib\u0117s imtis
badSizeOfGenSet=Netinkamas generuojamos por\u0173 aib\u0117s dydis
badInitialCapacity=Netinkamas pradinis mai\u0161os lentel\u0117s dydis
badLoadFactor=Netinkamas apkrovimo faktorius (0;1]
badColumnWidth=Netinkamas stulpelio plotis
notImplemented=Dar ne\u012fdiegta
carsNotGenerated=Automobiliai nesugeneruoti
carsIdsNotGenerated=Automobili\u0173 id nesugeneruoti
allSetStoredToMap=Visa sugeneruota aib\u0117 patalpinta atvaizdyje
allKeysStoredToMap=Visi sugeneruoti raktai i\u0161naudoti