Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create list of numbers and append its reverse to it efficiently in Ruby

Tags:

arrays

range

ruby

Given a minimum integer and maximum integer, I want to create an array which counts from the minimum to the maximum by two, then back down (again by two, repeating the maximum number).

For example, if the minimum number is 1 and the maximum is 9, I want [1, 3, 5, 7, 9, 9, 7, 5, 3, 1].

I'm trying to be as concise as possible, which is why I'm using one-liners.

In Python, I would do this:

range(1, 10, 2) + range(9, 0, -2)

In Ruby, which I'm just beginning to learn, all I've come up with so far is:

(1..9).inject([]) { |r, num| num%2 == 1 ? r << num : r }.reverse.inject([]) { |r, num| r.unshift(num).push(num) }

Which works, but I know there must be a better way. What is it?

like image 831
Kiwi Avatar asked May 12 '10 19:05

Kiwi


1 Answers

(1..9).step(2).to_a + (1..9).step(2).to_a.reverse

But shorter would be

Array.new(10) { |i| 2 * [i, 9-i].min + 1 }

if we're code golfing :)

like image 86
rampion Avatar answered Sep 30 '22 17:09

rampion