► JS Algorithm/Programmers

[Programmers] JavaScript 알고리즘 | Lv.0 수 조작하기 1

다람트리 2024. 1. 2. 20:34
반응형

🔒 문제 설명

정수 n과 문자열 control이 주어집니다. control은 "w", "a", "s", "d"의 4개의 문자로 이루어져 있으며, control의 앞에서부터 순서대로 문자에 따라 n의 값을 바꿉니다.

  • "w" : n이 1 커집니다.
  • "s" : n이 1 작아집니다.
  • "d" : n이 10 커집니다.
  • "a" : n이 10 작아집니다.

규칙에 따라 n 바꿨을 가장 마지막에 나오는 n 값을 return 하는 solution 함수를 완성해 주세요.


🔒 제한사항 

  • -100,000 ≤ n ≤ 100,000
  • 1 ≤ control 길이 ≤ 100,000
    • control은 알파벳 소문자 "w", "a", "s", "d"로 이루어진 문자열입니다.

🔒 입출력 예

n control result
0 "wsdawsdassw" -1

 


🔒 입출력 예 설명

입출력 예 #1

  • 수 n은 control에 따라 다음과 같은 순서로 변하게 됩니다.
  • 0 → 1 → 0 → 10 → 0 → 1 → 0 → 10 → 0 → -1 → -2 → -1
  • 따라서 -1 return 합니다.

 

🔐 solution of mine

reduce()

      const solution = (n, control) =>
        console.log(
          [...control].reduce(
            (a, c) =>
              c === "w"
                ? a + 1
                : c === "s"
                ? a - 1
                : c === "d"
                ? a + 10
                : c === "a"
                ? a - 10
                : a,
            n
          )
        );

      solution(0, "wsdawsdassw"); // expected output: -1

 


 

🔐 solution of others 

객체로 데이터구조화

reduce()

  const solution = (n, control) => {
  
    const operations = {
      w: (a) => a + 1,
      s: (a) => a - 1,
      d: (a) => a + 10,
      a: (a) => a - 10,
    };

    return console.log([...control].reduce((a, c) => operations[c](a), n));
  };

  solution(0, "wsdawsdassw"); // expected output: -1

 

◆ 객체로 데이터구조화 참고풀이

  const solution = (n, control) => {
  
    const operations = {
      w: (a) => a + 1,
      s: (a) => a - 1,
      d: (a) => a + 10,
      a: (a) => a - 10,
    };
    
    console.log(operations["w"]); // output: (a) => a + 1
    console.log(operations["w"](4)); // output: 5
  };

  solution(0, "wsdawsdassw"); // expected output: -1

 

 

레벨0치고.... 너무 풀이법도 다양하고 어려웠다 ㅜㅜ

 

덕분에 공부가 되어서,

지금 진행하는 리엑트네이티브 프로젝트에서 공통 props를 객체로 빼서

가독성을 올리고, 코드라인이 줄었다

올레~!

 

🔐 solution of others 

객체로 데이터구조화

  const solution = (n, control) => {
    let a = {
      w: +1,
      s: -1,
      d: +10,
      a: -10,
    };

    for (let i = 0; i < control.length; i++) {
      n += a[control[i]];
    }
    return console.log(n);
  };

  solution(0, "wsdawsdassw"); // expected output: -1

 

🔐 solution of others 

switch문

  const solution = (n, control) => {
    for (let i = 0; i < control.length; i++) {
      switch (control[i]) {
        case "w":
          n++;
          break;
        case "s":
          n--;
          break;
        case "d":
          n += 10;
          break;
        case "a":
          n -= 10;
          break;
      }
    }
    return console.log(n);
  };

  solution(0, "wsdawsdassw"); // expected output: -1

switch문도 잘 안쓰는 문법이라, 코드작성에 익숙해지려고함 오랜만에 직접 작성해봄

 

◆ 문자열 index

console.log("wsdawsdassw"[0]); //output: w

문자도 배열처럼 인덱스번호가 적용된다는걸 알게됨!

 

🔐 solution of others 

map()

reduce()

  const solution = (n, control) => {
    const setValue = (s) =>
      s === "w" ? 1 : s === "s" ? -1 : s === "d" ? 10 : -10;

    return console.log(
      [...control].map((x) => setValue(x)).reduce((a, b) => a + b, n)
    );
  };

  solution(0, "wsdawsdassw"); // expected output: -1

 

🔐 solution of others 

map()

for (let of)

  const solution = (n, control) => {
    let answer = n;
    for (let i of control) {
      if (i === "w") {
        n++;
      } else if (i === "s") {
        n--;
      } else if (i === "d") {
        n += 10;
      } else {
        n -= 10;
      }
    }
    return console.log(n);
  };

  solution(0, "wsdawsdassw"); // expected output: -1

 

🔐 solution of others 

Array.from()

reduce()

  const solution = (n, control) =>
    console.log(
      Array.from(control).reduce((acc, word) => {
        if (word === "w") acc++;
        if (word === "s") acc--;
        if (word === "d") acc += 10;
        if (word === "a") acc -= 10;
        return acc;
      }, n)
    );

  solution(0, "wsdawsdassw"); // expected output: -1

 


 

반응형