https://www.acmicpc.net/submit/11720/79358793
N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성
해결 방법
1. 주어진 숫자를 프로그램에 사용할수있도록 쪼개기
let test = input.split('\n')[1];
2. 주어진 숫자는 문자열이니 배열에 담자
3. 합산식을 해야하니 문자열을 숫자로 변환하자
let array = Array.from(String(test), Number);
4. 더하자
let result = (array.reduce((accumulator, currentValue) => accumulator + currentValue, 0));
5. 제출
const fs = require('fs');
const filePath = process.platform === "linux" ? '/dev/stdin' : __dirname + '/input.txt';
const input = fs.readFileSync(filePath).toString().trim();
let test = input.split('\n')[1];
let array = Array.from(String(test), Number);
let result = (array.reduce((accumulator, currentValue) => accumulator + currentValue, 0));
console.log(result);
위의 식을 풀면서 느낀점은... 메서드를 참 잘 알고 있어야겠구나..
reduce 메서드 아자아자 화이팅
reduce 메서드: 배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환
reduce는 이렇게 생김
arr.reduce(callback[, initialValue])
callback 함수를 각 요소를 순회하며 실행함
지정한 initialValue 의 형태로 반환함
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Array.prototype.reduce() - JavaScript | MDN
The reduce() method of Array instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across al
developer.mozilla.org
'코딩테스트 뿌수기' 카테고리의 다른 글
[백준 2884번 node.js] 알람 시계 (0) | 2024.06.09 |
---|---|
[백준 2908번 node.js] 상수 (0) | 2024.06.09 |
[백준 : 10988번 node.js] 팰린드롬인지 확인하기 (0) | 2024.06.08 |
[백준 : 2753번 node.js] 윤년 (0) | 2024.06.06 |
[백준 : 10172번 node.js] 개 (0) | 2024.06.06 |