Create an array with a range of floating point values, given a step - CSharp System

CSharp examples for System:Array Create

Description

Create an array with a range of floating point values, given a step

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from  w  ww  .ja va 2s.c o  m

public class Main{
        /// <summary>
    /// Create an array with a range of floating point values, given a step
    /// </summary>
    /// <param name="from"></param>
    /// <param name="step"></param>
    /// <param name="to"></param>
    /// <returns></returns>
    public static double[] CreateRangedArray(double from, double to, double step)
    {
      // parameter constrains
      if (from > to || step < 0) return null;

      int count = (int)Math.Ceiling((to - from) / step) + 1;
      var arr = new double[count];

      for(int idx = 0; idx < count; idx++)
      {
        arr[idx] = (from <= to ? from : to);
        from += step;
      }

      return arr;
    }
        /// <summary>
    /// Create an array with a range of integer values
    /// </summary>
    /// <param name="from">Range start</param>
    /// <param name="to">Range end</param>
    /// <returns></returns>
    public static int[] CreateRangedArray(int from, int to)
    {
      int step = (from < to ? 1 : -1);
      int size = (step == 1 ? to - from : from - to);

      var arr = new int[size+1];
      for (int idx = 0; idx <= size; idx++, from+=step)
        arr[idx] = from;

      return arr;
    }
}

Related Tutorials