Programovanie (1) v C/C++
1-INF-127, ZS 2024/25
Riešenia testu č. 2
Skočit na navigaci
Skočit na vyhledávání
Úloha č. 1
import java.util.*;
public class ComparableArrayList<E extends Comparable<E>> extends ArrayList<E> implements Comparable<List<E>> {
public ComparableArrayList() {
super();
}
public ComparableArrayList(int initialCapacity) {
super(initialCapacity);
}
public ComparableArrayList(Collection<? extends E> c) {
super(c);
}
@Override
public int compareTo(List<E> o) {
Iterator<E> iterator = iterator();
Iterator<E> oIterator = o.iterator();
while (iterator.hasNext()) {
if (!oIterator.hasNext()) {
return 1;
}
E next = iterator.next();
E oNext = oIterator.next();
int c = next.compareTo(oNext);
if (c != 0) {
return c;
}
}
if (oIterator.hasNext()) {
return -1;
}
return 0;
}
}
Úloha č. 2
public static TreeMap<String, Integer> findFrequentStrings(Scanner scanner) {
TreeMap<String, Integer> result = new TreeMap<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Map<String, Integer> frequencies = new HashMap<>();
int maxFrequency = 0;
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String s = lineScanner.next();
int current;
if (!frequencies.containsKey(s)) {
frequencies.put(s, current = 1);
} else {
frequencies.put(s, current = frequencies.get(s) + 1);
}
maxFrequency = Math.max(maxFrequency, current);
}
for (String s : frequencies.keySet()) {
if (frequencies.get(s) == maxFrequency) {
if (!result.containsKey(s)) {
result.put(s, 1);
} else {
result.put(s, result.get(s) + 1);
}
}
}
}
return result;
}
Úloha č. 3
import java.util.*;
public class RepeatedElementsIterator<E> implements Iterator<E> {
private Iterator<E> iterator;
private Map<E, Integer> repetitions;
private boolean hasNext;
private E next;
private int repetitionsLeft;
public RepeatedElementsIterator(Iterator<E> iterator, Map<E, Integer> repetitions) {
this.iterator = iterator;
this.repetitions = new HashMap<>(repetitions);
findNext();
}
private void findNext() {
hasNext = false;
while (iterator.hasNext() && !hasNext) {
E element = iterator.next();
if (!repetitions.containsKey(element)) {
repetitionsLeft = 1;
} else if (repetitions.get(element) > 0) {
repetitionsLeft = repetitions.get(element);
} else {
continue;
}
hasNext = true;
next = element;
}
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public E next() {
if (hasNext()) {
E result = next;
if (--repetitionsLeft == 0) {
findNext();
}
return result;
} else {
throw new NoSuchElementException();
}
}
}