Compare commits

...

16 Commits

Author SHA1 Message Date
Leonid
2ac4fd401b Solved Maximum Subarray Sum (Kadane’s Algorithm)
https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/#naive-approach-by-iterating-over-all-subarrays-on-2-time-and-o1-space
2025-04-29 14:19:17 +03:00
Leonid
b1682b8cad Solved FillDiags 2025-04-26 16:22:42 +03:00
Leonid
29e9d3247d Find Longest Series solution 2025-04-16 11:06:53 +03:00
Leonid
ad0acd060a FirstNonRepeatingLetter solution 2025-04-15 11:01:48 +03:00
Leonid
acb617b460 Решение 3-ей задачи easy с HH. Нахождение минимального, максимального и медианного возраста сотрудников. 2025-04-12 12:27:37 +03:00
Leonid
0e5fc7175a Lesson 4 homework solution 2025-04-11 23:11:08 +03:00
Leonid
629438b805 Lesson 4 homework solution 2025-04-11 23:08:49 +03:00
Leonid
d125a16368 Duplicate encoder solution 2025-04-09 12:33:50 +03:00
Leonid
a062cc1ca2 Lesson 3 homework solution 2025-04-08 23:44:30 +03:00
Leonid
a2132695d3 atm + ranges solution 2025-04-08 10:57:42 +03:00
Leonid
f40b140249 Build Tower solution 2025-04-08 10:30:41 +03:00
Leonid
17eb02553a Скорректировал обработку пробелов в строке. 2025-04-04 09:13:59 +03:00
Leonid
17186bc344 Добавил описания заданий. 2025-04-03 11:33:39 +03:00
Leonid
2005871330 Задачи medium с HH (две первых) 2025-04-03 11:10:12 +03:00
Leonid
79c26666c6 Решение Задачи на стримы от Java Gym Rat 2025-04-02 12:41:11 +03:00
Leonid
97aaf4c8fc Задача на стримы от Java Gym Rat 2025-04-01 19:30:53 +03:00
24 changed files with 1037 additions and 2 deletions

View File

@@ -0,0 +1,56 @@
package com.algos.codewars;
//Build Tower
//
// Build a pyramid-shaped tower, as an array/list of strings, given a positive integer number of floors. A tower block is represented with "*" character.
//
// For example, a tower with 3 floors looks like this:
//
// [
// " * ",
// " *** ",
// "*****"
// ]
//
// And a tower with 6 floors looks like this:
//
// [
// " * ",
// " *** ",
// " ***** ",
// " ******* ",
// " ********* ",
// "***********"
// ]
import java.util.Arrays;
public class BuildTower {
public static void main(String[] args) {
System.out.println(Arrays.toString(towerBuilder(3)));
}
public static String[] towerBuilder(int nFloors) {
String[] result = new String[nFloors];
int stars = (nFloors - 1) * 2 + 1;
int spaces = 0;
for (int i = nFloors - 1; i >= 0; i--) {
result[i] = buildFloor(stars, spaces);
stars = stars - 2;
spaces++;
}
return result;
}
private static String buildFloor(int stars, int spaces) {
String spacesStr = " ".repeat(spaces);
return spacesStr + "*".repeat(stars) + spacesStr;
}
}

View File

@@ -0,0 +1,56 @@
package com.algos.codewars;
//The goal of this exercise is to convert a string to a new string where each character in the new
// string is "(" if that character appears only once in the original string, or ")" if that character
// appears more than once in the original string. Ignore capitalization when determining if a character
// is a duplicate.
// Examples
//
// "din" => "((("
// "recede" => "()()()"
// "Success" => ")())())"
// "(( @" => "))(("
import java.util.stream.Collectors;
public class DuplicateEncoder {
public static void main(String[] args) {
String text = "din";
System.out.println(encode(text));
text = "recede";
System.out.println(encode(text));
text = "Success";
System.out.println(encode(text));
text = "(( @";
System.out.println(encode(text));
}
// static String encode(String word){
//
// Set<Character> duplicates = word.toLowerCase().chars().mapToObj(c -> (char) c)
// .collect(Collectors.groupingBy(c -> c, Collectors.counting()))
// .entrySet()
// .stream().filter(e -> e.getValue() > 1)
// .map(Map.Entry::getKey)
// .collect(Collectors.toSet());
//
// return word.toLowerCase().chars().mapToObj(c -> (char) c).map(c -> {
// if (duplicates.contains(c)) {
// return ")";
// }
// return "(";
// }).collect(Collectors.joining());
// }
static String encode(String word) {
return word.toLowerCase().chars().mapToObj(c -> word.indexOf(c) == word.lastIndexOf(c) ? "(" : ")")
.collect(Collectors.joining());
}
}

