Владислав Комза

Initial commit

# Project exclude paths
/target/
\ No newline at end of file
... ...
# Default ignored files
/shelf/
/workspace.xml
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="Lab1" />
</profile>
</annotationProcessing>
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" project-jdk-name="11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<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>ru.mephi</groupId>
<artifactId>Lab1</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
... ...
package ru.mephi.komzavladislav.lab1;
import java.util.Iterator;
public class MyArrayList implements MyList{
private static final int defaultBufferSize = 8;
private Object[] array;
private int length;
public MyArrayList(int bufferSize){
array = new Object[bufferSize];
length = 0;
}
public MyArrayList(){
this(defaultBufferSize);
}
@Override
public void add(Object item) {
if (length == array.length)
grow();
array[length] = item;
length++;
}
@Override
public void add(Object item, int position) {
position = Math.max(0, position);
position = Math.min(position, length);
if (length == array.length)
grow();
System.arraycopy(array, position, array, position + 1, length - position);
array[position] = item;
length++;
}
@Override
public Object get(int position) {
if(isPositionOutOfBounds(position))
return null;
return array[position];
}
@Override
public Object remove(int position) {
if (isPositionOutOfBounds(position))
return null;
Object toRemove = array[position];
System.arraycopy(array, position + 1, array, position, length - position);
length--;
return toRemove;
}
@Override
public Object set(Object item, int position) {
position = Math.max(0, position);
position = Math.min(position, length - 1);
if(isEmpty())
return null;
Object toSet = array[position];
array[position] = item;
return toSet;
}
@Override
public boolean isEmpty() {
return length == 0;
}
@Override
public int size() {
return length;
}
@Override
public boolean contains(Object item) {
return index(item) >= 0;
}
@Override
public int index(Object item) {
for (int i = 0; i < length; i++) {
if(item.equals(array[i]))
return i;
}
return -1;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("MyArrayList{[");
for (int i = 0; i < length; i++) {
builder.append(array[i]);
if(i != length - 1)
builder.append(", ");
}
builder.append("]}");
return builder.toString();
}
private boolean isPositionOutOfBounds(int position){
return position < 0 || position >= size();
}
private void grow(){
Object[] newArray = new Object[array.length * 2];
System.arraycopy(array, 0, newArray, 0, length);
array = newArray;
}
@Override
public Iterator iterator() {
return new MyArrayIterator();
}
class MyArrayIterator implements Iterator{
int index;
public MyArrayIterator() {
index = 0;
}
@Override
public boolean hasNext() {
return index < length;
}
@Override
public Object next() {
Object res = array[index];
index++;
return res;
}
}
}
... ...
package ru.mephi.komzavladislav.lab1;
import java.util.Iterator;
public class MyLinkedList implements MyList {
private ListItem head;
private ListItem tail;
private int length;
public MyLinkedList(){
head = null;
tail = null;
length = 0;
}
@Override
public void add(Object item){
ListItem toInsert = new ListItem(item, null);
if (tail != null)
tail.setNext(toInsert);
tail = toInsert;
length++;
if (head == null) // If was empty before adding
head = tail;
}
@Override
public void add(Object item, int position){
if (isEmpty()){
add(item);
return;
}
position = Math.max(0, position);
position = Math.min(position, length);
ListItem toInsert;
if (position == 0){
ListItem afterInserted = head;
toInsert = new ListItem(item, afterInserted);
head = toInsert;
}
else {
ListItem prev = itemAtPosition(position - 1);
ListItem afterInserted = prev.getNext();
toInsert = new ListItem(item, afterInserted);
prev.setNext(toInsert);
}
if (position == length)
tail = toInsert;
length++;
}
@Override
public Object get(int position){
if (isPositionOutOfBounds(position))
return null;
ListItem toGet = itemAtPosition(position);
return toGet.getValue();
}
@Override
public Object remove(int position){
if (isPositionOutOfBounds(position))
return null;
ListItem prev = null;
ListItem toRemove;
if (position == 0){
toRemove = head;
head = head.getNext();
}
else {
prev = itemAtPosition(position - 1);
toRemove = prev.getNext();
prev.setNext(toRemove.getNext());
}
if (position == length - 1){
tail = prev;
}
length--;
return toRemove.getValue();
}
@Override
public Object set(Object item, int position){
position = Math.max(0, position);
position = Math.min(position, length - 1);
if(isEmpty())
return null;
ListItem toSet = itemAtPosition(position);
Object prevValue = toSet.getValue();
toSet.setValue(item);
return prevValue;
}
@Override
public boolean isEmpty(){
return length == 0;
}
@Override
public int size(){
return length;
}
@Override
public boolean contains(Object item){
return index(item) >= 0;
}
@Override
public int index(Object item){
ListItem tmp = head;
for (int i = 0; i < length; i++){
if(item.equals(tmp.getValue()))
return i;
tmp = tmp.getNext();
}
return -1;
}
private ListItem itemAtPosition(int position){
ListItem tmp = head;
for (int i = 0; i < position; i++){
tmp = tmp.getNext();
}
return tmp;
}
private boolean isPositionOutOfBounds(int position){
return position < 0 || position >= size();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("MyLinkedList{[");
ListItem item = head;
while (item != null){
builder.append(item.getValue());
if(item.getNext() != null)
builder.append(", ");
item = item.getNext();
}
builder.append("]}");
return builder.toString();
}
@Override
public Iterator iterator() {
return new MyListIterator();
}
class MyListIterator implements Iterator{
private ListItem ptr;
public MyListIterator() {
this.ptr = head;
}
@Override
public boolean hasNext() {
return ptr != null;
}
@Override
public Object next() {
Object res = ptr.getValue();
ptr = ptr.getNext();
return res;
}
}
static class ListItem{
private Object value;
private ListItem next;
public ListItem(Object value, ListItem next){
this.value = value;
this.next = next;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public ListItem getNext() {
return next;
}
public void setNext(ListItem next) {
this.next = next;
}
}
}
... ...
package ru.mephi.komzavladislav.lab1;
import java.util.Iterator;
public interface MyList extends Iterable {
/*
* Сделать класс List
* Реализовать функции addValue(Object) -> void
* add(Object, int) -> void
* remove(int) -> Object
* get(int) -> Object
* set(Object, int) -> Object
* size() -> int
* isEmpty() -> boolean
* contains(Object) -> boolean
* index(Object) -> int
* ind < 0 => ind = 0
* ind >= size => ind = size - для add
* в set - вместо последнего элемента
* Для get и remove если выходит за зону возвращаем null
* */
void add(Object item);
void add(Object item, int position);
Object get(int position);
Object remove(int position);
Object set(Object item, int position);
boolean isEmpty();
int size();
boolean contains(Object item);
int index(Object item);
}
... ...
package ru.mephi.komzavladislav.lab1;
import java.util.Objects;
public class MyMap {
/*
* 2. Реализовать словарь (map)
* Операции
* - Положить по ключу значение: public void put(Object key, Object value);
* - Получить по ключу: public Object get(Object key);
* - Получить по ключу, public Object get(Object key, Object bydefault);
* если значение null, тогда надо
* вернуть значение по умолчанию,
* которое задается вторым параметром.
* Значение по умолчанию необходимо
* сохранить.
* - Удалить по ключу, возвращает текущее public Object remove(Object key);
* значение
* - Проверить наличие ключа: public boolean keyContains(Object key);
* - Получить список ключей: public List getKeys();
* Получить список значений: public List getValues();
* - Получить список пар: ключ, значение: public List getEntries();
* - Размер словаря: public int size();
* - Пустой или нет: public boolean isEmpty();
**/
private static final int defaultBufferSize = 8;
private MyList[] table;
private int size;
public MyMap(){
table = new MyLinkedList[defaultBufferSize];
size = 0;
}
public MyMap(int bufferSize){
table = new MyLinkedList[bufferSize];
size = 0;
}
public void put(Object key, Object value){
if (((double) size )/ table.length > 0.9)
grow();
int arrayPosition = getArrayPosition(key);
MyList sameHashList = table[arrayPosition];
if (sameHashList == null){
table[arrayPosition] = new MyLinkedList();
sameHashList = table[arrayPosition];
}
boolean hasSameKey = false;
for (Object o : sameHashList) {
KeyValuePair curPair = (KeyValuePair) o;
if (safeEquals(curPair.getKey(), key)) {
curPair.setValue(value);
hasSameKey = true;
}
}
if(!hasSameKey) {
sameHashList.add(new KeyValuePair(key, value));
size++;
}
}
public Object get(Object key){
int arrayPosition = getArrayPosition(key);
MyList sameHashList = table[arrayPosition];
if(sameHashList == null)
return null;
for (Object o : sameHashList) {
KeyValuePair curPair = (KeyValuePair) o;
if (safeEquals(curPair.getKey(), key))
return curPair.getValue();
}
return null;
}
public Object get(Object key, Object bydefault){
if(!keyContains(key)){
put(key, bydefault);
return bydefault;
}
return get(key);
}
public Object remove(Object key){
int arrayPosition = getArrayPosition(key);
MyList sameHashList = table[arrayPosition];
if(sameHashList == null)
return null;
// Find and remove pair with a given key
// Using the fact that pairs with the same key are considered equal
int positionToRemove = sameHashList.index(new KeyValuePair(key, null));
if (positionToRemove == -1)
return null;
KeyValuePair removedPair = (KeyValuePair) sameHashList.remove(positionToRemove);
if(sameHashList.isEmpty())
table[arrayPosition] = null;
size--;
return removedPair.getValue();
}
public boolean keyContains(Object key){
int arrayPosition = getArrayPosition(key);
MyList sameHashList = table[arrayPosition];
if(sameHashList == null)
return false;
for (Object o : sameHashList) {
KeyValuePair curPair = (KeyValuePair) o;
if (safeEquals(curPair.getKey(), key))
return true;
}
return false;
}
public MyList getKeys(){
return getFromPairs(KeyValuePair::getKey);
}
public MyList getValues(){
return getFromPairs(KeyValuePair::getValue);
}
public MyList getEntries(){
return getFromPairs(pair -> pair);
}
public int size() {
return size;
}
public boolean isEmpty(){
return size == 0;
}
private int getArrayPosition(Object key) {
if (key == null)
return 0;
return Math.abs(key.hashCode()) % table.length;
}
private static boolean safeEquals(Object o1, Object o2){
if (o1 == null) {
return o2 == null;
}
else if (o2 == null) {
return false;
}
else return o1.equals(o2);
}
private void grow(){
MyList[] newTable = new MyList[table.length * 2];
System.arraycopy(table, 0, newTable, 0, table.length);
table = newTable;
}
private MyList getFromPairs(LoopAction loopAction){
MyList list = new MyArrayList();
for (MyList sameHashList : table) {
if (sameHashList == null)
continue;
for (Object pair: sameHashList) {
KeyValuePair keyValuePair = (KeyValuePair) pair;
list.add(loopAction.action(keyValuePair));
}
}
return list;
}
interface LoopAction{
Object action(KeyValuePair pair);
}
static class KeyValuePair{
private final Object key;
private Object value;
public KeyValuePair(Object key, Object value) {
this.key = key;
this.value = value;