Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an enumerable range for a given min and max with a given number of steps

Tags:

c#

range

winforms

I am familiar with the Enumerable.Range method for generating an enumeration of values. But I would like something slightly different. I want to provide a min value, max value, and a number of desired points.

IE:

Method(double min, double max, int numberOfSteps)

taking

Method(0, 1000, 11);

would return

0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000

I figure for something like this, there must be a built-in method but my search hasn't turned anything up. Am I missing something?

like image 230
Michael Mankus Avatar asked Sep 13 '12 14:09

Michael Mankus


2 Answers

Other than the fact that you want the values to be double, everything else can be done with Enumerable.Range. I don't think there's anything built-in to do what you want, but it's trivial to implement on top of Enumerable.Range:

return Enumerable.Range(0, steps)
                 .Select(i => min + (max - min) * ((double)i / (steps - 1)));

I've written that somewhat carefully so that you always end up with the final value. It does bork if you say you only want a single step though... you might want to guard against that and use Enumerable.Repeat(min, 1) in that case.

like image 139
Jon Skeet Avatar answered Oct 13 '22 17:10

Jon Skeet


Just calculate 'Common Difference' & generate the series:

d = (max - min)/(numberOfSteps - 1)

Now, You can easily generate your series:

int [] a = new [numberOfSteps];

for(i=0; i<numberOfSteps ; i++)
{
  a[i] = min + (numberOfSteps - 1)d;
}
like image 3
Kapil Khandelwal Avatar answered Oct 13 '22 18:10

Kapil Khandelwal