View File

@@ -0,0 +1,57 @@
package com.algos.codewars;
//Write a function named first_non_repeating_letter† that takes a string input,
// and returns the first character that is not repeated anywhere in the string.
//
// For example, if given the input 'stress', the function should return 't',
// since the letter t only occurs once in the string, and occurs first in the string.
//
// As an added challenge, upper- and lowercase letters are considered the same character,
// but the function should return the correct case for the initial letter. For example, the input 'sTreSS' should return 'T'.
//
// If a string contains all repeating characters, it should return an empty string ("");
//
// † Note: the function is called firstNonRepeatingLetter for historical reasons,
// but your function should handle any Unicode character.
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstNonRepeatingLetter {
public static void main(String[] args) {
System.out.println(firstNonRepeatingLetter("manOn-aMoon"));
}
public static String firstNonRepeatingLetter(String s) {
if (s == null || s.isEmpty()) {
return "";
}
Map<Character, Integer> charCount = new LinkedHashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = Character.toLowerCase(s.charAt(i));
charCount.merge(c, 1, Integer::sum);
}
for (int i = 0; i < s.length(); i++) {
char currentChar = s.charAt(i);
if (charCount.get(Character.toLowerCase(currentChar)) == 1) {
return String.valueOf(currentChar);
}
}
return "";
// List<String> c = s.toLowerCase().chars().mapToObj(ch -> (char) ch).map(String::valueOf).toList();
// for (int i = 0; i < s.length(); i++) {
// if (Collections.frequency(c, c.get(i).toLowerCase()) == 1) {
// return String.valueOf(s.charAt(i));
// }
// }
// return "";
}
}

View File

@@ -0,0 +1,43 @@
package com.algos.codewars;
//The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array
// or list of integers:
//
// Max.sequence(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4});
//// should be 6: {4, -1, 2, 1}
//
// Easy case is when the list is made up of only positive numbers and the maximum sum is the sum
// of the whole array. If the list is made up of only negative numbers, return 0 instead.
//
// Empty list is considered to have zero greatest sum. Note that the empty list or array is also
// a valid sublist/subarray.
public class MaximumSubarraySum {
public static void main(String[] args) {
int [] testArray = new int[] {-2, 1, -3, 4, -1, 2, 1, -5, 4};
// int[] testArray = new int[]{2, 3, -8, 7, -1, 2, 3};
System.out.println(sequence(testArray));
}
public static int sequence(int[] arr) {
if (arr.length == 0) {
return 0;
}
int maxEnding = arr[0];
int result = arr[0];
for (int i = 1; i < arr.length; i++) {
// if (maxEnding < 0) {
// maxEnding = arr[i];
// } else {
// maxEnding + arr[i];
// }
maxEnding = Math.max(arr[i], maxEnding + arr[i]);
result = Math.max(result, maxEnding);
}
return Math.max(result, 0);
}
}

View File

@@ -0,0 +1,30 @@
package com.algos.gym_rat;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Product product1 = new Product("Молоко", 10, 2.0);
Product product2 = new Product("Масло", 1, 10.0);
Product product3 = new Product("Сыр", 5, 2.0);
Product product4 = new Product("Хлеб", 3, 1.0);
Product product5 = new Product("Лаваш", 4, 5.0);
Order order1 = new Order("1", "Вася");
order1.setProducts(new ArrayList<>(List.of(product1, product2, product3, product4)));
System.out.println(OrderAnalysis.calculateOrderTotal(order1));
Order order2 = new Order("2", "Коля");
order2.setProducts(new ArrayList<>(List.of(product2, product4, product5)));
List<Order> orders = new ArrayList<>(List.of(order1, order2));
System.out.println(OrderAnalysis.getUniqueProducts(orders));
System.out.println(OrderAnalysis.findMostPopularProduct(orders, 3));
System.out.println(OrderAnalysis.findMostPopularProductNice(orders, 3));
}
}

View File

