0

I have an array of Int32, every element contains index of reference to an object in another array:

class MyObject {
    public Int32 Time;
}

MyObject[] _objects;
Int32[] _indices;

Now i need to find index of an object which Time is closest to some Double d. The pseudocode of comparison could be like this:

for (i = 0; i < _indices.Length; i++)
    if (d > _objects[indices[i]].Time)
        ...

I don't want to write algorithm by hands. Can i somehow use one of standard library algorithms?

EDIT:

I think it is important to say, that _indices stores indexes of objects in order of increasing .Time.

Yola
  • 18,496
  • 11
  • 65
  • 106

1 Answers1

2

You could use this LINQ query:

int indexClosestTime = indices
    .Select(i => new { Object = _objects[i], Index = i})
    .OrderBy(x => Math.Abs(d - x.Object.Time))
    .First().Index;

I have used Math.Abs, so it doesn't mater if the Time is smaller or greater than d. You wasn't clear regarding this. It also only returns one index even if there are multiple with the same distance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • That's ok with comparison, because i need the closest. I have one question, i have never used LINQ yet, but i have heard that LINQ is slow, and this part of code will be running a lot of times. Wouldn't it hurt performance? – Yola Mar 13 '15 at 14:37
  • @Yola: LINQ is not slow per se. But you need to understand what you're doing. In this case it just "loops" the index-array once and orders the anonymous types by distance. I don't think that you can get it much faster with a plain loop. By the way, sometimes LINQ does not only help to get readable and concise solutions for complex problems but also to improve performance since many LINQ methods use set based approaches(like `Union`, `Intersect`, `Join`, `GroupBy` etc). – Tim Schmelter Mar 13 '15 at 14:56