package edd.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; public class ListsAndIterators { public static List duplicate(List list) { List result = new ArrayList<>(); for (T elem : list) { result.add(elem); result.add(elem); } return result; } public static List consecute(List list) { List result = new ArrayList<>(); int c = 1; for (T elem : list) { for (int i = 0; i < c; i++) { result.add(elem); } c++; } return result; } public static List removeDuplicates(List list) { List result = new ArrayList<>(); for (T elem : list) { if (!result.contains(elem)) { result.add(elem); } } return result; } private static class Pow2Iterator implements Iterator { private int n; private int i; private int result; public Pow2Iterator(int n) { this.n = n; this.i = 0; this.result = 1; } @Override public boolean hasNext() { return i < n; } @Override public Integer next() { if (!hasNext()) { throw new NoSuchElementException(); } int r = result; result *= 2; i++; return r; } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator pow2(int n) { return new Pow2Iterator(n); } private static class PrimesIterator implements Iterator { private int current; private int max; public PrimesIterator(int max) { this.max = max; this.current = 2; } @Override public boolean hasNext() { return current <= max; } private boolean isPrime(int n) { for (int i = 2; i < n; i++) { if (n % i == 0) { return false; } } return true; } private void getNextPrime() { while (!isPrime(++current)) ; } @Override public Integer next() { if (!hasNext()) { throw new NoSuchElementException(); } int result = current; getNextPrime(); return result; } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator primes(int max) { return new PrimesIterator(max); } private static class SquaresIterator implements Iterator { private int[] array; private int currentIndex; public SquaresIterator(int[] list) { this.array = list; this.currentIndex = 0; } @Override public boolean hasNext() { return currentIndex < array.length; } @Override public Integer next() { if (!hasNext()) { throw new NoSuchElementException(); } int x = array[currentIndex]; currentIndex++; return x * x; } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator squares(int[] array) { return new SquaresIterator(array); } }