package ru.sigma.test.learning.generics;

import java.util.Collection;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: emaltsev
 * Date: 25.11.13
 * Time: 10:34
 * To change this template use File | Settings | File Templates.
 */
interface UnaryPredicate<T> {
    public boolean test(T obj);
}

public class Algorithm {

    public static <T> void swap(T[] a, int i, int j) {
        T temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static <T> int findFIrst(List<T> list, int begin, int end, UnaryPredicate<T> p) {
        for (; begin < end; ++begin)
            if (p.test(list.get(begin)))
                return begin;
        return -1;
    }

    public static int gcd(int x, int y) {
        for (int r; (r = x % y) != 0; x = y, y = r) ;
        return y;
    }

    public static <T extends Object & Comparable<? super T>> T max(List<? extends T> list, int begin, int end) {
        T maxElem = list.get(begin);

        for (++begin; begin < end; ++begin)
            if (maxElem.compareTo(list.get(begin)) < 0)
                maxElem = list.get(begin);

        return maxElem;
    }

    public static <T> int countIf(Collection<T> c, UnaryPredicate<T> p) {
        int count = 0;
        for (T elem : c)
            if (p.test(elem))
                ++count;

        return count;
    }
}
