관리 메뉴

Silver Library (Archived)

다시봐도 헷깔리는 While 문 본문

CS Library/JavaScript - Data Structure

다시봐도 헷깔리는 While 문

Chesed Kim 2021. 8. 25. 22:08
반응형

물론 지금을 기준으로입니다.

다만 현 시점에서는 이해하기가 다소 한계가 느껴지네요.

 

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

 

10951번: A+B - 4

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

www.acmicpc.net

 

let input = require('fs').readFileSync('/dev/stdin').toString().split('\n');

for (let i = 0; i < input.length - 1; i++) {
    let numbers = input[i].split(' ');
    
    console.log(Number(numbers[0]) + Number(numbers[1]));
}

해석.

이대로라면, 반복문이 시작되는 지점인 값은 0 부터고, 0 보다도 큰 값은 '입력되는 값들의 길이 수 만큼(에서 -1)' 이다.

그렇게 해서, 해당 입력값은 더해나가는 식.

 

여기서, 변수를 생성해서 해당 변수 명에다가 입력 값이 참조 하게 될 i 값을 참조.

그리해서 .split method 를 사용함으로서 '각 테스트 케이스는 한 줄로 이루어져 있으며' 의 조건이 성립. 

'각 줄에 A와 B가 주어진다(0<A, B<10)' 는, 현 시점에서는 그냥 있는 그대로 받아들이는 수밖에 없어 보인다.

 

다만, 출력 조건이 '각 테스트 케이스마다 A+B를 출력한다' 이다.

 

1) 다시말해, '각 케이스 마다' 출력이 가능하도록 for 반복문을 구성하고.

2) 여기에, A+B 를 확실하게 실행 가능한 프로그램을 구성하기 위해

3) '입력 값이 받아 진 값대로 = numbers'

4) 이들을 넘버링화 시킨다

console.log(Number(numbers[0] + Number(numbers[1]));

 

이렇게 해석을 해 보았는데, 이게 그나마 가장 근접한 해답의 이유다.

 

그럼 가장 큰 의문이 드는 것 하나가, '도대체 for 반복문에서 input.length 는 언제 가장 적절히 사용 할 수 있는가?'

 

자, 체스판을 뒤집어보자.

"When using byte length semantics (the default), the input length represents the number of bytes in the current character set. In other words, it is the number of bytes used by the character string in the character set used by the runtime system." 

 

여전히 이해가 안간다. 그럼, 이건 어떨까.

"You are assigning its number of characters"

 

꽤 맞는 것 같다. 아니...어쩌면 내가 한글로 이해하려해서 그런 걸지도...ㄷ

만약 이 글을 미래에 누군가 본다면 무례하게 느껴지겠지만, 미리 사과한다. 편의상 잠시 영어로 적겠다...


"You must read how to name variables, there are certain rules. Your second question is, assume you have a string variable called input. You are assigning its number of characters to length." 

Note: this quote's name of the variable example was 'length'. Do not get confused from here.

 

Literally, each number of characters represent the count of its value.

Whatever numeric was input, then it obviously indicates 'the length of its value.'

And the example is given as follows:

 

If I input:

1 1

2 3

3 4

9 8

5 2 

 

Suppose to see:

2

5

7

17

7

 

Or...this input.length method might has the purpose to limit its length to print it.

Maybe I should look for 'length' property. ※Caution: length is property, not a method.

Ok. Don't expand this too long.

let input = require('fs').readFileSync('/dev/stdin').toString().split('\n');

for (let i = 0; i < input.length - 1; i++) {
    let numbers = input[i].split(' ');
    
    console.log(Number(numbers[0]) + Number(numbers[1]));
}

Seems this i < input.length - 1 literally indicates; the count of input's length. From that, subtract value 1.

And found it.

 

[JavaScript] input 한글 입력길이 제한 (korean, text, length, limit)

input type="text" 의 입력가능한 문자길이 제한은 보통 maxlength attrtibute를 이용한다. 이 때 maxlength를 넘어서는 문자열이 입력되면 alert으로 경고창을 출력하고자 한다면 아래처럼 처리할 수 있음. 근

bloodguy.tistory.com

It was really the code to limit its number of values to print it from the given input value.

 

 

아무래도 정말 출력 길이를 제한하는 목적이 전부인가 보다. 현재로서는 그 용도로 밖에 안 보임...그런데 너무 찝찝하다.

 

그래서 readline 을 찾아보았습니다.

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

const input = [];

rl.on('line', function (line) {
    input.push(line);
}).on('close', function () {
    for (let i = 0; i < input.length; i++) {
        const num1 = +input[i].split(' ')[0];
        const num2 = +input[i].split(' ')[1];

        const result = num1 + num2;

        if (!result) {
            break;
        }
        console.log(result);
    }

    process.exit();
});

그냥 fs 모듈의 특징인걸까요? 하지만 readline 은 좀 더 명확하게 설정해 둔 모습이 보입니다.

if (!result) { break; } 가 유사시, 확실히 막아주고 있습니다.

 

여담: 10952번 문제. = 10951 과 유사.

"for문의 2번째 조건을 지움으로써, while문을 만든다.

if문은 0을 false로 인식한다. 

result가 0 이면 !result가 true가 되면서 if문이 동작하고 break로 while문을 빠져나오게 된다."

 

결론:

input.length - 1 의 용도는, 구분 용도가 맞다. 우선은 설명 가능한 모듈로 사용해보기.

'CS Library > JavaScript - Data Structure' 카테고리의 다른 글

Prototype 을 요약해보기.  (0) 2021.09.08
연결 리스트와 이진 트리  (0) 2021.09.07
백준 1065 한수 - JS  (0) 2021.08.08
BJ 2562 - JS  (0) 2021.08.06
Note of readline module - Node.js  (0) 2021.07.24