@@ -0,0 +1,22 @@
package com.algos.gym_rat;
import java.util.List;
public class Order {
String orderId;
String customerName;
List<Product> products;
public Order(String orderId, String customerName) {
this.orderId = orderId;
this.customerName = customerName;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}

View File

@@ -0,0 +1,63 @@
package com.algos.gym_rat;
import java.util.*;
import java.util.stream.Collectors;
public class OrderAnalysis {
// Рассчитать полную стоимость заказа
public static Double calculateOrderTotal(Order order) {
return order
.getProducts()
.stream()
.mapToDouble(p -> p.getQuantity() * p.getPrice())
.sum();
}
//Получить список наименований товаров из заказов
public static Set<String> getUniqueProducts(List<Order> orders) {
return orders
.stream()
.flatMap(o -> o.getProducts().stream())
.map(Product::getName)
.collect(Collectors.toSet());
}
//Вывести наименования N популярных товаров в порядке уменьшения популярности
//Популярный товар - товар, который больше остальных покупается
public static List<String> findMostPopularProduct(List<Order> orders, int topN) {
Map<String, Integer> popularProducts = new HashMap<>();
for (Order order : orders) {
List<Product> products = order.getProducts();
for (Product product : products) {
popularProducts.merge(product.getName(), product.getQuantity(), Integer::sum);
}
}
return popularProducts
.entrySet()
.stream()
.sorted((e1, e2) -> {
return e2.getValue().compareTo(e1.getValue());
})
.limit(topN)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
public static List<String> findMostPopularProductNice(List<Order> orders, int topN) {
return orders
.stream()
.flatMap(o -> o.getProducts().stream())
.collect(Collectors.groupingBy(Product::getName, Collectors.summingInt(Product::getQuantity)))
.entrySet()
.stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(topN)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,26 @@
package com.algos.gym_rat;
public class Product {
String name;
Integer quantity;
Double price;
public Product(String name, Integer quantity, Double price) {
this.name = name;
this.quantity = quantity;
this.price = price;
}
public Integer getQuantity() {
return quantity;
}
public Double getPrice() {
return price;
}
public String getName() {
return name;
}
}

View File

@@ -0,0 +1,58 @@
package com.algos.hh.easy;
import java.util.Arrays;
import java.util.List;
//Возраст сотрудников
// Вы работаете над модулем внутрикорпоративной системы учета данных сотрудников компании. Программа должна:
// 1. Найти сотрудника с минимальным возрастом;
// 2. Вычислить медианный возраст всех сотрудников;
// 3. Найти сотрудника с максимальным возрастом.
// Медиана — число, которое находится в середине этого набора, если его упорядочить по возрастанию. Если набор чисел четный, то берется среднее между двумя средними числами и округляется до целого.
// Формат ввода
// Одна строка — данные сотрудников. Данные включают имя, возраст и отдел, разделенные запятой, без пробелов. Информация о каждом сотруднике разделена через точку с запятой.
// Количество сотрудников — от 2 до 100.
// Формат вывода
// Одна строка содержит три целых числа, разделенные пробелом: минимальный возраст, медианный возраст и максимальный возраст.
// Пример 1
// Входные данные:
// Иван,28,Инженер;Олег,34,HR;Денис,45,Маркетинг;Анна,30,Инженер;Борис,24,HR
// Выходные данные:
// 24 30 45
// Пример 2
// Входные данные:
// Павел,28,Инженер;Елена,34,Маркетинг
// Выходные данные:
// 28 31 34
public class AgeProcessor {
public static void main(String[] args) {
String input = "Иван,28,Инженер;Олег,34,HR;Денис,45,Маркетинг;Анна,30,Инженер;Борис,24,HR";
String input2 = "Павел,28,Инженер;Елена,34,Маркетинг";
System.out.println(processEmployeeData(input));
System.out.println(processEmployeeData(input2));
}
public static String processEmployeeData(String input) {
String[] employees = input.split(";");
List<Integer> ages = Arrays.stream(employees)
.map(s -> s.split(","))
.filter(parts -> parts.length >= 2)
.map(e -> Integer.parseInt(e[1]))
.sorted()
.toList();
if (ages.isEmpty()) {
return "0 0 0";
}
int minAge = ages.get(0);
int maxAge = ages.get(ages.size() - 1);
int middleOfList = ages.size() / 2;
int medAge = ages.size() % 2 != 0 ? ages.get(middleOfList) :
Math.round((ages.get(middleOfList) + ages.get(middleOfList - 1)) / 2f);
return minAge + " " + medAge + " " + maxAge;
}
}

View File

@@ -1,4 +1,4 @@
package com.algos.hh;
package com.algos.hh.easy;
//Обработка логов
// Вы работаете над системой анализа логов. Вам нужно разработать компонент для обработки и анализа строк. Этот компонент должен выполнять следующие операции:

View File

@@ -1,4 +1,4 @@
package com.algos.hh;
package com.algos.hh.easy;
//Площадь и периметр
// Вы разрабатываете программу для обработки информации о фигурах на плоскости. Вам необходимо создать класс, который будет вычислять площадь и периметр фигуры. Программа работает с двумя типами фигур круг и квадрат.

View File

@@ -0,0 +1,57 @@
package com.algos.hh.medium;
//Проверка на палиндром
//
// Уровень: Средний
// Темы: Циклы и итерации, Строки, Условия
//
// Вы разрабатываете программу для проверки строк на палиндром.
// Палиндром — это строка, которая читается одинаково с начала и с конца. При этом пробелы и регистр букв игнорируются.
//
// Напишите программу, которая определяет, является ли заданная строка палиндромом.
//
// Формат ввода:
// Одна строка, содержащая только заглавные и/или строчные буквы русского алфавита и, в некоторых случаях, пробелы.
// Длина строки от 2 до 100 символов включительно.
//
// Формат вывода:
// Одна из двух фраз (без кавычек):
// - Палиндром
// - Не палиндром
//
// Примеры:
//
// Пример 1
// Входные данные:
// Тут как тут
// Выходные данные:
// Палиндром
//
// Пример 2
// Входные данные:
// Программист
// Выходные данные:
// Не палиндром
import java.util.Locale;
public class Palindrome {
public static void main(String[] args) {
System.out.println(checkPalindrome("Тут как тут"));
System.out.println(checkPalindrome("Программист"));
System.out.println(checkPalindrome("Шалаш"));
System.out.println(checkPalindrome("А роза упала на лапу Азора"));
}
public static String checkPalindrome(String input) {
input = input.trim().replaceAll("\\s+", "").toLowerCase(Locale.ROOT);
for (int i = 0; i < input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
return "Не палиндром";
}
}
return "Палиндром";
}
}

View File

@@ -0,0 +1,54 @@
package com.algos.hh.medium;
//Значительное похолодание
// Средний
// Временные ряды
// Массивы
// Циклы
// Индексация
// Вы разрабатываете приложение для определения погоды. Вы работаете с массивом значений температур по дням. В нем вам нужно найти значительные падения температур — дни, когда температура упала на 3 и более градуса относительно предшествующего значения. Температура может принимать положительные, нулевые и отрицательные значения.
// Формат ввода
// Одна строка, в которой чередуются целые числа, разделенные пробелами. Числа могут быть положительными, отрицательными или нулем. Длина списка — не больше 100 элементов.
// Формат вывода
// Одна строка, в которой чередуются целые числа, разделенные пробелами. В строке содержатся индексы дней, соответствующие определению «значительное падение температуры». Если таких дней нет, выводится «Нет».
// Пример 1
// Входные данные:
// 0 5 2 7 4 1
// Выходные данные:
// 2 4 5
// Пример 2
// Входные данные:
// 10 8 6 4 2 0 -2 -4
// Выходные данные:
// Нет
public class TemperatureDrops {
public static void main(String[] args) {
System.out.println(findDrops("0 5 2 7 4 1"));
System.out.println(findDrops("10 8 6 4 2 0 -2 -4"));
}
public static String findDrops(String input) {
String[] sourceArray = input.split(" ");
Integer[] destArray = new Integer[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++) {
destArray[i] = Integer.parseInt(sourceArray[i]);
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i < destArray.length ; i++) {
int prev = destArray[i - 1];
int curr = destArray[i];
if (Math.abs(prev) - Math.abs(curr) >= 3) {
sb.append(i).append(" ");
}
}
if (!sb.isEmpty()) {
return sb.toString().trim();
}
return "Нет";
}
}

View File

@@ -0,0 +1,50 @@
package com.algos.om;
//Вам дан отсортированный массив уникальных целых чисел nums.
//
// Диапазон [a, b] — это набор всех целых чисел от a до b (включительно).
//
// Верните наименьший отсортированный список диапазонов, которые покрывают все числа в массиве точно.
// То есть, каждый элемент nums должен быть покрыт ровно одним из диапазонов,
// и не должно быть такого числа x, которое находится в одном из диапазонов, но отсутствует в nums.
//
// Каждый диапазон [a, b] в списке должен быть представлен в следующем формате:
//
// "a->b", если a != b
// "a", если a == b
//
// Пример:
// Вход: [1, 2, 3, 5, 6, 8]
// Выход: ["1->3", "5->6", "8"]
import java.util.ArrayList;
import java.util.List;
public class Ranges {
public static void main(String[] args) {
// int[] source = new int[]{1, 2, 3, 5, 6, 8};
int[] source = new int[]{1, 3, 4, 5, 6, 8, 9};
System.out.println(getRanges(source));
}
public static List<String> getRanges(int[] source) {
List<String> result = new ArrayList<>();
int begin = source[0];
int end = source[0];
for (int i = 1; i < source.length; i++) {
int nextValue = source[i];
if (nextValue - end > 1) {
result.add(begin == end ? String.valueOf(end) : begin + "->" + end);
begin = nextValue;
}
end = nextValue;
}
result.add(begin == end ? String.valueOf(end) : begin + "->" + end);
return result;
}
}

View File

@@ -0,0 +1,46 @@
package com.algos.shortcut;
import java.util.Arrays;
// В банкомате доступны банкноты различных номиналов, например, [100, 500, 1000].
// Вам необходимо написать программу, которая по заданной сумме определяет минимальное количество банкнот,
// необходимое для выдачи этой суммы. Допускается использовать любое количество банкнот каждого номинала.
//
// Если точно составить требуемую сумму с использованием имеющихся номиналов невозможно,
// программа должна вернуть -1.
public class Atm {
public static void main(String[] args) {
int[] banknotes = {100, 500, 1000};
// int[] banknotes = {1000, 100, 500};
// int amount = 1500;
int amount = 1803;
// int amount = 1800;
// int amount = 600;
int result = minBanknotes(banknotes, amount);
System.out.println(result);
}
private static int minBanknotes(int[] banknotes, int amount) {
Arrays.sort(banknotes);
int[] result = new int[banknotes.length];
for (int i = banknotes.length - 1; i >= 0; i--) {
if (amount < banknotes[i]) {
continue;
}
result[i] = amount / banknotes[i];
amount = amount % banknotes[i];
}
if (amount != 0) {
return -1;
}
return Arrays.stream(result).sum();
}
}

View File

@@ -0,0 +1,63 @@
package com.algos.stepik;
//У вас есть переменная n, которая содержит входные пользовательские данные.
//
// Напишите код, который создает двумерный список и заполняет его по следующему правилу: на главной диагонали должны быть записаны числа 0. На двух диагоналях, прилегающих к главной, числа 1. На следующих двух диагоналях числа 2, и т.д.
//
// Результат записать в виде нового списка в переменную result.
//
// Например:
//
// Если n = 4 тогда:
//
// [
// [ 0, 1, 2, 3 ],
// [ 1, 0, 1, 2 ],
// [ 2, 1, 0, 1 ],
// [ 3, 2, 1, 0 ]
// ]
//
// Если n = 5 тогда:
//
// [
// [ 0, 1, 2, 3, 4 ],
// [ 1, 0, 1, 2, 3 ],
// [ 2, 1, 0, 1, 2 ],
// [ 3, 2, 1, 0, 1 ],
// [ 4, 3, 2, 1, 0 ]
// ]
import com.google.gson.Gson;
import java.util.*;
public class FillDiags {
public static void main(String[] args) {
//int n = readInput();
int n = 5;
List<List<Integer>> result = fillDiagonalList(n);
System.out.println(new Gson().toJson(result));
}
public static List<List<Integer>> fillDiagonalList(int n) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> row = new ArrayList<>();
for (int j = 0; j < n; j++) {
row.add(Math.abs(i - j));
}
result.add(row);
}
return result;
}
public static int readInput() {
Scanner scanner = new Scanner(System.in);
return Integer.parseInt(scanner.nextLine().trim());
}
}

View File

@@ -0,0 +1,56 @@
package com.algos.stepik;
//У вас есть переменная data которая содержит входные пользовательские данные.
//
// data - список из элементов целых числел.
//
// Напишите код, который находит наибольшую серию подряд идущих элементов, расположенных по возрастанию.
//
// Результат записать в переменную result.
//
// Sample Input 1:
//
// [1, 2, 3, 4, 4, 3, 4, 6, 8, 10]
//
// Sample Output 1:
//
// 5
//
// Sample Input 2:
//
// [1, 2, 3, 4, 4, 3, 5, 5, 8, 10]
//
// Sample Output 2:
//
// 4
import java.util.List;
public class FindLongestSeries {
public static void main(String[] args) {
List<Integer> list1 = List.of(1, 2, 3, 4, 4, 3, 4, 6, 8, 10);
List<Integer> list2 = List.of(1, 2, 3, 4, 4, 3, 5, 5, 8, 10);
System.out.println(findLongestSeries(list1));
System.out.println(findLongestSeries(list2));
}
public static int findLongestSeries(List<Integer> data) {
int max = 0;
int counter = 1;
for(int i = 1; i < data.size(); i++) {
if (data.get(i) - data.get(i - 1) > 0) {
counter++;
} else {
max = Math.max(max, counter);
counter = 1;
}
}
return Math.max(max, counter);
}
}

View File

@@ -0,0 +1,60 @@
package com.algos.vtb.exceptions;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
String[][] myArray = new String[][]{
{"1", "2", "3", "4"},
{"5", "6", "7b", "8"},
{"9", "10", "5", "12"},
{"13", "14", "15", "16"}
};
try {
System.out.printf("Cумма = %d%n", getSum(myArray));
} catch (MyArrayException e) {
System.out.println("Exception processed");
}
}
private static int getSum(String[][] myArray) throws MyArraySizeException, MyArrayDataException {
if (myArray.length != 4) {
throw new MyArraySizeException("Размер массива должен быть 4x4!");
}
// for (int i = 0; i < myArray.length; i++) {
// if (myArray[i].length != 4) {
// throw new MyArraySizeException(i);
// }
// }
// IntStream.range(0, myArray.length)
// .forEach(i -> {
// if (myArray[i].length != 4) {
// throw new MyArraySizeException(i);
// }
// });
IntStream.range(0, myArray.length)
.filter(i -> myArray[i].length != 4)
.findFirst()
.ifPresent(i -> {
throw new MyArraySizeException(i);
});
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
try {
sum += Integer.parseInt(myArray[i][j]);
} catch (NumberFormatException e) {
throw new MyArrayDataException(i, j, myArray);
}
}
}
return sum;
}
}

