백준 5단계: 1차원 배열 (node.js)

Hmm·2022년 1월 27일

백준

목록 보기
7/8

10818번

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "예제.txt";
// const input = fs.readFileSync(filePath).toString().split("");
const input = fs.readFileSync(filePath).toString().trim().split("\n");

const arr = input[1].split(" ");

let max = arr.reduce(function (a, b) {
  return Math.max(a, b);
});

let min = arr.reduce(function (a, b) {
  return Math.min(a, b);
});
console.log(`${min} ${max}`);


Math.min()과 Math.max() 메서드를 쓰면 손쉽게 해결할 수 있다.
사실 Math메서드 말고 다른 방법이 있긴 하나 해당 문제에선 오류를 만들 것 같아 math()와 reduce를 사용하였다.

그러나, 두 스프레드 (...)와 apply 모두 실패하거나 배열에 요소가 너무 많은 경우 잘못된 결과를 반환합니다. 왜냐하면 배열이 함수 요소를 통과하기 때문입니다. 배열 요소를 함수 매개 변수로 사용할 수 있습니다. apply와 built-in 함수들의 사용법은 여기서 확인 할 수 있습니다. reduce를 사용한 방법에는 해당 문제가 발생하지 않습니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/max

2562번

헷갈렸던 개념

findIndex, indexOf

indexOf는 값이 정확하게 일치하는지(===)로 확인한다.

지금 배열의 값들은 string형태이다. 나는 최댓값을 number형태로 쓰고 있으므로 배열의 값들은 map을 이용해서 다 number형으로 똑같이 바꿔준다.

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "예제.txt";
// const input = fs.readFileSync(filePath).toString().split("");
const input = fs.readFileSync(filePath).toString().trim().split("\n");
const arr = input.map((x) => Number(x));
const max = Math.max(...input);
// indexOf대신 이렇게 써도 된다.
// const index = arr.findIndex((el) => el == max) + 1;
const index = arr.indexOf(max) + 1;
console.log(`${max}\n${index}`);

2577번

i와 일치하는 걸 배열로 만들고, 그 배열의 길이를 반환한다.

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "예제.txt";
// const input = fs.readFileSync(filePath).toString().split("");
const input = fs.readFileSync(filePath).toString().trim().split("\n");
const multiplied = input[0] * input[1] * input[2];
const arr = String(multiplied).split("");
for (let i = 0; i <= 9; i++) {
  const numEA = arr.filter((el) => el == i);
  console.log(numEA.length);
}

3052번

헷갈렸던 개념

Set

Set을 사용하면 중복된 값 없는 배열을 얻을 수 있다. 다만 set은 다시 Array로 변환해주어야 한다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Set

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "예제.txt";
// const input = fs.readFileSync(filePath).toString().split("");
const input = fs.readFileSync(filePath).toString().trim().split("\n");
const digitArr = input.map((el) => Number(el) % 42);
const set = new Set(digitArr);
const notSameArr = [...set];
console.log(notSameArr.length);

참고 https://velog.io/@wandakim/boj-node.js-%EB%B0%B1%EC%A4%80-3052%EB%B2%88-%EB%82%98%EB%A8%B8%EC%A7%80-javascript

1546번

헷갈렸던 개념

Reduce함수

문제를 잘못 읽어서 다르게 풀고 있었다ㅠ_ㅠ 시간아까웡

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "예제.txt";
// const input = fs.readFileSync(filePath).toString().split("");
const input = fs.readFileSync(filePath).toString().trim().split("\n");
const N = Number(input[0]);
const scoreArr = input[1].split(" ").map((el) => Number(el));
const max = scoreArr.reduce(function (a, b) {
  return Math.max(a, b);
});
const cheatScoreArr = scoreArr.map((el) => (el / max) * 100);
const reducer = (prev, current) => prev + current;
const plusTotal = cheatScoreArr.reduce(reducer);
const average = plusTotal / N;
console.log(average);

8958번

헷갈렸던 개념

전체 사이클이 몇번 도는지 체크하고 작은 사이클을 묶어줄 것

+=

변수에 오른쪽 값을 더한 값을 다시 변수에 할당한다.

// foo = 'foo'
// bar = 5
// baz = true
// 위와 같은 변수를 가정할 때

// Number + Number -> 덧셈
bar += 2 // 7
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "예제.txt";
// const input = fs.readFileSync(filePath).toString().split("");
const input = fs.readFileSync(filePath).toString().trim().split("\n");
const caseNum = +input[0];
for (let i = 1; i <= caseNum; i++) {
  let zeroNum = 0;
  let total = 0;
  input[i].split("").map((el) => {
    if (el === "O") {
      zeroNum++;
      total += zeroNum;
    } else {
      zeroNum = 0;
    }
  });
  console.log(total);
}

참고 https://velog.io/@wandakim/boj-node.js-%EB%B0%B1%EC%A4%80-8958%EB%B2%88-OX%ED%80%B4%EC%A6%88javascript

4344번

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "예제.txt";
const input = fs.readFileSync(filePath).toString().trim().split("\n");
const cases = input.splice(1);
const C = Number(input[0]);
for (let i = 0; i < C; i++) {
  let oneCase = cases[i]
    .trim()
    .split(" ")
    .map((el) => Number(el));
  let cOfOneCase = oneCase[0];
  let scores = oneCase.splice(1);
  let sum = 0;
  for (let x = 0; x < cOfOneCase; x++) {
    sum += scores[x];
  }
  let average = sum / cOfOneCase;
  let higherScores = scores.filter((el) => el > average);
  let studentRatio = ((higherScores.length / scores.length) * 100).toFixed(3);
  console.log(`${studentRatio}%`);
}

0개의 댓글