x만큼 간격이 있는 n개의 숫자 Array()

lim1313·2021년 7월 21일
0

프로그래머스

문제2. x만큼 간격이 있는 n개의 숫자

함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다. 다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요.

제한 조건
x는 -10000000 이상, 10000000 이하인 정수입니다.
n은 1000 이하인 자연수입니다.


내 풀이

function solution(x,n){
  let answer = [x]
  let value = x
  for(let i = 1; i< n; i++ ){
    x += value
    answer.push(x)
  }
  return answer
}

내 풀이 과정

1. 
2. 
3. 

다른 사람 풀이

function solution(x, n) {
    return Array(n).fill(x).map((v, i) => (i + 1) * v)
}

---

function solution(x, n) {
    return (n === 1) ? [x] : [ ...solution(x, n - 1), (x * n)];
}

나의 코드가 초라해지는 순간...이었다.

  • Array().fill()
  • [...Array(n).keys()]
  • Array.from();

학습 내용 정리

  1. Array().fill()
const array1 = [1,2,3,4]
console.log(array1.fill(0, 2, 4)) //->[1,2,0,0]
console.log(array1.fill(2)) //-> [2,2,2,2]

let arrFill = Array(3).fill("x")
console.log(arrFill) //-> ["x", "x", "x"]

  1. [...Array(n).keys()]
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
  console.log(key);
}
console.log([...iterator])

// expected output: 0
// expected output: 1
// expected output: 2

// Array [0, 1, 2]
  1. Array.from();
Array.from('Tei');
//["T", "e", "i"]

Array.from([1, 2, 3], x => x + x);
//[2, 4, 6]
profile
start coding

0개의 댓글