Loading...
본문 바로가기
👥
총 방문자
📖
0개 이상
총 포스팅
🧑
오늘 방문자 수
📅
0일째
블로그 운영

여러분의 방문을 환영해요! 🎉

다양한 개발 지식을 쉽고 재미있게 알려드리는 블로그가 될게요. 함께 성장해요! 😊

백준 문제풀이/Nodejs

[백준][백트래킹] 15650 N과 M NodeJs 구현

by 꽁이꽁설꽁돌 2024. 10. 14.
728x90
반응형

목차

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

    문제

     

     

    문제 구현 방향

    조합을 통해 모든 경우의 수를 세서 출력해 주었다.

     

    NodeJs로 알아가면 좋은 것들

    1. process.stdout.write

    console.log는 줄바꿈이 있기 때문에 이것을 사용하면 줄바꿈을 없앨 수 있다.

    하지만 숫자는 안되니 string으로 바꾸어 주어야 한다.

    process.stdout.write(String(combinations[i][j]));

     

    2. push시 객체 복사

    배열이나 객체는 참조 타입이기 때문에, 단순히 배열이나 객체를 추가하면 그 배열이나 객체의 참조값만 저장된다. 이 참조값은 원본 배열 또는 객체가 변경되거나 초기화되면 영향을 받게 되어 undefined가 출력될 수 있다.

      combinations.push([...stack]);

     

     

    코드 구현

    const input = require("fs")
      .readFileSync("../test.txt", "utf-8")
      .trim()
      .split(" ");
    
      let n = Number(input[0]);
      let m = Number(input[1]);
    
    let stack =[];
    let combinations =[];
    
    function combi(start){
        if(stack.length === m){
            combinations.push([...stack]);
            return;
        }
        for(let i= start; i<=n; i++){
            stack.push(i);
            combi(i+1);
            stack.pop();
        }
    }
    
    combi(1);
    
    for(let i=0; i< combinations.length; i++){
        for(let j=0; j< m; j++){
            process.stdout.write(String(combinations[i][j])); //String만됨
            process.stdout.write(" ");
        }
        process.stdout.write("\n");
    }

     

    반응형