Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array with evenly-spaced values

Tags:

ruby

What is an easy way to generate an array that has values with a fixed distance between them?

For example:

1, 4, 7, 10,... etc

I need to be able to set start, end, and step distance.

like image 575
NullVoxPopuli Avatar asked Jan 29 '11 17:01

NullVoxPopuli


People also ask

Which function is used to create an array with evenly spaced points?

Creating Sequential Arrays: arange and linspace The linspace function allows you to generate evenly-spaced points within a user-specified interval ( and are included in the interval).

How do you evenly space a list in Python?

The most straightforward option that Python offers is the built-in range() . The function call range(10) returns an object that produces the sequence from 0 to 9 , which is an evenly spaced range of numbers.

What is the NumPy function used to create evenly spaced arrays analogous to the range () function used in Python?

arange() NumPy arange() is one of the array creation routines based on numerical ranges. It creates an instance of ndarray with evenly spaced values and returns the reference to it.

Is Linspace an array?

linspace) is a tool in Python for creating numeric sequences. It's somewhat similar to the NumPy arange function, in that it creates sequences of evenly spaced numbers structured as a NumPy array.


2 Answers

Try using Range.step:

> (1..19).step(3).to_a
=> [1, 4, 7, 10, 13, 16, 19]
like image 164
Mark Byers Avatar answered Sep 18 '22 18:09

Mark Byers


In Ruby 1.9:

1.step(12).to_a   #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
1.step(12,3).to_a #=> [1, 4, 7, 10]

Or you can splat instead of to_a:

a = *1.step(12,3)  #=> [1, 4, 7, 10]
like image 22
Phrogz Avatar answered Sep 21 '22 18:09

Phrogz