https://www.acmicpc.net/problem/2562
자바스크립트로 백준 문제 풀려면 입력과 출력의 코드를 알아야한다 여간 귀찮은게 아니다 ..
나는 코드 에디터로 vscode 를 사용중이기 때문에
이런식으로 입력 받은 글자들을 input.txt 에 적은 다음
Node.js 환경에서 파일 시스템 모듈인 fs를 사용하여 파일을 읽어들이는 코드를 사용하여야 한다
const fs = require('fs');
const input = fs.readFileSync('linux' ? '/dev/stdin' : './input.txt').toString().trim().split('\n');
대략 이런식으로 외워서 한다 => 백준은 linux 환경이기 때문에 '/dev/stdin' 을 불러오고 vscode 는 txt 파일경로를 불러온다.
## 문제
## 풀이
/**
* 브론즈 3
*
* 출력 :
* 85 //최댓값
* 8 //몇번째 수인지
*/
const fs = require('fs');
const input = fs
.readFileSync('linux' ? '/dev/stdin' : './input.txt')
.toString()
.trim()
.split('\n');
let inputNums = input.map((i) => Number(i));
const maxNum = Math.max(...inputNums);
const index = inputNums.indexOf(maxNum) + 1;
console.log(`${maxNum}\n${index}`);
input 배열의 값은 string 이기 때문에 각각의 요소들을 숫자로 변환해준다
(map() 사용 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
숫자 배열인 inputNums 의 최댓값을 구하기 위해 Math.max() 사용해서 구한다
여기서 주의할 점은
Math.max()
-> array 를 매개변수로 spread operator 를 넣어줘야 한다
✅ spread operator(전개 구문)
: 반복 가능한(iterable) 객체에 적용할 수 있는 문법입니다. 배열이나 문자열 등을 아래처럼 풀어서 요소 하나 하나로 전개시킬 수 있습니다.
const arr = [1, 2, 3, 4, 5]; const str = "string"; console.log(...arr); // 1 2 3 4 5 console.log(...str); // "s" "t" "r" "i" "n" "g"
💡 Why is the spread operator needed for Math.max()?
참고: https://stackoverflow.com/questions/70944210/why-is-the-spread-operator-needed-for-math-max
마지막으로 최댓값의 인덱스 값을 알기 위해 array.indexOf() 사용해서 인덱스 값 구한다 (0 부터 시작이므로 +1 해준다)
참고: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
728x90
반응형
'자료구조+알고리즘 > BOJ' 카테고리의 다른 글
[BOJ-10773-Siver4]제로 (javascript) (0) | 2024.02.29 |
---|---|
[1152][백준_브론즈2] 단어의 개수 - JavaScript (0) | 2023.11.07 |
[11720][java][백준] 숫자의 합 (0) | 2022.02.09 |
[11654][java][백준] 아스키 코드 (0) | 2022.02.09 |
[2884][java][백준] 알람 시계 (0) | 2022.02.08 |