let's get IT with DAVINA ๐Ÿ’ป

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] Lv0. ์ง„๋ฃŒ ์ˆœ์„œ ์ •ํ•˜๊ธฐ ๋ณธ๋ฌธ

DEV_IN/๋ฌธ์ œํ’€์ด

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] Lv0. ์ง„๋ฃŒ ์ˆœ์„œ ์ •ํ•˜๊ธฐ

๋‹ค๋นˆ์น˜์ฝ”๋“œ๐Ÿ’Ž 2023. 3. 15. 15:11

โ“ ๋ฌธ์ œ ์„ค๋ช…

์™ธ๊ณผ์˜์‚ฌ ๋จธ์“ฑ์ด๋Š” ์‘๊ธ‰์‹ค์— ์˜จ ํ™˜์ž์˜ ์‘๊ธ‰๋„๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ง„๋ฃŒ ์ˆœ์„œ๋ฅผ ์ •ํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์ •์ˆ˜ ๋ฐฐ์—ด emergency๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ ์‘๊ธ‰๋„๊ฐ€ ๋†’์€ ์ˆœ์„œ๋Œ€๋กœ ์ง„๋ฃŒ ์ˆœ์„œ๋ฅผ ์ •ํ•œ ๋ฐฐ์—ด์„ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

๐Ÿšซ ์ œํ•œ์‚ฌํ•ญ

  • ์ค‘๋ณต๋œ ์›์†Œ๋Š” ์—†์Šต๋‹ˆ๋‹ค. 
  • 1 ≤ emergency์˜ ๊ธธ์ด ≤ 10
  • 1 ≤ emergency์˜ ์›์†Œ ≤ 100

๐Ÿ—๏ธ ์ž…์ถœ๋ ฅ ์˜ˆ

emergency result
[3, 76, 24] [3, 1, 2]
[1, 2, 3, 4, 5, 6, 7] [7, 6, 5, 4, 3, 2, 1]
[30, 10, 23, 6, 100] [2, 4, 3, 5, 1]

โ—๏ธ ๋น„๋‹ˆ's ํ’€์ด

๋ถ„๋ช… ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ๋ฐฐ์—ด์„ ์ •๋ ฌํ•ด๋ณธ๋’ค, ์›์†Œ์˜ index๊ฐ’์„ ์ฐพ์•„์„œ ์กฐ์ ˆํ•˜๋Š” ๋กœ์ง์€ ๋งž๋Š”๋ฐ ์ž๊พธ ํ…Œ์ŠคํŠธ ํ†ต๊ณผ๊ฐ€ ์•ˆ๋˜์–ด์„œ ๋ญ๊ฐ€ ๋ฌธ์  ์ง€ ์ฝ”๋“œ ํ•œ์ค„ํ•œ์ค„์„ ์‹คํ–‰ํ•ด๋ณธ ๊ฒฐ๊ณผ, sortedArr๋ฅผ ์ฒ˜์Œ์— emergency.sort()๋ฅผ ํ•˜์—ฌ์„œ emergency(์›๋ณธ ๋ฐฐ์—ด) ์ž์ฒด๊ฐ€ ๋ณ€ํ•ด๋ฒ„๋ฆฐ ์ด์œ ์˜€๋‹ค..

๊ทธ๋ž˜์„œ ์›๋ณธ ๋ฐฐ์—ด์„ ๊ฑด๋“ค์ง€ ์•Š๊ธฐ ์œ„ํ•ด spread์—ฐ์‚ฐ์ž๋กœ ๋‹ค์‹œ ์ •๋ ฌ์„ ์‹œ์ผœ์„œ ๋น„๊ตํ•˜์˜€๋‹ค! 

function solution(emergency) { //[3,76,24]
    let sortedArr=[...emergency].sort((a,b)=>b-a); //[76,24,3]
    for(let i=0;i<emergency.length;i++){
        for(let j=0;j<sortedArr.length;j++){
            if(emergency[i]===sortedArr[j]){
                emergency[i]=j+1;
                break;
            }
            continue;
        }
    }
    return emergency;
}

๐Ÿ‘€ others' ํ’€์ด

map์„ ์จ์„œ ๋ฐฐ์—ด์„ ๋‹ค์‹œ ์ƒˆ๋กญ๊ฒŒ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์€ ์ƒ๊ฐ์„ ๋ชปํ•˜๊ณ  ์ด์ค‘ for๋ฌธ๋ฐ–์— ๋– ์˜ฌ๋ฆฌ์ง€ ๋ชปํ–ˆ์—ˆ๋‹ค.. ์ด ๋ฐฉ๋ฒ•์€ ์ฝ”๋“œ๋„ ํ›จ์”ฌ ๊ฐ„๊ฒฐํ•˜๊ณ  ์‹ ๋ฐ•ํ–ˆ๋˜๊ฒƒ๊ฐ™๋‹ค.

const solution = (emergency) => {
    const sorted = [...emergency].sort((a, b) => b - a)
    return emergency.map(el => sorted.indexOf(el) + 1)
}

⊕ Extra Knowledge ++

js array.sort()๋Š” ์›๋ณธ ๋ฐฐ์—ด์„ ๋ฐ”๊พผ๋‹ค!
// ์›๋ณธ์ธ arr ์ด ์ •๋ ฌ๋จ
{
  const arr = [1, 2, 3];
  const sortedArr = arr.sort((a, b) => b - a);
  console.log(arr === sortedArr); // true
}

// ์›๋ณธ์ธ arr๋ฅผ ์‚ด๋ฆฌ๋ฉด์„œ ์ •๋ ฌ๋œ ์ƒˆ ๋ฐฐ์—ด ์–ป๊ธฐ
{
  const arr = [1, 2, 3];
  const sortedArr = [...arr].sort((a, b) => b - a);
  console.log(arr === sortedArr); // false
}
Comments