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

こ雲淡風輕ζ 提交于 2020-06-24 08:20:02

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/12408118/get-an-enumerable-range-for-a-given-min-and-max-with-a-given-number-of-steps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!