[JS] BOJ 2562번 최댓값

yeopto·2022년 1월 11일
0

Algorithm

목록 보기
2/11
post-thumbnail

출처

BOJ

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

문제

9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오.

예를 들어, 서로 다른 9개의 자연수

3, 29, 38, 12, 57, 74, 40, 85, 61

이 주어지면, 이들 중 최댓값은 85이고, 이 값은 8번째 수이다.

나의 풀이

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().split("\n").map(x => Number(x));

let max = input[0];
let maxIndex = 1; // 틀린이유는 0으로 할당해줘서. 1로 변경.
// 배열 안 가장 큰값이 input[0]이라면 나머지 input 요소들은 if문에서 다 걸러짐 결국 maxIndex는 0이됨. 
// 하지만 출력은 첫번째 요소라 1로 출력해야하므로 애초에 1로 할당을 해주던가 아님 마지막에 출력할 때 1을 더해주어야함
// 그래야 1이 출력됨. 아님 0이 출력되기에 틀린 것.

solution();

function solution() {
    for (let i = 1; i < 9; i++) {
        if (input[i] > max) {
            max = input[i];
            maxIndex = i + 1;
        }
    }
    console.log(max + "\n" + maxIndex);
}

입력받은 input의 요소들을 map으로 Number 한 뒤 max를 input 첫번째 요소로 할당함. maxIndex는 max가 몇번째 인덱스 요소인지 알기 위함. 솔루션 함수에서 max보다 input[i]가 클 때 maxIndex를 i + 1를 해준 이유는 첫번째 요소가 인덱스는 0부터 시작하기 때문. → 터미널 node.js에선 문제의 출력값과 같게 출력되는데 백준 채점에선 틀렸다고 함. → 해결완료!😀

다른 풀이 1

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().split("\n").map(x => Number(x));

let max = input[0];
let maxIndex = 0;

solution();

function solution() {
    for (let i = 1; i < 9; i++) {
        if (input[i] > max) {
            max = input[i];
            maxIndex = i;
        }
    }
    console.log(max + "\n" + (maxIndex + 1)); 

같은 로직이다. 나의 풀이와 차이는 if문에서 maxIndex를 i + 1한 값으로 할당을 할건가 아님 console.log로 maxIndex에서 1을 더한 값을 출력할 것인가 차이다. 이건 정답. 나의 풀이와 같게 출력되는데 무슨 차이인지 모르겠음.

다른 풀이 2

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().split("\n").map(x => Number(x));

solution();

function solution() {
    "use strict";

    let max = Math.max(...input);

    console.log(max);  
    console.log(input.indexOf(max) + 1);
}

...input에서 ...이 전개 연산자. 객체나 배열의 원소들을 하나씩 꺼내서 펼쳐 리턴함. ES6문법이라 솔루션 함수안에 “use strict”를 명시해줌. Math.max는 파라미터로 입력받은 숫자들 중 최대값을 구해 리턴하는 함수다. 변수 max값을 console.log 해주고 변수 max의 값은 Math.max로 인해 할당되어 있으니 input배열에서 max값의 인덱스가 무엇인지 알려주는 indexOf를 사용하여 인덱스 값을 얻고 +1를 해줌.


둘 다 시간과 메모리가 비슷하다. 나의 풀이와 다른 풀이 1의 차이점이 뭘까? 낼 친구에게 물어봐야겠다. → 멍청했다.. 하지만 해결해서 기분이 좋다.😃

profile
https://yeopto.github.io로 이동했습니다.

0개의 댓글