-1

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;
}

1 Answers1

0

If you fix the return type of minPos() to be consistent with the parameter, then you'd do it with a lambda expression like this:

static <U extends Comparable<U>> U minPos(Iterable<U> coll) {
    return foldLeft((U) null, coll, (a, b) -> a != null && a.compareTo(b) <= 0 ? a : b);
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Unfortunately we cannot change the signature for this assignment, so I cannot do that as much as I'd like to. – laraveldev17 Jan 30 '20 at 11:54
  • @laraveldev17 Then how do you get an `int` value from a `U`, given that `U` can be just about anything? – Andreas Jan 30 '20 at 14:09