Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate sequence with step value

Tags:

c#

.net

linq

I have following inputs:

double zmin;
double zmax;
int count;
int N; //Total number of element in result array

I want to generate a sequence of double array with zmin as first and zmax as last value. But from second value until last but one it should be steзped by (zmax-zmin)/count.

Example:

zmin = 1;
zmax = 10;
count = 3

Expected result:

double[] result = { 1, 4, 7, 10}

My try:

double[] result = Enumerable.Repeat(zmin, N).Select(iv => (iv +(zmax-zmin)/count)).ToArray();
like image 993
Suresh Avatar asked Sep 26 '11 09:09

Suresh


1 Answers

public static IEnumerable<double> Range(double min, double max, double step)
{
    double i;
    for (i=min; i<=max; i+=step)
        yield return i;

    if (i != max+step) // added only because you want max to be returned as last item
        yield return max; 
}
like image 156
Muhammad Hasan Khan Avatar answered Oct 11 '22 02:10

Muhammad Hasan Khan