runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Collections should have extensions to compute order statistic

Open pkothare opened this issue 11 years ago • 27 comments

System.Linq has extensions implemented for computing the minimum and maximum.

Example:

var a = new int[] {100, 300, 200, 400};
WriteLine(a.Max()); // prints 400
WriteLine(a.Min()); // prints 100

While these are useful values when dealing with collections, they are merely special cases of nth order statistics. More often than not, people are also interested in a specific cases. For example, when querying the collection in the sample code above, the question may be posed, what is the 3rd smallest item in the array?

The naive implementation would be to sort the array and print the 3rd item in it. However, there are selection algorithms that can do this more efficiently, without the need to actually invoke a sort method on the array. A method should be implemented in line with the Min and Max extension methods to accomplish this. The API should be a simple as:

WriteLine(a.NthSmallestElement(3)) // should print 300
WriteLine(a.NthSmallestElement(1)) // should print 100
WriteLine(a.NthSmallestElement(a.Length)) // should print 400

The method name may differ based on further discussion. I chose the name based on C++ references that I had seen earlier.

pkothare avatar Apr 06 '15 22:04 pkothare

@theoy, can you make sure this gets triaged?

terrajobst avatar Apr 07 '15 22:04 terrajobst

We need formal API proposal

karelz avatar Nov 14 '16 22:11 karelz

The naive implementation would be to sort the array and print the 3rd item in it.

Changes since this issue was opened mean that the combination .OrderBy(x => x).ElementAt(2) would find the third element using Hoare's quickselect algorithm. The pivot strategy is simple median, which is indeed naïve. I thought of experimenting with random, median-of-three, etc. and even made a start at it, but got distracted by other things. It'd be worth looking at.

JonHanna avatar Nov 14 '16 22:11 JonHanna

I also find tremendous usage of my public static T MaxBy<T, TSort>(this IEnumerable<T> enumerable, Func<T, TSort> sortSelector, IComparer<TSort> sortComparer = null). I wonder if having overloads that take a sort selector like OrderBy would be a good addition to this proposal?

jnm2 avatar Nov 15 '16 14:11 jnm2

Unless it is directly related to these APIs, I would suggest to keep it in separate issue.

karelz avatar Nov 15 '16 16:11 karelz

@karelz To clarify, I'm suggesting that this proposal considers:

a.NthSmallestElement(3)
a.NthSmallestElement(3, _ => _.SortValue)

jnm2 avatar Nov 15 '16 16:11 jnm2

In the last post you suggested adding MaxBy. How does that fit? Either way, we still need formal API proposal. It is also best way to clarify what exactly is asked for and why.

karelz avatar Nov 15 '16 16:11 karelz

@karelz NthSmallestElement(1) is Min() and NthLargestElement(1) is Max(). My point was that I haven't found Min and Max to be half as useful as MinBy and MaxBy, so I would expect that NthSmallestElement(n) would not be half so useful as NthSmallestElement(n, sortSelector). I hope we get both overloads. MaxBy would be great too, but I'd have to start a proposal for that.

jnm2 avatar Nov 15 '16 16:11 jnm2

Separate point: ElementAt is 0-based but it looks like NthSmallestElement is proposed to be 1-based. What are the consequences of choosing 0 or 1?

jnm2 avatar Nov 15 '16 16:11 jnm2

I would expect that NthSmallestElement(n) would not be half so useful as NthSmallestElement(n, sortSelector)

Now I see your point. It makes sense to keep them together as they are very related APIs.

ElementAt is 0-based but it looks like NthSmallestElement is proposed to be 1-based. What are the consequences of choosing 0 or 1?

Very good question - I would expect the proposal to suggest solution here, providing arguments why.

karelz avatar Nov 15 '16 17:11 karelz

One question is whether the IQueryable version of this immediately return .OrderBy(…).ElementAt(n - 1), or directly represent an NthSmallest operation. The latter has the advantage that a provider could more directly support it, but the former would allow for backwards compatibility.

JonHanna avatar Nov 15 '16 17:11 JonHanna

One question is whether the IQueryable version of this immediately return .OrderBy(…).ElementAt(n - 1), or directly represent an NthSmallest operation. The latter has the advantage that a provider could more directly support it, but the former would allow for backwards compatibility.

