Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,21 +1,141 @@
package hse.java.lectures.lecture3.practice.randomSet;

public class RandomSet<T> {
import java.util.Objects;
import java.util.Random;

public class RandomSet<T extends Number> {
private static class Node<T> {
T value;
int index;
Node<T> next;

Node(T value, int index, Node<T> next) {
this.value = value;
this.index = index;
this.next = next;
}
}


private static final int CAPACITY = 100;
private static final int PRIME = 15_485_863;

private Object[] elements;
private Node<T>[] heads;
private int len;
private final Random random = new Random();

@SuppressWarnings("unchecked")
public RandomSet() {
elements = new Object[CAPACITY];
heads = new Node[CAPACITY];
len = 0;
}

private int get_hash(T value) {
return (value == null ) ? 0 : Math.abs((int) value.longValue() * PRIME) % heads.length;
}

private Node<T> findNode(T value) {
int h = get_hash(value);
Node<T> cur = heads[h];
while (cur != null) {
if (Objects.equals(value, cur.value)) {
return cur;
}
cur = cur.next;
}
return null;
}

@SuppressWarnings("unchecked")
public boolean insert(T value) {
throw new UnsupportedOperationException("Not implemented");
if (findNode(value) != null) {
return false;
}

if (len == elements.length) {
Object[] newData = new Object[elements.length * 2];
for (int i = 0; i < elements.length; i++) {
newData[i] = elements[i];
}
elements = newData;
}

elements[len] = value;

int h = get_hash(value);
heads[h] = new Node<>(value, len, heads[h]);

len++;

if (len > heads.length * 0.75) {
Node<T>[] oldHeads = heads;
heads = new Node[oldHeads.length * 2];
for (Node<T> head : oldHeads) {
Node<T> cur = head;
while (cur != null) {
Node<T> next = cur.next;
int newHash = get_hash(cur.value);
cur.next = heads[newHash];
heads[newHash] = cur;
cur = next;
}
}
}
return true;
}

@SuppressWarnings("unchecked")
public boolean remove(T value) {
throw new UnsupportedOperationException("Not implemented");
Node<T> node = findNode(value);
if (node == null) {
return false;
}

int ind = node.index;

int h = get_hash(value);
Node<T> cur = heads[h];
Node<T> prev = null;
while (cur != null) {
if (cur == node) {
if (prev == null) {
heads[h] = cur.next;
} else {
prev.next = cur.next;
}
break;
}
prev = cur;
cur = cur.next;
}

if (ind != len - 1) {
T lastValue = (T) elements[len - 1];
elements[ind] = lastValue;

Node<T> lastNode = findNode(lastValue);
if (lastNode != null) {
lastNode.index = ind;
}
}

len--;

return true;
}

public boolean contains(T value) {
throw new UnsupportedOperationException("Not implemented");
return findNode(value) != null;
}


@SuppressWarnings("unchecked")
public T getRandom() {
throw new UnsupportedOperationException("Not implemented");
if (len == 0) {
throw new EmptySetException("No elements in the random set");
}
int randomIndex = random.nextInt(len);
return (T) elements[randomIndex];
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ public int getBalance() {
return 0;
}

}
}
20 changes: 14 additions & 6 deletions src/main/java/hse/java/lectures/lecture3/tasks/atm/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,24 @@ Tag: atm

## Условие

Реализовать класс `Atm`, который хранит купюры фиксированных номиналов и выполняет операции пополнения и выдачи наличных. При ошибках операции должны завершаться выбросом исключения без изменения состояния банкомата.
Реализовать класс `Atm`, который хранит купюры фиксированных
номиналов и выполняет операции пополнения и выдачи наличных.
При ошибках операции должны завершаться выбросом исключения
без изменения состояния банкомата.

## Номиналы

Фиксированный набор номиналов: `50, 100, 200, 500, 1000, 2000, 5000`.
Фиксированный набор номиналов: `50, 100, 200, 500,
1000, 2000, 5000`.
Порядок выдачи: жадный алгоритм по убыванию номиналов.

## Публичный API

1. `Atm()` — создаёт пустой банкомат.
1. `void deposit(Map<Integer, Integer> banknotes)` — добавляет купюры (ключ — номинал, значение — количество).
1. `Map<Integer, Integer> withdraw(int amount)` — выдаёт сумму `amount` и возвращает разбиение по номиналам.
1. `void deposit(Map<Integer, Integer> banknotes)`
2. — добавляет купюры (ключ — номинал, значение — количество).
1. `Map<Integer, Integer> withdraw(int amount)` —
2. выдаёт сумму `amount` и возвращает разбиение по номиналам.
1. `int getBalance()` — возвращает текущий баланс.

## Правила ошибок
Expand All @@ -25,7 +31,8 @@ Tag: atm
- номинал не входит в допустимый набор.
1. `InvalidAmountException` — если `amount <= 0`.
1. `InsufficientFundsException` — если `amount > getBalance()`.
1. `CannotDispenseException` — если сумма не набирается доступными купюрами.
1. `CannotDispenseException` — если сумма не набирается
2. доступными купюрами.

Во всех случаях при исключении состояние банкомата не изменяется.

Expand All @@ -37,6 +44,7 @@ Tag: atm
- После выдачи `700` (например, `1×500 + 2×100`) баланс `2800`.

**Ошибки:**
- Запрос `10_000` при балансе `3000` → `InsufficientFundsException`.
- Запрос `10_000` при балансе `3000` →
`InsufficientFundsException`.
- Запрос `375` → `CannotDispenseException`.
- Вызов `withdraw(-100)` → `InvalidAmountException`.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ private String readFile(Path filePath) {
}
}

private void validate(String content){}
private void validate(String content){

}

}
2 changes: 1 addition & 1 deletion src/main/java/hse/java/practice/task1/Edge.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ public void setParts(CubeColor[][] parts) {
public String toString() {
return Arrays.deepToString(parts);
}
}
}
Loading