[백준/Node.js] 상어 초등학교 #21608
짧 후기
문제를 읽자마자 바로 코드부터 작성하려는 습관을 줄이고 있다.
큰 틀을 생각하면서 그에 대한 생각을 종이에 적어 이런 flow로 코드를 작성하면 되겠다고 생각하고 그 생각대로 함수를 분리하여 작성했다.
그랬더니 solution
안에 써야할 코드가 함수 단위로 분리되어 코드 수가 적어졌으며, 디버깅시에도 어느 함수에서 문제가 발생한 것인지 파악하기 쉬워 당분간은 이런 방식대로 코드를 작성해보려고 한다.(이게 역할분리인건가..?ㅋㅋ)
아 그리고 이번주부터 유튜버 쩜님이 올려주시는 삼성기출문제풀기에 참가하고 있는데 문제만 풀고 글은 작성하지 않았었다.
이것도 추후에 풀이에 제출한 코드를 올려야겠다.
제출코드
const fs = require('fs');
const DIRECTION = [
[-1, 0],
[0, -1],
[0, 1],
[1, 0],
];
const setStudentPosition = (student, prorities, board, N) => {
const possiblePosition = {};
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
if (board[i][j] !== 0) continue;
const ruleScore = [0, 0]; // 우선순위친구수, 비어있는칸수
for (let k = 0; k < 4; k++) {
const [dx, dy] = DIRECTION[k];
const [nextX, nextY] = [i + dx, j + dy];
if (nextX < 0 || nextY < 0 || nextX >= N || nextY >= N) continue;
if (prorities.includes(board[nextX][nextY])) {
ruleScore[0]++;
} else if (board[nextX][nextY] === 0) ruleScore[1]++;
}
const key = JSON.stringify(ruleScore);
if (!possiblePosition[key]) possiblePosition[key] = [[i, j]];
else possiblePosition[key].push([i, j]);
}
}
const sortedResult = Object.keys(possiblePosition).sort((a, b) => {
const [a0, a1] = JSON.parse(a);
const [b0, b1] = JSON.parse(b);
if (a0 !== b0) return b0 - a0;
return b1 - a1;
});
const [x, y] = possiblePosition[sortedResult[0]][0];
board[x][y] = student;
};
const calcSatisfaction = (board, studentPriorities, N) => {
let total = 0;
const SCORE = [0, 1, 10, 100, 1000];
studentPriorities.forEach(([student, ...priorities]) => {
let adjScore = 0;
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
if (board[i][j] !== student) continue;
for (let k = 0; k < 4; k++) {
const [dx, dy] = DIRECTION[k];
const [x, y] = [i + dx, j + dy];
if (x < 0 || x >= N || y < 0 || y >= N) continue;
if (priorities.includes(board[x][y])) adjScore++;
}
}
}
total += SCORE[adjScore];
});
return total;
};
const solution = (N, studentPriorities) => {
const board = Array.from({ length: N }, () => new Array(N).fill(0));
studentPriorities.forEach(([student, ...priorities]) => {
setStudentPosition(student, priorities, board, N);
});
return calcSatisfaction(board, studentPriorities, N);
};
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const N = Number(input[0]);
const studentPriorities = input.slice(1).map((v) => v.split(' ').map(Number));
console.log(solution(N, studentPriorities));
Author And Source
이 문제에 관하여([백준/Node.js] 상어 초등학교 #21608), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@ahu8867/백준Node.js-상어-초등학교-21608저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)