I am stuck figuring out how I may solve this problem. The goal is to find the position of the minimum value of an Iterable (l) without loops. There is a similar problem here: How would I get the minVal without a loop and using only foldLeft? But this can simply use a lambda. In this case I need to pass a class that implements BiFunction as the third argument to the foldLeft or foldRight call. How would you solve this? I started making a new class that implemented BiFunction, but got lost as to how I determine the position of the minimum value in l.
static <U,V> V foldLeft(V e, Iterable<U>l, BiFunction<V,U,V> f){
//BiFunction takes a U and V and returns a V
V ret = e;
for(U i : l) {
ret = f.apply(ret, i);
}
return ret;
}
static <U,V> V foldRight(V e, Iterable<U>l, BiFunction<U,V,V> f){
for(U u:l) {
e = f.apply(u, e);
}
return e
}
static <U extends Comparable<U>> int minPos(Iterable<U> l){
// write using fold. No other loops permitted.
int value = 0;
return value;
}
UPDATE: I have figured it out
class FindMinPos<U extends Comparable<U>> implements BiFunction<U, U, U> {
public Iterable<U> l;
public ArrayList<U> a = new ArrayList<U>();
public int minPos;
public FindMinPos(Iterable<U> l) {
this.l = l;
for(U i : l) {
a.add(i);
}
}
@Override
public U apply(U u, U u2) {
U minVal = u != null && u.compareTo(u2) <= 0 ? u : u2;
minPos = a.indexOf(minVal);
return minVal;
}
}
static <U extends Comparable<U>> int minPos(Iterable<U> l){
// write using fold. No other loops permitted.
int minPos = 0;
FindMinPos<U> f = new FindMinPos<U>(l);
U minValue = foldLeft(l.iterator().next(), l, f);
minPos = f.minPos;
return minPos;
}