[프로그래머스 lev1/JS] x만큼 간격이 있는 n개의 숫자

woolee의 기록보관소·2022년 10월 22일
0

알고리즘 문제풀이

목록 보기
11/178

문제 출처

프로그래머스 lev1 - x만큼 간격이 있는 n개의 숫자

문제 요약

정수 x와 자연수 n,
x부터 시작해서 x씩 증가하는 숫자를 n개 지니는 리스트 반환하기

나의 풀이

for 문에서 i+=x로 증가폭 설정하기.
x==0이라면 n개 만큼 배열에 넣어주면 됨.

function solution(x, n) {
  let answer = [];
  if (x > 0) {
    for (let i=0; i<n*x; i+=x) {
      answer.push(x+i);
    }
    return answer;
  }
  else if (x < 0) {
    for (let i=0; i>n*x; i+=x) {
      answer.push(x+i);
    }
    return answer;
  }
  else if (x == 0) {
    while (x<n) {
      answer.push(0);
      x++; 
    }
    return answer; 
  }
}

console.log(solution(0, 11));

다른 풀이

그냥 곱해주면 된다.

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

for문이 더 빠르다고는 하더라

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

array.from 메서드

function solution(x, n) {
    return nNumbers(x,n);
}

const nNumbers = (x, n)=>{
    return Array.from({length: n},(v,index)=>(index+1)*x);
};

재귀

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

console.log(solution(2, 4));
profile
https://medium.com/@wooleejaan

0개의 댓글