Jieunny์˜ ๋ธ”๋กœ๊ทธ

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์—ฐ์†๋œ ์ˆ˜์˜ ํ•ฉ ๋ณธ๋ฌธ

Study/Coding Test

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์—ฐ์†๋œ ์ˆ˜์˜ ํ•ฉ

Jieunny 2023. 2. 3. 15:46

๐Ÿ“Œ  ๋ฌธ์ œ

์—ฐ์†๋œ ์„ธ ๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ๋”ํ•ด 12๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ๋Š” 3, 4, 5์ž…๋‹ˆ๋‹ค. ๋‘ ์ •์ˆ˜ num๊ณผ total์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์—ฐ์†๋œ ์ˆ˜ num๊ฐœ๋ฅผ ๋”ํ•œ ๊ฐ’์ด total์ด ๋  ๋•Œ, ์ •์ˆ˜ ๋ฐฐ์—ด์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋‹ด์•„ returnํ•˜๋„๋ก solutionํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด๋ณด์„ธ์š”.


์ œํ•œ์‚ฌํ•ญ

  • 1 ≤ num ≤ 100
  • 0 ≤ total ≤ 1000
  • num๊ฐœ์˜ ์—ฐ์†๋œ ์ˆ˜๋ฅผ ๋”ํ•˜์—ฌ total์ด ๋  ์ˆ˜ ์—†๋Š” ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ์—†์Šต๋‹ˆ๋‹ค.

 

๐Ÿ’ก  ์•„์ด๋””์–ด

num์ด ์ง์ˆ˜๋ฉด, total์„ num์œผ๋กœ ๋‚˜๋ˆˆ ๊ฐ’์ด ์—ฐ์†๋œ ์ˆ˜๋ฅผ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆˆ ๋ฐ”๋กœ ์•ž์˜ ๊ฐ’์ด ๋œ๋‹ค.

num=6, total=21์ด๋ฉด (1, 2, 3, 4, 5, 6) ์—ฌ๊ธฐ์„œ 3์ด๋˜๋Š” ๊ฒƒ

num์ด ํ™€์ˆ˜๋ฉด, total์„ num์œผ๋กœ ๋‚˜๋ˆˆ ๊ฐ’(๋‚˜๋จธ์ง€ ๋ฒ„๋ฆฌ๊ณ )์ด ์—ฐ์†๋œ ์ˆ˜์˜ ์ค‘๊ฐ„ ๊ฐ’์ด ๋œ๋‹ค.

์ด๋ฅผ ์ด์šฉํ•ด์„œ middle์„ ๊ตฌํ•ด๋†“๊ณ , for๋ฌธ์„ ์–ด๋””์„œ๋ถ€ํ„ฐ ์–ด๋””๊นŒ์ง€ ๋Œ๋ฆด์ง€ ์ƒ๊ฐํ•ด๋ณธ๋‹ค.

 

โœ๏ธ  ํ’€์ด

function solution(num, total) {
  var answer = [];

  if(num % 2 === 0){
    let middle = Math.floor(total / num);
    let from = middle - (num/2 - 1);	// ์ฒซ๋ฒˆ์งธ ์ˆ˜๋Š” num์„ 2๋กœ ๋‚˜๋ˆ„๊ณ , 1์„ ๋บ€ ๊ฐ’์„ middle์—์„œ ๋บ€ ๊ฐ’
    let to = middle + (num/2);	// ๋งˆ์ง€๋ง‰ ์ˆ˜๋Š” middle์— num/2ํ•œ ๊ฐ’์„ ๋”ํ•œ ๊ฐ’
    for(let i=from; i<=to; i++){
      answer.push(i);
    }
  }
  else{
    let middle = Math.floor(total / num);
    let from = middle - (Math.floor(num/2));
    let to = middle + (Math.floor(num/2));
    for(let i=from; i<=to; i++){
      answer.push(i);
    }
  }

  return answer;
}