reverseSequence.js (8kyu 30)

Codewars 알고리즘 풀이


Description

  • Get the number n(n > 0) to return the reversed sequence from n to 1.
    • n부터 1까지 역순, 연속으로 반환한다.



Solution 01

function reverseSequence(n) {
  let result = [];
  
  for (let i = n; i > 0; i--) {
    result.push(i);
  }
  
  return result;
}

reverseSequence(5);  // [5, 4, 3, 2, 1]
reverseSequence(4);  // [4, 3, 2, 1]
reverseSequence(3);  // [3, 2, 1]
reverseSequence(2);  // [2, 1]
reverseSequence(1);  // [1]


Solution 02

function reverseSequence(n) {
  return new Array(n).fill().map((_, index) => n - index);
}

reverseSequence(5);  // [5, 4, 3, 2, 1]
reverseSequence(4);  // [4, 3, 2, 1]
reverseSequence(3);  // [3, 2, 1]
reverseSequence(2);  // [2, 1]
reverseSequence(1);  // [1]


Solution 03

function reverseSequence(n) {
  return new Array(n).fill(0).map((_, index) => n - index);
}

reverseSequence(5);  // [5, 4, 3, 2, 1]
reverseSequence(4);  // [4, 3, 2, 1]
reverseSequence(3);  // [3, 2, 1]
reverseSequence(2);  // [2, 1]
reverseSequence(1);  // [1]


Solution 04

function reverseSequence(n) {
  return Array.from({ length: n }, (_, index) => n - index);
}

reverseSequence(5);  // [5, 4, 3, 2, 1]
reverseSequence(4);  // [4, 3, 2, 1]
reverseSequence(3);  // [3, 2, 1]
reverseSequence(2);  // [2, 1]
reverseSequence(1);  // [1]


Solution 05

function reverseSequence(n) {
  if (n === 1) return [n];
  
  return [n].concat(reverseSequence(n - 1));
}

reverseSequence(5);  // [5, 4, 3, 2, 1]
reverseSequence(4);  // [4, 3, 2, 1]
reverseSequence(3);  // [3, 2, 1]
reverseSequence(2);  // [2, 1]
reverseSequence(1);  // [1]