Skip to content

Instantly share code, notes, and snippets.

@1ou
Created May 11, 2021 12:03
Show Gist options
  • Save 1ou/5e394e30770be7eaa96fa7c812a85a31 to your computer and use it in GitHub Desktop.
Save 1ou/5e394e30770be7eaa96fa7c812a85a31 to your computer and use it in GitHub Desktop.
Anton Skub’ev, [11.05.21 14:58]
Написать аналог Enum (как если бы до Java 1.5) на примере какого-нибудь перечислимого списка, например списка валют.
Нужно:
- самое важное требование, которое следует удовлетворять в процессе всей реализации - расставить как можно меньшее количество граблей для разработчика, который в будущем будет добавлять новые значения
- иметь фиксированный список значений, задаваемый на этапе компиялции
- иметь строгую типизацию значений
- уметь безопасно сравнивать значения по ==
- получать все значения
- иметь неизменяемый ordinal (порядковый номер с 0 в порядке объявления значений)
- получать значения по ordinal
- иметь название значения, совпадающее с названием поля для значения
- искать по имени
public double convert(Currency from, Currency to, double amount) {
///
}
public void main() {
double a = convert(Currency.USD, Currency.RUB, 100);
}
class Currency {
private final int order;
private final String currencyName;
public static final Currency USD;
public static final Currency RUB;
private static List<Currency> values;
static {
final values = new ArrayList<>();
final Field[] fields = Currency.class.getFields();
int k = 0;
for (int i = 0; i < fields.lenght; i++) {
if (field.class.equals(Currency.class)) {
final String currencyName = field.getName();
// give access to edit static final field
field.set(new Currency(k++, currencyName));
values.add(field);
}
}
}
public ordinal() {
return this.order;
}
private Currency(final int order, final String currencyName ) {
this.order = order;
this.currencyName = currencyName;
}
public static Currency[] values() {
final int len = values.length;
final Currency[] copyCurrencies = new Currency[len];
for (int i = 0; i < len; i++) {
copyCurrencies[i] = values[i];
}
return copyCurrencies;
}
public static Currency valueOf(final String currencyName) {
final int len = this.values.length;
for (int i = 0; i < len; i++) {
if (cuurencyName.equals(this.values[i].currencyName)) {
return this.values[i];
}
}
throw new NoSuchElementException();
}
}
Дана последовательность целых чисел. Необходимо найти минимально возможное произведение пары элементов последовательности.
Например, для последовательности чисел 9 4 2 5 3 ответ будет 6.
1 2 3 4 5
1 2 (2 x min)
-6 -7 -8 - 10 (2 x max)
-5 -4 0 1 2 (1 x max * 1 x min)
-5 -1 -1 2 2
long calculate(int[] arr) {
if (arr == null) {
throw new IllegalStateException();
}
int n = arr.length();
if (n < 2) {
throw new IllegalStateException();
}
// min1 <= min2 <= max2 <= max1
long min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE, max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
if (arr[i] <= min1) {
min2 = min1;
min1 = arr[i];
} else if (arr[i] < min2) {
min2 = arr[i];
}
if (arr[i] >= max1) {
max2 = max1;
max1 = arr[i];
} else if (arr[i] > max2) {
max2 = arr[i];
}
}
if (min1 > 0) {
return min1 * min2;
} else if (max1 < 0) {
return max1 * max2;
} else {
return min1 * max1;
}
}
Напишите реализацию Java-итератора по заданному на входе набору целых чисел, возвращающий только четные (по значению) числа из этого набора.
- реализовать Iterator<Integer>
- придумать интерфейс для конечного пользователя (что принимать на вход)
- БЕЗ удаления элементов
Anton Skub’ev, [11.05.21 14:58]
class CustomIterator {
Iterator collection;
public Iterator(Iterator<Integer> collection) {
this.collection = collection;
}
int next() {
while(collection.hasNext()) {
int next = collection.next();
if (next % 2 == 0) {
return next;
}
}
throw new NoSuchElementException():
}
boolean hasNext() {
try {
retrun collection.next();
} catch (NoSuchElementExceptio ex) {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment