์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 42578] ์œ„์žฅ (Javascript)

์€์ง„ 2021. 8. 3. 12:22

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 42578] ์œ„์žฅ (Javascript)
ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค


โœ๏ธIdea Sketch

2021-07-08

1. ๋ฌธ์ œ ์ดํ•ด

  • ๋งค์ผ ๋‹ค๋ฅธ ์˜ท์„ ์ž…์„ ๊ฒƒ
  • ํ•œ๊ฐ€์ง€ ์ข…๋ฅ˜๋งŒ ์ž…์–ด๋„ ๋จ
  • ๊ฐ™์€ ์ข…๋ฅ˜์˜ ์˜ท์€ ๋ฐ˜๋“œ์‹œ ์ตœ๋Œ€ ํ•˜๋‚˜๋งŒ ์ž…์Œ
  • ์ด๋ฆ„์ด ๊ฐ™์€ ์˜ท์€ ์กด์žฌํ•˜์ง€ ์•Š์Œ

2. ๋กœ์ง ์ดํ•ด 1

  • ์˜ท ์ข…๋ฅ˜๋ณ„๋กœ ๋ช‡๊ฐ€์ง€๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”์ง€ ์ •๋ฆฌ : Map()
  • ํ•œ๊ฐ€์ง€๋งŒ ์ž…๊ฑฐ๋‚˜, ๋‘๊ฐ€์ง€๋ฅผ ์ž…๊ฑฐ๋‚˜, โ€ฆ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๊ธฐ

3. ๋กœ์ง ์ดํ•ด 2 : headgear์— ํ•ด๋‹นํ•˜๋Š” ์˜์ƒ์ด yellow_hat, green_turban์ผ ๊ฒฝ์šฐ

  • yellow_hat์„ ์„ ํƒํ•˜๋Š” ๊ฒฝ์šฐ, green_turban์„ ์„ ํƒํ•˜๋Š” ๊ฒฝ์šฐ, ์•„๋ฌด๊ฒƒ๋„ ์„ ํƒํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ
  • ์ด 3๊ฐ€์ง€
  • ์•„๋ฌด๊ฒƒ๋„ ์„ ํƒํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๋ฅผ ํฌํ•จ

4. ๊ฒฝ์šฐ์˜ ์ˆ˜ ๊ตฌํ•˜๊ธฐ

  • ๊ณต์ง‘ํ•ฉ ํฌํ•จ ์•ˆ๋˜๋ฏ€๋กœ(์ตœ์†Œ ํ•œ ๊ฐœ์˜ ์˜์ƒ์€ ์ž…๋Š”๋‹ค) -1์„ ํ•ด์ค€๋‹ค
  • (์ฒซ๋ฒˆ์งธ ์˜์ƒ ๊ฐœ์ˆ˜ + 1) X (๋‘๋ฒˆ์งธ ์˜์ƒ ๊ฐœ์ˆ˜ + 1) X โ€ฆ X (n๋ฒˆ์งธ ์˜์ƒ ๊ฐœ์ˆ˜ + 1) - 1

5. Map()์œผ๋กœ ์ข…๋ฅ˜๋ณ„ ์˜์ƒ ๊ฐœ์ˆ˜ ์ •๋ฆฌํ•˜๊ธฐ

  let hash = new Map();

  clothes.forEach(cloth => {
    hash.set(cloth[1], (hash.get(cloth[1]) | 0) + 1);
  })


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-07-08 ์ •ํ™•์„ฑ ํ†ต๊ณผ

function solution(clothes) {
  let sum = 1;

  let hash = new Map();
  clothes.forEach(cloth => {
    hash.set(cloth[1], (hash.get(cloth[1]) | 0) + 1);
  })

  for (let [key, val] of hash) {
    sum *= val + 1;
  }

  return sum - 1;
}

console.log(solution([["yellowhat", "headgear"], ["bluesunglasses", "eyewear"], ["green_turban", "headgear"]]))

โœ๏ธ๋ช…๋‹ต

Map ๋Œ€์‹  Object ์‚ฌ์šฉ

  • sum์„ ๊ตฌํ•  ๋•Œ๋„ object์—์„œ key๊ฐ’๋งŒ ๋ฐ›์•„์˜ด
function solution(clothes) {
  let sum = 1;

  let obj = {};
  clothes.forEach(cloth => {
    obj[cloth[1]] = (obj[cloth[1]] || 0) + 1;
  })

  for (let key in obj) {
    sum *= (obj[key] + 1);
  }

  return sum - 1;
}

Object.values()์™€ reduce() ์‚ฌ์šฉ

function solution(clothes) {
  return Object.values(
    clothes.reduce((obj, cloth) => {
      obj[cloth[1]] = (obj[cloth[1]] || 0) + 1;
      return obj;
    }, {})  // reduce์˜ ์ดˆ๊ธฐ๊ฐ’ : ๊ฐ์ฒด {}
  ).reduce((a, b) => a * (b + 1), 1) - 1;
}

console.log(solution([["yellowhat", "headgear"], ["bluesunglasses", "eyewear"], ["green_turban", "headgear"]]))
  • Object.values() : value๋งŒ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฐฐ์—ด์„ ๋ฆฌํ„ด, for โ€ฆ in ๊ตฌ๋ฌธ๊ณผ ๋™์ผํ•œ ์ˆœ์„œ
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));  // output: ["somestring", 42, false]