View File

@@ -0,0 +1,25 @@
package com.algos.vtb.exceptions;
public class MyArrayDataException extends MyArrayException {
private int row;
private int col;
private Object value;
public MyArrayDataException() {
super();
}
public MyArrayDataException(String message) {
super(message);
}
public MyArrayDataException(int row, int col, Object[][] array) {
super("Неверные данные в массиве [" + row + "][" + col + "]: " + array[row][col]);
this.row = row;
this.col = col;
this.value = array[row][col];
}
}

View File

@@ -0,0 +1,10 @@
package com.algos.vtb.exceptions;
public class MyArrayException extends RuntimeException{
public MyArrayException() {
}
public MyArrayException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,19 @@
package com.algos.vtb.exceptions;
public class MyArraySizeException extends MyArrayException {
int row;
public MyArraySizeException() {
super();
}
public MyArraySizeException(String message) {
super(message);
}
public MyArraySizeException(int row) {
super(String.format("Размер массива в строке %d не равен 4", row));
this.row = row;
}
}

View File

@@ -0,0 +1,35 @@
package com.algos.vtb.generics_collections.generics_collections;
import java.util.Arrays;
//Написать метод, который меняет два элемента массива местами (массив может быть любого
// ссылочного типа).
public class Task1 {
public static void main(String[] args) {
String[] strArray = new String[]{"a", "c", "b"};
System.out.println("before : " + Arrays.toString(strArray));
System.out.println("after : " + Arrays.toString(exchangeElements(1, 2, strArray)));
Integer[] intArray = new Integer[]{20, 19, 22, 21};
System.out.println("before : " + Arrays.toString(intArray));
exchangeElements(0, 1, intArray);
exchangeElements(2, 3, intArray);
System.out.println("after : " + Arrays.toString(intArray));
}
public static <T> T[] exchangeElements(int i, int j, T[] array) {
if (i >= array.length || j >= array.length) {
throw new IllegalArgumentException("Индекс превышает размер массива");
}
T temp = array[i];
array[i] = array[j];
array[j] = temp;
return array;
}
}

View File

@@ -0,0 +1,24 @@
package com.algos.vtb.generics_collections.generics_collections;
import java.util.Arrays;
import java.util.List;
public class Task2 {
// Написать метод, который преобразует массив в ArrayList.
public static void main(String[] args) {
String[] strArray = new String[]{"one", "two", "three", "four"};
List<String> strList = convertArrayToArrayList(strArray);
System.out.println(strList.getClass().getSimpleName() + ": " + strList);
Integer[] intArray = new Integer[]{5, 4, 3, 2, 1};
List<Integer> intList = convertArrayToArrayList(intArray);
System.out.println(intList.getClass().getSimpleName() + ": " +intList);
}
public static <T> List<T> convertArrayToArrayList(T[] array ) {
return Arrays.asList(array);
}
}

View File

@@ -0,0 +1,125 @@
package com.algos.vtb.generics_collections.generics_collections;
//a. Даны классы Fruit -> Apple, Orange.
// b. Класс Box, в который можно складывать фрукты. Коробки условно сортируются по типу
// фрукта, поэтому в одну коробку нельзя сложить и яблоки, и апельсины.
// c.
// Для хранения фруктов внутри коробки можно использовать ArrayList.
// d. Написать метод getWeight(), который высчитывает вес коробки. Задать вес одного
// фрукта и их количество: вес яблока — 1.0f, апельсина — 1.5f (единицы измерения не
// важны).
// e. Внутри класса Box написать метод Compare, который позволяет сравнить текущую
// коробку с той, которую подадут в Compare в качестве параметра. True, если их массы
// равны, False — в противном случае. Можно сравнивать коробки с яблоками и
// апельсинами.
// f.
// Написать метод, который позволяет пересыпать фрукты из текущей коробки в другую.
// Помним про сортировку фруктов: нельзя высыпать яблоки в коробку с апельсинами.
// Соответственно, в текущей коробке фруктов не остаётся, а в другую перекидываются
// объекты, которые были в первой.
// g. Не забываем про метод добавления фрукта в коробку.
import java.util.ArrayList;
import java.util.List;
public class Task3 {
public static void main(String[] args) {
Box<Apple> boxOfApples = new Box<>();
boxOfApples.addFruit(new Apple());
boxOfApples.addFruit(new Apple());
boxOfApples.addFruit(new Apple());
// boxOfApples.addFruit(new Orange());
System.out.println(boxOfApples.getWeight());
System.out.println(boxOfApples);
Box<Orange> boxOfOranges = new Box<>();
boxOfOranges.addFruit(new Orange());
boxOfOranges.addFruit(new Orange());
System.out.println(boxOfOranges.getWeight());
System.out.println(boxOfOranges);
System.out.println(boxOfOranges.compare(boxOfApples));
// boxOfApples.moveTo(boxOfOranges);
}
}
abstract class Fruit {
protected float weight;
public Fruit(float weight) {
this.weight = weight;
}
public float getWeight() {
return weight;
}
}
class Apple extends Fruit {
public Apple() {
super(1.0f);
}
@Override
public String toString() {
return "Apple{" +
"weight=" + weight +
'}';
}
}
class Orange extends Fruit {
public Orange() {
super(1.5f);
}
@Override
public String toString() {
return "Orange{" +
"weight=" + weight +
'}';
}
}
class Box<T extends Fruit> {
private final List<T> storage = new ArrayList<>();
public void addFruit(T fruit) {
storage.add(fruit);
}
public double getWeight() {
return storage.stream().mapToDouble(Fruit::getWeight).sum();
}
public boolean compare(Box<?> box) {
// return box.getWeight() == this.getWeight();
return Math.abs(box.getWeight() - this.getWeight()) < 0.00001;
}
public Box<T> moveTo(Box<T> boxSource) {
if (boxSource == this) {
throw new IllegalArgumentException("Could not move elements to itself");
}
storage.forEach(boxSource::addFruit);
storage.clear();
return boxSource;
}
@Override
public String toString() {
return "Box{" +
"storage=" + storage +
'}';
}
}