I would hope it would be symmetrical to whatever tactic Max uses today.

jnm2 avatar Nov 15 '16 17:11 jnm2

The tactic Max uses is to be in Queryable from the time it was first created, so that anyone writing a query provider knows about it, and knows to implement support for it unless that's impossible for some reason.

JonHanna avatar Nov 15 '16 17:11 JonHanna

For example, I would not expect NthSmallest to work until Entity Framework knows about it. It's not unusual for BCL extension methods to be unsupported by EF. I'd prefer the semantics to be preserved. .OrderBy(…).ElementAt(n - 1) has polyfilling going for it but has neither semantics nor in-memory perf on its side.

Separate note: I'm really not in love with the name NthSmallestElement. Off the top of my head I don't know any place I would use it either, so from my vantage point it'd just be extra names in IEnumerable intellisense. This is obviously subjective.

jnm2 avatar Nov 15 '16 17:11 jnm2

On the other hand, it's unlikely that any provider is likely to do anything other than the same as it would with .OrderBy(…).ElementAt(n - 1) (for that matter, with IEnumerable it's going to be pretty much the same as that anyway, except for one object allocation). If providers aren't going to find some extra benefit then that is likely the way to go.

I'm sceptical if there's any need for this for similar reasons. The initial comment said:

The naive implementation would be to sort the array and print the 3rd item in it. However, there are selection algorithms that can do this more efficiently, without the need to actually invoke a sort method on the array.

And at the time of writing, .OrderBy(…).ElementAt(n - 1) would have sorted the array and then found the 3rd item, whereas now it uses a selection algorithm (or just spins through and finds the minimum element if n happens to be 1).

JonHanna avatar Nov 15 '16 17:11 JonHanna

@JonHanna, I'm just curious, is the current process of selection still subject to n^2 worst case time complexity?

pkothare avatar Nov 15 '16 17:11 pkothare

It is, except for the indices of 0 or Count - 1; they're guaranteed linear time.

I've thought about randomising the pivots, but not experimented with it. For one thing I've honestly no idea how fast the PRNG is and hence whether it would have an appreciable downside in some cases.

Ideas? (If the idea in this issue was pursued, it would be necessary to consider it there, to).

JonHanna avatar Nov 15 '16 18:11 JonHanna

@jnm2

MaxBy would be great too, but I'd have to start a proposal for that.

There already is one: https://github.com/dotnet/corefx/issues/2146.

svick avatar Nov 15 '16 19:11 svick

ElementAt is 0-based but it looks like NthSmallestElement is proposed to be 1-based. What are the consequences of choosing 0 or 1?

The justification here to use 1 based instead of 0 based arguments for the method, is because of the semantics of language. For example, given the following array:

var a = new int[] {100, 200, 300, 400};

we can characterize 300 in the following way:

  • It is the 3rd element in the array
  • It has index value of 2
  • It is the 3rd smallest value in the array

If the proposed naming convention NthSmallestElement() is used, it would be incorrect to use a parameter based on index value. Imagine NthSmallestElement(2) returning 300. This would cause so much confusion based on the characterization stated above.

Conversely, a better naming convention instead of NthSmallestElement can be propsed that accepts an index value as an argument.

@JonHanna , the more I think about it, the more I realize that the invocation of OrderBy(...).ElementAt(...) does not signal to a developer consuming the API that they are trying to calculate the nth order statistic. It's true that as a consequence of optimization that it does indeed end up invoking a selection algorithm. I feel like the implementation of NthSmallestElement should be first addressed independently of OrderBy and ElementAt. If at a later point they do happen to converge that's great. Also, the median-of-three, median of medians, BFPRT algorithms, all sound like much more robust ways of solving this problem.

I also agree with @jnm2, the use of NthSmallestElement<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) provides a lot of flexibility.

pkothare avatar Nov 15 '16 20:11 pkothare

Given https://github.com/dotnet/corefx/issues/2146, we might want NthSmallestElementBy for consistency. Also, I make good use of the IComparer<TKey> at times!

jnm2 avatar Nov 15 '16 21:11 jnm2