Arithmetic sequence in Ruby using #reduce
Arithmetic sequence in Ruby using #reduce
The question is simple: implement an arithmetic sequence algorithm with params (first,n,c) where first is the first number in the sequence, n is the nth index in the sequence, and c is the addition number for the sequence. This is what I've done but so far it's giving me wrong answers.
EDIT: found solution, below
def nthterm(first, n, c)
(1..n).reduce(first)memo, x
end
Test.assert_equals(nthterm(1, 2, 3), 7)
Test.assert_equals(nthterm(2, 2, 2), 6)
Test.assert_equals(nthterm(-50, 10, 20), 150)
Your description seems off,
c
appears to be a number, not an operator.– b4hand
May 9 '15 at 15:54
c
youre right I will change the description. I will also post the solution I was trying to go for for posterity
– Chris
May 9 '15 at 16:16
You shouldn't edit questions to include the answer. Instead you should post them as a answer.
– b4hand
May 13 '15 at 2:27
1 Answer
1
def nthterm(first, n, c)
(1..n).reduce([first])
end
nthterm(1, 10, 20)
==>
[1, 21, 41, 61, 81, 101, 121, 141, 161, 181, 201]
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I figured it out thanks for the help!
– Chris
May 9 '15 at 1:09