views:

249

answers:

3

Say I have a list val list = List(34, 11, 98, 56, 43).

Now how do I find the index of the minimum element of the list (e.g. 1 in this case)?

+6  A: 

An empty list has no minimal value. A list of only one element has that element as its minimum. For all other lists the minimum is either the first element of that list or the minimum of the rest of the list, depending on which is greater.

So to find the index this becomes: For a list of length 1 the index of the minimum is 0. If the list has more than one element and the minimum of the tail is greater than the head, it's also 0. If the head is greater then the index is the index of the minimum of the tail plus one.

sepp2k
+7  A: 

On Scala 2.8:

List(34, 11, 98, 56, 43).zipWithIndex.min._2
Daniel
+1  A: 

I suppose the easiest way is list.indexOf(list.min). It will throw an exception when the list is empty, although so will Daniel's answer.

James Cunningham