ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Programmers] JavaScript 알고리즘 | Lv.0 배열의 원소만큼 추가하기
    ► JS Algorithm/Programmers 2024. 1. 5. 20:28
    반응형

    🔒 문제 설명

    아무 원소도 들어있지 않은 배열 X 있습니다. 양의 정수 배열 arr 매개변수로 주어질 , arr 앞에서부터 차례대로 원소를 보면서 원소가 a라면 X 뒤에 a a 추가하는 일을 반복한 뒤의 배열 X return 하는 solution 함수를 작성해 주세요.


    🔒 제한사항 

    • 1 ≤ arr의 길이 ≤ 100
    • 1 ≤ arr 원소 ≤ 100

    🔒 입출력 예

    arr result
    [5, 1, 4] [5, 5, 5, 5, 5, 1, 4, 4, 4, 4]
    [6, 6] [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
    [1] [1]

    🔒 입출력 예 설명

    입출력 예 #1

    • 예제 1번에 대해서 a와 X를 나타내보면 다음 표와 같습니다.
    a X

    []
    5 [5, 5, 5, 5, 5]
    1 [5, 5, 5, 5, 5, 1]
    4 [5, 5, 5, 5, 5, 1, 4, 4, 4, 4]

    따라서 [5, 5, 5, 5, 5, 1, 4, 4, 4, 4]를 return 합니다.

     

     

    입출력 예 #2

    • 예제 2번에 대해서 a와 X를 나타내보면 다음 표와 같습니다.
    a X

    []
    6 [6, 6, 6, 6, 6, 6]
    6 [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]

    따라서 [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]를 return 합니다.

     

     

    입출력 예 #3

    • 예제 2번에 대해서 a와 X를 나타내보면 다음 표와 같습니다.
    a X

    []
    1 [1]

    따라서 [1] return 합니다.


     

    🔐 solution of mine

    forEach()

    push()

    new Array()

    Array.fill()

      const solution = (arr) => {
        let answer = [];
        arr.forEach((v, i) => answer.push(...new Array(v).fill(v)));
        return console.log(answer);
      };
    
      solution([5, 1, 4]); // expected output: [5, 5, 5, 5, 5, 1, 4, 4, 4, 4]
      solution([6, 6]); // expected output: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
      solution([1]); // expected output: [1]

     


     

    🔐 solution of others 

    reduce()

    new Array()

    Array.fill()

      const solution = (arr) =>
        arr.reduce((acc, cur) => [...acc, ...new Array(cur).fill(cur)], []);

     

    🔐 solution of others 

    reduce()

    concat()

    Array()

    fill()

      const solution = (arr) =>
        console.log(
          arr.reduce((acc, cur) => acc.concat(Array(cur).fill(cur)), [])
        );
    
      solution([5, 1, 4]); // expected output: [5, 5, 5, 5, 5, 1, 4, 4, 4, 4]
      solution([6, 6]); // expected output: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
      solution([1]); // expected output: [1]

     

    🔐 solution of others 

    map()

    Array()

    fill()

    flat()

      const solution = (arr) =>
        console.log(arr.map((v) => Array(v).fill(v)).flat());
    
      solution([5, 1, 4]); // expected output: [5, 5, 5, 5, 5, 1, 4, 4, 4, 4]
      solution([6, 6]); // expected output: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
      solution([1]); // expected output: [1]

     

    🔐 solution of others 

    flatMap()

    Array()

    fill()

      const solution = (arr) =>
        console.log(arr.flatMap((v) => Array(v).fill(v)));
    
      solution([5, 1, 4]); // expected output: [5, 5, 5, 5, 5, 1, 4, 4, 4, 4]
      solution([6, 6]); // expected output: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
      solution([1]); // expected output: [1]

     


     

    반응형
Designed by Tistory.