From 2e4afbd06bd797486e58d4a6de407c93376e1e16 Mon Sep 17 00:00:00 2001 From: Elena Radchenko Date: Thu, 4 May 2023 17:27:49 +0300 Subject: [PATCH 1/2] added dz --- RedBlackTree.java | 149 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 RedBlackTree.java diff --git a/RedBlackTree.java b/RedBlackTree.java new file mode 100644 index 0000000..21cc544 --- /dev/null +++ b/RedBlackTree.java @@ -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); + } + } +} + From 1026dbe8b32320d04398b4364a253ff014662bc0 Mon Sep 17 00:00:00 2001 From: Elena Radchenko Date: Sun, 7 May 2023 21:11:33 +0300 Subject: [PATCH 2/2] added dz --- ExceptionPractice.java | 53 +++++++++++++++++++++++++++++++++++++++++ ExceptionPractice2.java | 50 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 ExceptionPractice.java create mode 100644 ExceptionPractice2.java diff --git a/ExceptionPractice.java b/ExceptionPractice.java new file mode 100644 index 0000000..c41222f --- /dev/null +++ b/ExceptionPractice.java @@ -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 array, Integer el) { + + ArrayList 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 arr = new ArrayList<>(); + + methodOne(arr1, 1); // первый метод + methodTwo(arr1, arr2); // второй метод + methodThree(arr, 2); // третий метод + + + } + +} + + diff --git a/ExceptionPractice2.java b/ExceptionPractice2.java new file mode 100644 index 0000000..0bcccc7 --- /dev/null +++ b/ExceptionPractice2.java @@ -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); // второй метод + } + +}