[백준/9093] 단어 뒤집기

문제

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

 

정답

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";

const input = fs.readFileSync(filePath).toString().split("\n");

function solution(input) {
  const caseCount = Number(input[0]);

  for (let i = 1; i <= caseCount; i++) {
    let words = input[i].split(" ");
    let result = words
      .map((word) => {
        return word.split("").reverse().join("");
      })
      .join(" ");
    console.log(result);
  }
}

solution(input);

 

풀이

각 단어를 배열을 만들어준다.

let words = input[i].split(" "); //  [ 'I', 'am', 'happy', 'today' ]

 

단어를 다시 배열로 만든다.

word.split("");

// [ 'I' ]
// [ 'a', 'm' ]
// [ 'h', 'a', 'p', 'p', 'y' ]
//  [ 't', 'o', 'd', 'a', 'y' ]

 

단어를 뒤집어준다.

word.split("").reverse()

// [ 'I' ]
// [ 'm', 'a' ]
// [ 'y', 'p', 'p', 'a', 'h' ]
// [ 'y', 'a', 'd', 'o', 't' ]

 

뒤집어진 배열을 문자로 만들어주고, 전체를 문자로 만들어주면 완성