[백준]JS 입력

JH Cho·2022년 7월 30일
0

알고리즘

목록 보기
5/12

C++ 예시

이런 입력 예시가 있다.

5
5 50 50 70 80 100
7 100 95 90 80 70 60 50
3 70 90 80
3 70 90 81
9 100 99 98 97 96 95 94 93 91

참고) 화이트 스페이스 : ' ' 공백,\n 줄바꿈, \t 탭

  • 아래 C++코드는 이해하기 위한 예시일 뿐이므로 부정확 할 수 있다.
int main() {
  int t;  //char t; 로 받았다면 숫자5가 아닌 문자5로 받게 됨.(타입을 미리 지정함.) 
  int arr[1001];
  int arrLength;

  cout << fixed;
  cout.precision(3);
             //(  cin을 이용해 입력 받은 것을 t라는 변수에 넣는다.
             //cin을 쓸 때마다 줄 바꿈이나 공백에 상관 없이 하나씩 입력을 받음. 자바스크립트는 화이트 스페이스로 잘라서 하나씩 받는 기능이 없다. )
  cin >> t; //t는 int라는 정수형 타입이기 때문에 자동으로 숫자로 들어가 숫자 5를 받음
           //(  cin을 이용해 입력 받은 것을 t라는 변수에 넣는다. cin을 쓸 때마다 하나씩 입력을 받음. )
  while(t--) {
    double totalSum = 0.0;
    cin >> arrLength; //두번 째 입력값 5는 arrLength에 들어감
    
    for(int i =0;i<arrLength;++i) {
      cin >> arr[i];  // 여기서 for함수를 통해 5를 입력받은 arrLength만큼 반복하여 해당 줄의 배열 값을 입력 받게 됨.
      totalSum += double(arr[i]);
    }
...생략
  }
}

https://hianna.tistory.com/377

JS 입력 코드

const fs = require("fs"); // "fs"라는 외부 모듈을 가져온다.
let input = fs.readFileSync("./input.txt").toString();
console.log(input); // 위 입력값이 그대로 출력됨.  콘솔로그 1번
input = input.split("\n"); // 인풋값을 \n(줄바꿈)으로 나눠주겠다.
console.log(input); // 줄 별로 배열 안의 배열이 됨. 
                    
const testCaseNum = +input[0]; // 그냥 input[0]을 넣어주면 문자열 '5'가 선언이 됨. 그래서 숫자로 변환하기 위해 'Number(input[0])'을 써줌.  //console.log(+input[0]) = 5
//'+'단항 연산자를 사용하여 '+input[0]' 으로 가능.
//console.log("testCaseNum : ", testCaseNum); 5
// 참고 - 여기서 ++i는 i++처럼 작동하더라. 미리 값 증가 안시키고.
for (let i = 1; i <= testCaseNum; ++i) {  //인덱스 1인 2번째 줄부터 시작하고 끝 줄까지 반복.
  // 참고 : i++ 은 먼저 해당 연산 수행 후 i의 값을 1 증가시킴 / ++i는 수행 전 1 증가해서 해당 연산을 수행
  const arr = input[i].split(" ")// .map((item) => +item); 아래 3줄의 코드가 map함수의 기능을 풀어놓은 것.
  /* 공백으로 분리된 상태 : ['5', '50', '50', '70','80', '100'] */
  let newArr = [];
  for (let i = 0; i < arr.length; ++i) {
    newArr.push(+arr[i])   // arr 요소를 숫자로 바꿔서 newArr 배열에  push! 현 상태: [5, 50, 50, 70, 80, 100]
  }
  console.log("arr : ", arr);   //3번째
  console.log("newArr : ", newArr); //4번째
  break;

} 
  • 위 코드 실제로 쓸 때는 콘솔로그 빼도 됨. 걍 중간 중간 배열 확인차 넣어 놓은 것.
  • 첫번째 콘솔로그 출력
const fs = require("fs");
let input = fs.readFileSync("./input.txt").toString();
console.log(input);

------------
5
5 50 50 70 80 100
7 100 95 90 80 70 60 50
3 70 90 80
3 70 90 81
9 100 99 98 97 96 95 94 93 91
  • 두번째 콘솔로그 출력
