본문 바로가기

백준14584 - 암호 해독 node.js 본문

개발/algorithm

백준14584 - 암호 해독 node.js

자전하는명왕성 2024. 2. 2. 09:53

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

 

문제 풀이 방식

모든 경우의 수를 파악하는 방식으로 문제를 해결했다.

첫 번째 등장한 문자열의 charCode를 하나씩 증가시킨 문자열로 바꾼 뒤, 해당 문자열 안에 사전에 존재하는 단어가 있는지 파악하여 없을 경우 재탐색, 있는 경우 답을 출력하는 로직으로 구현했다.

 

전체 소스 코드

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "입력.txt")
  .toString()
  .trim()
  .split("\n");

function solution(data) {
  const [str, _, ...words] = data;

  for (let i = 0; i < 26; i++) {
    const transStr = str
      .split("")
      .map((el) => {
        const chr = el.charCodeAt() + i;
        const chrCode = chr > 122 ? chr - 26 : chr;
        return String.fromCharCode(chrCode);
      })
      .join("");

    if (verify(words, transStr)) {
      console.log(transStr);
      return;
    }
  }
}

function verify(words, tranStr) {
  for (const word of words) {
    if (tranStr.includes(word)) return true;
  }
  return false;
}

solution(input);
Comments