3003번 : 킹, 퀸, 룩, 비숍, 나이트, 폰 - map사용하여 입출력

2022. 10. 17. 16:00BaekJoon/코드정리

문제

동혁이는 오래된 창고를 뒤지다가 낡은 체스판과 피스를 발견했다.

체스판의 먼지를 털어내고 걸레로 닦으니 그럭저럭 쓸만한 체스판이 되었다. 하지만, 검정색 피스는 모두 있었으나, 흰색 피스는 개수가 올바르지 않았다.

체스는 총 16개의 피스를 사용하며, 킹 1개, 퀸 1개, 룩 2개, 비숍 2개, 나이트 2개, 폰 8개로 구성되어 있다.

동혁이가 발견한 흰색 피스의 개수가 주어졌을 때, 몇 개를 더하거나 빼야 올바른 세트가 되는지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 동혁이가 찾은 흰색 킹, 퀸, 룩, 비숍, 나이트, 폰의 개수가 주어진다. 이 값은 0보다 크거나 같고 10보다 작거나 같은 정수이다.

출력

첫째 줄에 입력에서 주어진 순서대로 몇 개의 피스를 더하거나 빼야 되는지를 출력한다. 만약 수가 양수라면 동혁이는 그 개수 만큼 피스를 더해야 하는 것이고, 음수라면 제거해야 하는 것이다.

예제 입력 1 복사

0 1 2 2 2 7

예제 출력 1 복사

1 0 0 0 0 1

예제 입력 2 복사

2 1 2 1 2 1

예제 출력 2 복사

-1 0 0 1 0 7

제출코드

const fs = require("fs");
let input = fs
  .readFileSync("/dev/stdin")
  .toString()
  .trim()
  .split(" ")
  .map((el) => Number(el));
let originVal = [1, 1, 2, 2, 2, 8];
let result = originVal.map((el, idx) => el - input[idx]);
console.log(result.join(" "));

 

 

 

참고자료 - https://velog.io/@daybreak/Javascript-map%ED%95%A8%EC%88%98

여러가지 예시를 들어 array map 함수를 익혀보자.

1. 간단하게 square root (제곱근)을 구해보자

var numbers = [4,9,16,25,36];
var result = numbers.map(Math.sqrt);
console.log(result);

result
[ 2, 3, 4, 5, 6 ]

2. 이번에는 기존 배열에 값의 x2를 한 배열을 생성해 보자.

다음 세개는 결과가 같다.

var numbers = [ 1,2,3,4,5,6,7,8,9];
var newNumbers = numbers.map(number =>number *2);
console.log(newNumbers);

result
[2, 4, 6, 8, 10, 12, 14, 16, 18]

var numbers = [ 1,2,3,4,5,6,7,8,9];
var newNumbers = numbers.map(function(number){
  return number*2;  // 이렇게 해도 결과가 위에 것과 똑같다.
});
console.log(newNumbers);

result
[2, 4, 6, 8, 10, 12, 14, 16, 18]

var numbers = [ 1,2,3,4,5,6,7,8,9];

function multiplyTwo(number){
    return number *2;
}
var newNumbers = numbers.map(multiplyTwo);
console.log(newNumbers); // 이렇게 해도 결과가 같다. 

result
[2, 4, 6, 8, 10, 12, 14, 16, 18]

위에 결과들은 다 같다.
numbers에 곱하기 2한 값이 newNumbers에 똑같이 나타난다.

map 함수는 기존의 배열을 callbackFunction에 의해 새 배열을 만드는 함수이다.
그러니 기존의 배열이 변하지는 않는다.

3. map 함수는 filter함수와 같이 Object(객체)타입도 컨트롤 할 수도 있다.

var students = [
  {id:1, name:"james"},
  {id:2, name:"tim"},
  {id:3, name:"john"},
  {id:4, name:"brian"}
];

이러한 Object(객체)타입의 변수가 있다.
여기서 이름만 추출하고 싶으면 Array map을 이용해서 쉽게 추출할 수 있다.

var students = [
  {id:1, name:"james"},
  {id:2, name:"tim"},
  {id:3, name:"john"},
  {id:4, name:"brian"}
];
var names = students.map(student =>student.name);
console.log(names); 

result
['james', 'tim', 'john', 'brian']

result를 보면 이름만 추출된것을 볼 수 있다.
여기서 student.name을 student.id로 바꾸면 id 값만 추출된다.

var students = [
  {id:1, name:"james"},
  {id:2, name:"tim"},
  {id:3, name:"john"},
  {id:4, name:"brian"}
];
var names = students.map(student =>student.id);
console.log(names); 

result
[ 1, 2, 3, 4 ]

결과를 보면 id 값만 추출된 것을 볼 수 있다.

3-2 또다른 Object(객체)를 보자.

var testJson = 
    [{name : "이건", salary : 50000000},
     {name : "홍길동", salary : 1000000},
     {name : "임신구", salary : 3000000},
     {name : "이승룡", salary : 2000000}];
 
 var newJson = testJson.map(function(element, index){
        console.log(element);
        var returnObj = {}
        returnObj[element.name] = element.salary;
        return returnObj;
    });
    console.log("newObj");
    console.log(newJson);

result
1. console.log(element);
{ name: '이건', salary: 50000000 }
{ name: '홍길동', salary: 1000000 }
{ name: '임신구', salary: 3000000 }
{ name: '이승룡', salary: 2000000 }
2. console.log(newJson);
[{ '이건': 50000000 },{ '홍길동': 1000000 },{ '임신구': 3000000 },{ '이승룡': 2000000 }]

4. 이번에는 Array를 reverse해보자.

배열 값에 곱하기 2한 값들을 reverse한다.

var numbers = [1,2,3,4,5,6];
var numbersReverse  = numbers.map(number => number *2).reverse();
console.log(numbersReverse);

result
[ 12, 10, 8, 6, 4, 2 ]

5. Array안에 Array가 있는 경우를 보자.

var numbers = [[1,2,3],[4,5,6],[7,8,9]]; //array안에 array가 있는 경우
var newNumbers = numbers.map(array => array.map(number => number *2));
console.log(newNumbers);

result
[ [ 2, 4, 6 ], [ 8, 10, 12 ], [ 14, 16, 18 ] ]