ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Programmers] JavaScript 알고리즘 | Lv.0 수열과 구간 쿼리 4
    ► JS Algorithm/Programmers 2024. 7. 14. 16:23
    반응형

     🔒 문제 설명

    정수 배열 arr와 2차원 정수 배열 queries이 주어집니다. queries의 원소는 각각 하나의 query를 나타내며, [s, e, k] 꼴입니다.

    각 query마다 순서대로 s ≤ i ≤ e인 모든 i에 대해 i가 k의 배수이면 arr[i]에 1을 더합니다.

    규칙에 따라 queries 처리한 이후의 arr return 하는 solution 함수를 완성해 주세요.


    🔒 제한사항  

    • 1 ≤ arr 길이 ≤ 1,000
      • 0 ≤ arr 원소 ≤ 1,000,000
    • 1 ≤ queries 길이 ≤ 1,000
      • 0 ≤ s ≤ e < arr 길이
      • 0 ≤ k ≤ 5

    🔒 입출력 예

    arr queries result
    [0, 1, 2, 4, 3] [[0, 4, 1],[0, 3, 2],[0, 3, 3]] [3, 2, 4, 6, 4]

    🔒 입출력 예 설명

    입출력 예 #1

    • 쿼리에 따라 arr 다음과 같이 변합니다.
    arr
    [0, 1, 2, 4, 3]
    [1, 2, 3, 5, 4]
    [2, 2, 4, 5, 4]
    [3, 2, 4, 6, 4]
    • 따라서 [3, 2, 4, 6, 4] return 합니다.

    ※ 2023 04 27 입출력 설명이 수정되었습니다.


     

    🔐 solution of mine

    for...of

    for...in

    function solution(arr, queries) {
      let answer = arr;
      for (let array of queries) {
        for (let idx in arr) {
          if (array[0] <= idx && idx <= array[1] && idx % array[2] === 0) {
            answer[idx] += 1;
          }
        }
      }
      return console.log(answer);
    }
    
    solution(
      [0, 1, 2, 4, 3],
      [
        [0, 4, 1],
        [0, 3, 2],
        [0, 3, 3],
      ]
    ); //output: [3, 2, 4, 6, 4]

     


     

    🔐 solution of others

    for...of

    function solution(arr, queries) {
      for (let [s, e, k] of queries) {
        for (let i = s; i <= e; i++) {
          if (i % k === 0) {
            arr[i]++;
          }
        }
      }
      return console.log(arr);
    }
    
    solution(
      [0, 1, 2, 4, 3],
      [
        [0, 4, 1],
        [0, 3, 2],
        [0, 3, 3],
      ]
    ); //output: [3, 2, 4, 6, 4]

     

    🔐 solution of others 

    Array.prototype.map()

    Array.prototype.slice()

    const solution = (a, q) =>
      q.length
        ? solution(
            a.map((v, i) =>
              q[0][0] <= i && i <= q[0][1] && !(i % q[0][2]) ? v + 1 : v
            ),
            q.slice(1)
          )
        : console.log(a);
    
    solution(
      [0, 1, 2, 4, 3],
      [
        [0, 4, 1],
        [0, 3, 2],
        [0, 3, 3],
      ]
    ); //output: [3, 2, 4, 6, 4]

     

    🔐 solution of others 

    Array.prototype.reduce()

    const solution = (a, q) =>
      console.log(
        q.reduce((bucket, [s, e, k]) => {
          for (let i = s; i <= e; i++) {
            if (i % k === 0) bucket[i]++;
          }
          return bucket;
        }, a)
      );
    
    solution(
      [0, 1, 2, 4, 3],
      [
        [0, 4, 1],
        [0, 3, 2],
        [0, 3, 3],
      ]
    ); //output: [3, 2, 4, 6, 4]

     


     

     
     
    반응형
Designed by Tistory.