๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค1๋‹จ๊ณ„ : ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ์ˆซ์ž ๋ฐฐ์—ด

by _ํ† ๋งคํ†  2022. 11. 21.
728x90

๐Ÿ–ฑ ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 1๋‹จ๊ณ„ : ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ์ˆซ์ž ๋ฐฐ์—ด ๐Ÿ–ฑ


๐Ÿ“– ๋ฌธ์ œ ์„ค๋ช… ๐Ÿ“–

array์˜ ๊ฐ element ์ค‘ divisor๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ๊ฐ’์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”. divisor๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” element๊ฐ€ ํ•˜๋‚˜๋„ ์—†๋‹ค๋ฉด ๋ฐฐ์—ด์— -1์„ ๋‹ด์•„ ๋ฐ˜ํ™˜ํ•˜์„ธ์š”.

๐Ÿงธ ์ œํ•œ ์‚ฌํ•ญ ๐Ÿงธ

arr์€ ์ž์—ฐ์ˆ˜๋ฅผ ๋‹ด์€ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
์ •์ˆ˜ i, j์— ๋Œ€ํ•ด i โ‰  j ์ด๋ฉด arr[i] โ‰  arr[j] ์ž…๋‹ˆ๋‹ค.
divisor๋Š” ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.
array๋Š” ๊ธธ์ด 1 ์ด์ƒ์ธ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.

function solution(arr, divisor) {
    let answer = [];
 
    for(let i=0; i<arr.length; i++) {
        if(arr[i] % divisor == 0) {
            answer.push(arr[i]);
        }
    }
    answer.sort(function(a, b) {
       return a - b;
    });
 
    if(answer.length == 0) {
        answer.push(-1);
    }
    return answer;
}

// sort() : ๋ฐฐ์—ด์˜ ์š”์†Œ๋ฅผ ์ ์ ˆํ•œ ์œ„์น˜์— ์ •๋ ฌํ•œ ํ›„ ๊ทธ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. a-b์ผ ๊ฒฝ์šฐ ์˜ค๋ฆ„์ฐจ์ˆœ(์ž‘์€์ˆ˜๋ถ€ํ„ฐ ์ •๋ ฌ)์œผ๋กœ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.
// arr = [5, 9, 7, 10] / divisor = 5์ผ ๋•Œ [5, 10]์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
// arr = [3,2,6]/ divisor = 10์ผ ๋•Œ [-1]์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

๐Ÿงธ ๋ฌธ์ œ ํ’€์ด ๐Ÿงธ

1. ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด arr์˜ ๊ธธ์ด๋งŒํผ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.
2. ์กฐ๊ฑด๋ฌธ์„ ํ†ตํ•ด ๋งŒ์•ฝ arr์˜ ๊ฐ ๊ฐ’์„ divisor๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‚˜๋จธ์ง€ ์—†์ด ๋”ฑ ๋–จ์–ด์ง„๋‹ค๋ฉด answer์— ๊ทธ ๊ฐ’์„ ํ‘ธ์‰ฌํ•ฉ๋‹ˆ๋‹ค.
3. ๊ทธ๋ฆฌ๊ณ  ๋ฐ˜๋ณต๋ฌธ์ด ๋๋‚˜๊ฒŒ ๋˜๋ฉด ํ‘ธ์‰ฌ๋œ ์ƒˆ๋กœ์šด ๊ฐ’๋“ค์„ sort๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋ฐฐ์—ด์„ ์ •๋ ฌ์‹œํ‚ค๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.
4. ๊ทธ๋ฆฌ๊ณ  ๋งŒ์•ฝ answer์— ์•„๋ฌด๋Ÿฐ ๊ฐ’์ด ํ‘ธ์‰ฌ๋˜์ง€ ์•Š์„ ๊ฒฝ์šฐ -1์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.


๐Ÿงธ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด ๐Ÿงธ

function solution(arr, divisor) {
    var answer = [];
    for(x of arr){
        (x % divisor == 0 ) ? answer.push(x) : null;
    }
    if(answer.length == 0) answer.push(-1)
    return answer.sort((a,b) => a - b);
  }

for of๋ฌธ๊ณผ ์กฐ๊ฑด์‚ผํ•ญ์ž, ์กฐ๊ฑด๋ฌธ์„ ์ ์ ˆํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜์—ฌ ์‹์„ ํ›จ์”ฌ ๊ฐ„ํŽธํ™”ํ–ˆ๋„ค์š”...

728x90

๋Œ“๊ธ€


Lucky Charms Rainbow
js
html
css