Integers in Range Recursion

Ayumi Tanaka
Algorithm Novice
Published in
Oct 1, 2020

Q. Write an algorithm that is the integers in range function with recursion.

const intInRangeRecursive = function (startValue, endValue) { if (endValue - startValue === 2) {  return [startValue + 1]; } else {  let list = intInRangeRecursive(startValue, endValue - 1);  list.push(endValue - 1);  return list; }}console.log(intInRangeRecursive(1, 5)); // [2, 3, 4]
  1. If endValue — startValue === 2, return [startValue + 1].
  2. Otherwise, declare the list is equal to the function intInRangeRecursive(startValue, endValue1).
  3. Push the element endValue — 1 to list.
  4. Return list.
? 5 - 1 === 2 // False
list = intInRangeRecursive(1, 4)
list.push(4)
list = [4]
? 4 - 1 === 2 // False
list = intInRangeRecursive(1, 3)
list.push(3)
list = [3, 4]
? 3 - 1 === 2 // True // [1 + 1]
list = [2, 3, 4]

--

--