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?
(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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With