Skip to content
Open
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
53 changes: 53 additions & 0 deletions ExceptionPractice.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import java.util.ArrayList;

public class ExceptionPractice {

public static void methodOne(int[] arr, int el) {
if (el > arr.length - 1) {
throw new RuntimeException("Вы вышли за границу массива!!!");
}

System.out.println(arr[el]);
}


public static void methodTwo(int[] arr1, int[] arr2) {

int[] arr3 = new int[arr1.length];

for (int i = 0; i < arr3.length; i++) {
if (arr2[i] == 0) {
throw new RuntimeException("Делить на ноль нельзя!!!");
}
arr3[i] = arr1[i] / arr2[i];
System.out.print(arr3[i] + " ");
}

}

public static void methodThree(ArrayList<Integer> array, Integer el) {

ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.remove(el);
System.out.println("Удалено");
if (array.isEmpty()) {
throw new RuntimeException("Массив пустой, удалять нечего!");
}
}


public static void main(String[] args) {
int[] arr1 = {1, 3, 6, 3, 10, 0};
int[] arr2 = {2, 4, 7, 1, 6, 0};
ArrayList<Integer> arr = new ArrayList<>();

methodOne(arr1, 1); // первый метод
methodTwo(arr1, arr2); // второй метод
methodThree(arr, 2); // третий метод


}

}


50 changes: 50 additions & 0 deletions ExceptionPractice2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
public class ExceptionPractice2 {

// Реализуйте метод, принимающий в качестве аргументов два целочисленных массива, и возвращающий новый массив,
// каждый элемент которого равен разности элементов двух входящих массивов в той же ячейке.
// Если длины массивов не равны, необходимо как-то оповестить пользователя.


// Реализуйте метод, принимающий в качестве аргументов два целочисленных массива, и возвращающий новый массив, каждый элемент которого равен частному элементов двух входящих массивов в той же ячейке.
// Если длины массивов не равны, необходимо как-то оповестить пользователя.
// Важно: При выполнении метода единственное исключение, которое пользователь может увидеть - RuntimeException, т.е. ваше.

public static void usingArray1(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length];

if (arr1.length != arr2.length) {
throw new RuntimeException("Длины массивов не равны!!!");
}
for (int i = 0; i < arr3.length; i++) {
arr3[i] = arr1[i] - arr2[i];
System.out.print(arr3[i] + " ");
}

}

public static void usingArray2(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length];

if (arr1.length != arr2.length) {
throw new RuntimeException("Длины массивов не равны!!!");
}
for (int i = 0; i < arr3.length; i++) {
if (arr2[i] == 0) {
throw new RuntimeException("Делить на ноль нельзя!!!");
}
arr3[i] = arr1[i] / arr2[i];
System.out.print(arr3[i] + " ");

}
}

public static void main(String[] args) {
int[] arr1 = {7, 6, 4, 6, 9};
int[] arr2 = {4, 6, 6, 8, 0, 8};


usingArray1(arr1, arr2); // первый метод
// usingArray2(arr1, arr2); // второй метод
}

}
149 changes: 149 additions & 0 deletions RedBlackTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
//Необходимо превратить собранное на семинаре дерево поиска в полноценное левостороннее красно-черное дерево.
//И реализовать в нем метод добавления новых элементов с балансировкой.
//
// Красно-черное дерево имеет следующие критерии:
// • Каждая нода имеет цвет(красный или черный)
// • Корень дерева всегда черный
// • Новая нода всегда красная
// • Красные ноды могут быть только левым ребенком
// • У красной ноды все дети черного цвета
//Соответственно,чтобы данные условия выполнялись,после добавления элемента в дерево необходимо произвести балансировку,
//благодаря которой все критерии выше станут валидными.Для балансировки существует 3 операции – левый малый поворот,правый малый поворот и смена цвета.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class RedBlackTree {
private Node root;
public boolean add(int value) {
if (root != null) {
boolean result = addNode(root, value);
root = rebalance(root);
root.color = Color.BLACK;
return result;
} else {
root = new Node();
root.color = Color.BLACK;
root.value = value;
return true;
}
}

private Node rebalance(Node node) {
Node result = node;
boolean needRebalance;
do {
needRebalance = false;
if (result.rightChild != null && result.rightChild.color == Color.RED && (result.leftChild == null || result.leftChild.color == Color.BLACK)) {
needRebalance = true;
result = rightSwap(result);
}
if (result.leftChild != null && result.leftChild.color == Color.RED && result.leftChild.leftChild != null && result.leftChild.leftChild.color == Color.RED) {
needRebalance = true;
result = leftSwap(result);
}
if (result.leftChild != null && result.leftChild.color == Color.RED && result.rightChild != null && result.rightChild.color == Color.RED) {
needRebalance = true;
colorSwap(result);
}
} while (needRebalance);
return result;
}

private Node leftSwap(Node node) {
Node leftChild = node.leftChild;
Node betweenChild = leftChild.rightChild;
leftChild.rightChild = node;
node.leftChild = betweenChild;
leftChild.color = node.color;
node.color = Color.RED;
return leftChild;
}

private Node rightSwap(Node node) {
Node rightChild = node.rightChild;
Node betweenChild = rightChild.leftChild;
rightChild.leftChild = node;
node.rightChild = betweenChild;
rightChild.color = node.color;
node.color = Color.RED;
return rightChild;
}

private void colorSwap(Node node) {
node.rightChild.color = Color.BLACK;
node.leftChild.color = Color.BLACK;
node.color = Color.RED;
}

private boolean addNode(Node node, int value) {
if (node.value == value) {
return false;
} else {
if (node.value > value) {
if (node.leftChild != null) {
boolean result = addNode(node.leftChild, value);
node.leftChild = rebalance(node.leftChild);
return result;
} else {
node.leftChild = new Node();
node.leftChild.color = Color.RED;
node.leftChild.value = value;
return true;
}
} else {
if (node.rightChild != null) {
boolean result = addNode(node.rightChild, value);
node.rightChild = rebalance(node.rightChild);
return result;
} else {
node.rightChild = new Node();
node.rightChild.color = Color.RED;
node.rightChild.value = value;
return true;
}
}
}
}

private class Node {
private int value;
private Color color;
private Node leftChild;
private Node rightChild;

@Override
public String toString() {
return "Node{" +
"value=" + value +
", color=" + color +
"}";
}
}

private enum Color {
RED, BLACK
}


public static void main(String[] args) {

RedBlackTree tree = new RedBlackTree();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
while (true) {
try {
int value = Integer.parseInt(reader.readLine());
tree.add(value);
System.out.println("finish");
} catch (Exception ignored) {
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}