const fs = require("fs");
let input = fs.readFileSync("./input.txt").toString().
console.log(input); // 위 입력값이 그대로 출력됨.
input = input.split("\n"); // 인풋값을 \n(줄바꿈)으로 나눠주겠다.
console.log(input);
----------------------

[
  '5',
  '5 50 50 70 80 100',
  '7 100 95 90 80 70 60 50',
  '3 70 90 80',
  '3 70 90 81',
  '9 100 99 98 97 96 95 94 93 91'
]
  • 3번째 & 4번째
arr :  [ '5', '50', '50', '70', '80', '100' ]
newArr :  [ 5, 50, 50, 70, 80, 100 ]
// input[1] 을  함수를 통해 출력한 모습.
// 이게 반복 되면서 위 입력값을 완성.
  • 문제 풀 준비가 완료된 기본 코드 세팅 완료.
const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
// 인풋을 리눅스(백준)이면 dev 내 컴이면 txt를 받겠다.
let input = fs.readFileSync(filePath).toString().split('\n');
// 파일 받은걸 동기식을 불러와서 문자열로 만들고 그걸 줄바꿈을 기준으로 나눠서 input에 배열로 넣겠다.
input = input[0];
input = input.split(' ').map((item) => +item);
/*
공백으로 배열을 나눠서
map함수 (콜백함수대로 실행해서 새 배열을 만들어준다.)
let newArr = [];
for (let i = 0; i < arr.length; ++i) {
newArr.push(+arr[i])   // arr 요소를 숫자로 바꿔서 newArr 배열에  push! 
}       숫자로 변환하여 새 배열 생성.
  */

백준 4344번에 적용해서 풀어보기.

const fs = require("fs");
let input = fs.readFileSync("./input.txt").toString();
//console.log(input); 입력값 확인.
input = input.split("\n");
const inputC = +input[0]; // C = 0
const inputTestCase = [];

for (let i = 1; i <= inputC; ++i) {
  const arr = input[i].split(" ").map((item) => +item); // 배열 요소를 문자 -> 숫자로 바꿔줌.

  const newArr = [];
  for (let i = 1; i <= arr[0]; ++i) {
    newArr.push(arr[i]); // 첫번째 인덱스 요소 제외한 다음 값들이 배열로 들어가야 함.
  }
  const testCase = {
    N: arr[0],
    arr: newArr,
  };
  //console.log("testcase : ", testCase); testCase 값 확인
  inputTestCase.push(testCase);
}
console.log(inputTestCase); 

--------------여기까지의 결과------
[
  { N: 5, arr: [ 50, 50, 70, 80, 100] },
  { N: 7,
    arr: [100, 95, 90, 80, 70, 60, 50]
  },
  { N: 3, arr: [ 70, 90, 80 ] },
  { N: 3, arr: [ 70, 90, 81 ] },
  {
    N: 9,
    arr: [100, 99, 98, 97, 96, 95, 94, 93, 91]
  }
]


--------solution-----------
  function solution(C, testCase) {
  console.log("C : ", C);
  console.log("testCase : ", testCase);
}

solution(inputC, inputTestCase);

----------결과 ------------
c : 5
testCase : [
  { N: 5, arr: [ 50, 50, 70, 80, 100] },
  { N: 7,
    arr: [100, 95, 90, 80, 70, 60, 50]
  },
  { N: 3, arr: [ 70, 90, 80 ] },
  { N: 3, arr: [ 70, 90, 81 ] },
  {
    N: 9,
    arr: [100, 99, 98, 97, 96, 95, 94, 93, 91]
  }
]

총평 : 개어렵네; 수고했다 오늘 치킨 먹을 자격이 있다.
초보자로서 처음 문제 풀 때는 안풀리면 너무 고민하지 말고 구글링해서 찾아봐라.
글고 첨에는 map reduce filter indexOf 배열 메서드 사용하기 보다는
for 문을 사용해서 직접 배열을 만드는 연습을 하면 좋댄다. 해보자.

profile
주먹구구식은 버리고 Why & How를 고민하며 프로그래밍 하는 개발자가 되자!

0개의 댓글