๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

57๋ฒˆ. ์ค‘๋ณต ๋‹จ์–ด ์ œ๊ฑฐ - ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” ํ•จ์ˆ˜ Set

 

๋ฌธ์ œ 

 

์ค‘๋ณต ๋‹จ์–ด๋ฅผ ์ œ๊ฑฐํ•ด์ฃผ๋Š” ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•˜์‹œ์˜ค. ์ž…๋ ฅ๊ฐ’์€ ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ ์š”์†Œ๋“ค์€ ๋ฌธ์žํ˜•์ด ์ž…๋ ฅ๋˜๊ณ , ์ค‘๋ณต ๋‹จ์–ด๊ฐ€ ์ œ๊ฑฐ๋œ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. 

 

์ž…๋ ฅ๊ฐ’  ์ถœ๋ ฅ๊ฐ’
["john", "alice", "alice"] ['john', 'alice']
["Hello", "hello", "Hello", "hello"] ['Hello', 'hello', 'HELLO']
["kiwi", "banana", "mango", "kiwi", "banana"] ['kiwi', 'banana', 'mango']

 

 

(1) ๋‚˜์˜ ์ ‘๊ทผ ๋ฐฉ๋ฒ•

 

1. ๋ฐฐ์—ด์„ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พผ๋‹ค.

2. ๋ฌธ์ž์—ด์˜ ๋ชจ๋“  ์š”์†Œ๋“ค์„ ์†Œ๋ฌธ์ž๋กœ ๋ฐ”๊พผ๋‹ค. 

3. ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ ค์„œ ์ค‘๋ณต ๋‹จ์–ด๊ฐ€ ๋‚˜์˜ค๋Š” ๊ฒฝ์šฐ, ๋’ค์— ๋‚˜์˜จ ๋‹จ์–ด๋ฅผ ์ œ๊ฑฐํ•œ๋‹ค. 

4. new_arr์— ๊ธฐ์กด arr๊ฐ’์„ pushํ•œ๋‹ค. 

 

 

(2) ๋ชจ๋ฒ” ์ฝ”๋“œ  ๋ฐ ์ ‘๊ทผ ๋ฐฉ๋ฒ• 

 

1. Set ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ํ•œ๋ฒˆ์— ์ค‘๋ณต๊ฐ’์„ ์ •๋ฆฌํ•œ๋‹ค.

function answer(arr) {
  let new_arr = [];

  new_arr = Array.from(new Set(arr));

  return new_arr;
}

 

 

(3) ๋ฌธ์ œ๋ฅผ ํšจ์œจ์ ์œผ๋กœ ํ’€์ง€ ๋ชปํ–ˆ๋˜ ์ด์œ 

 

โ—  Set ํ•จ์ˆ˜๋ฅผ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด์„œ ์ „ํ˜€ ๋– ์˜ฌ๋ฆฌ์ง€ ๋ชปํ–ˆ๊ณ , Set ํ•จ์ˆ˜์— ๋Œ€ํ•œ ๊ฐœ๋…์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์•˜๋‹ค. ๊ทธ๋ž˜์„œ ๋‹จ์ˆœํ•˜๊ฒŒ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋ คํ–ˆ๋‹ค. 

 

 

ํ•ด๊ฒฐ ๋ฐฉ์•ˆ

 

(1) Set ํ•จ์ˆ˜ ๋ฐ Array.from์— ๋Œ€ํ•œ ๊ฐœ๋… ์ดํ•ด  - ๊ฐ•์˜ Set ํ•จ์ˆ˜ ๋ถ€๋ถ„ ๋‹ค์‹œ ์ฒญ์ทจ (38. Set)

 

  โ€ป Set 

     - value ๋งŒ์„ ์ €์žฅํ•˜๋ฉฐ ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” Collection 

     - Set.has(i) : Set ์•ˆ์— i ์š”์†Œ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ

     - Set.delete(i) : Set ์—์„œ i ์š”์†Œ๋ฅผ ์‚ญ์ œ

let set = new Set(); // output: Set(0) {}
let num = new Set([1, 2, 3, 4, 5]); // output: Set(5) { 1, 2, 3, 4, 5 }
let str = new Set("Hello!"); // output: Set(5) { 'H', 'e', 'l', 'o', '!' }

 

  โ€ป Array.from

     - ์œ ์‚ฌ ๋ฐฐ์—ด ๊ฐ์ฒด๋‚˜ ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด๋ฅผ ์–•๊ฒŒ ๋ณต์‚ฌํ•ด ์ƒˆ๋กœ์šดArray ๊ฐ์ฒด๋ฅผ ๋งŒ๋“œ๋Š” ๋ฉ”์„œ๋“œ. 

let friends = ['Tom', 'Jim', 'Kevin', 'Tom']
set = new Set (Array.from(friends)); // output: Set(3) { 'Tom', 'Jim', 'Kevin' }

 

 

(2) ๋ชจ๋ฒ” ์ฝ”๋“œ์— ๋Œ€ํ•œ ์ดํ•ด 

function answer(arr) {
  let new_arr = [];

  new_arr = Array.from(new Set(arr));

  return new_arr;
}

  : Set ๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•ด, ๊ธฐ์กด arr ๋ฐฐ์—ด๋กœ ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” ์ƒˆ๋กœ์šด Collection Set ์„ ํ˜•์„ฑํ•œ ํ›„ Array.from์„ ์ด์šฉํ•ด ์ƒˆ๋กœ์šด Array ๊ฐ์ฒด์ธ new_arr ๋ฅผ ํ˜•์„ฑํ•œ๋‹ค.