Notice
Recent Posts
Recent Comments
Link
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[๋ฐฑ์ค€ 14888๋ฒˆ] ์—ฐ์‚ฐ์ž ๋ผ์›Œ๋„ฃ๊ธฐ - ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(nodejs) ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm/Baekjoon

[๋ฐฑ์ค€ 14888๋ฒˆ] ์—ฐ์‚ฐ์ž ๋ผ์›Œ๋„ฃ๊ธฐ - ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(nodejs)

Lennon 2022. 2. 18. 20:19
728x90
๋ฐ˜์‘ํ˜•

https://www.acmicpc.net/problem/14888

 

14888๋ฒˆ: ์—ฐ์‚ฐ์ž ๋ผ์›Œ๋„ฃ๊ธฐ

์ฒซ์งธ ์ค„์— ์ˆ˜์˜ ๊ฐœ์ˆ˜ N(2 ≤ N ≤ 11)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” A1, A2, ..., AN์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ Ai ≤ 100) ์…‹์งธ ์ค„์—๋Š” ํ•ฉ์ด N-1์ธ 4๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ, ์ฐจ๋ก€๋Œ€๋กœ ๋ง์…ˆ(+)์˜ ๊ฐœ์ˆ˜, ๋บ„์…ˆ(-)์˜ ๊ฐœ์ˆ˜, 

www.acmicpc.net

const fs = require('fs');
let [n, ...input] = fs.readFileSync('dev/stdin').toString().trim().split('\n');
const [expression, sign] = input.map((v) => v.split(' ').map(Number));
const type = ['+', '-', '*', '/'];

const solution = () => {
  const signType = [];

  sign.forEach((ele, idx) => {
    if (ele !== 0) {
      for (let i = 0; i < ele; i++) {
        signType.push(type[idx]);
      }
    }
  });

  let max = Number.MIN_SAFE_INTEGER;
  let min = Number.MAX_SAFE_INTEGER;

  for (let ele of permutations(signType)) {
    const value = calculate(expression, ele);
    max = Math.max(max, value);
    min = Math.min(min, value);
  }

  if (max == '-0' || max == '+0') max = 0;
  if (min == '-0' || min == '+0') min = 0;

  console.log(`${max}\n${min}`);

  function* permutations(elements) {
    if (elements.length === 1) {
      yield elements;
    } else {
      const [first, ...rest] = elements;

      for (const a of permutations(rest)) {
        for (let i = 0; i < elements.length; i++) {
          const start = a.slice(0, i);
          const ended = a.slice(i);
          yield [...start, first, ...ended];
        }
      }
    }
  }

  function calculate(number, operate) {
    let idx = 0;
    let finalValue = number[0];
    for (let i = 1; i < number.length; i++) {
      const value = number[i];
      const oper = operate[idx++];

      if (oper === '+') {
        finalValue += value;
      } else if (oper === '-') {
        finalValue -= value;
      } else if (oper === '*') {
        finalValue *= value;
      } else {
        finalValue = parseInt(finalValue / value);
      }
    }

    return finalValue;
  }
};

solution();

์ฃผ์˜ํ•  ์ 

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋Š” +0, -0์„ ํ‘œ์‹œํ•˜๋ฏ€๋กœ ์ฒ˜๋ฆฌ๊ฐ€ ํ•„์š”ํ•˜๋‹ค.

๋‚˜๋ˆ—์…ˆ์€ ์ •์ˆ˜๋กœ ๋‚˜์˜ค๊ฒŒ ์ฒ˜๋ฆฌํ•ด์•ผํ•œ๋‹ค.(๋ฌธ์ œ์— ์จ์žˆ์Œ)

evalํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋‹น์—ฐํžˆ ์•ˆ๋œ๋‹ค.

 

๋ถ€ํ˜ธ์— ๋Œ€ํ•ด ์ˆœ์—ด์„ ๊ตฌํ•œ ํ›„ ๊ณ„์‚ฐํ•˜๋ฉด ๋์ด๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
Comments