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

Algorithm/Programmers

[Programmers] ์นดํŽซ

 

 

๋ฌธ์ œ 

 

Leo๋Š” ์นดํŽซ์„ ์‚ฌ๋Ÿฌ ๊ฐ”๋‹ค๊ฐ€ ์•„๋ž˜ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ์ค‘์•™์—๋Š” ๋…ธ๋ž€์ƒ‰์œผ๋กœ ์น ํ•ด์ ธ ์žˆ๊ณ  ํ…Œ๋‘๋ฆฌ 1์ค„์€ ๊ฐˆ์ƒ‰์œผ๋กœ ์น ํ•ด์ ธ ์žˆ๋Š” ๊ฒฉ์ž ๋ชจ์–‘ ์นดํŽซ์„ ๋ดค์Šต๋‹ˆ๋‹ค.

 

Leo๋Š” ์ง‘์œผ๋กœ ๋Œ์•„์™€์„œ ์•„๊นŒ ๋ณธ ์นดํŽซ์˜ ๋…ธ๋ž€์ƒ‰๊ณผ ๊ฐˆ์ƒ‰์œผ๋กœ ์ƒ‰์น ๋œ ๊ฒฉ์ž์˜ ๊ฐœ์ˆ˜๋Š” ๊ธฐ์–ตํ–ˆ์ง€๋งŒ, ์ „์ฒด ์นดํŽซ์˜ ํฌ๊ธฐ๋Š” ๊ธฐ์–ตํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.

Leo๊ฐ€ ๋ณธ ์นดํŽซ์—์„œ ๊ฐˆ์ƒ‰ ๊ฒฉ์ž์˜ ์ˆ˜ brown, ๋…ธ๋ž€์ƒ‰ ๊ฒฉ์ž์˜ ์ˆ˜ yellow๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ ์นดํŽซ์˜ ๊ฐ€๋กœ, ์„ธ๋กœ ํฌ๊ธฐ๋ฅผ ์ˆœ์„œ๋Œ€๋กœ ๋ฐฐ์—ด์— ๋‹ด์•„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

 

 

์ œํ•œ ์‚ฌํ•ญ
  • ๊ฐˆ์ƒ‰ ๊ฒฉ์ž์˜ ์ˆ˜ brown์€ 8 ์ด์ƒ 5,000 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.
  • ๋…ธ๋ž€์ƒ‰ ๊ฒฉ์ž์˜ ์ˆ˜ yellow๋Š” 1 ์ด์ƒ 2,000,000 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.
  • ์นดํŽซ์˜ ๊ฐ€๋กœ ๊ธธ์ด๋Š” ์„ธ๋กœ ๊ธธ์ด์™€ ๊ฐ™๊ฑฐ๋‚˜, ์„ธ๋กœ ๊ธธ์ด๋ณด๋‹ค ๊น๋‹ˆ๋‹ค.

 

๋‚˜์˜ ์ฝ”๋“œ 
def solution(brown, yellow):
    # a์™€ b์˜ ์กฐ๊ฑด (a = ๊ฐ€๋กœ, b = ์„ธ๋กœ)
    # yellow = (a - 2) * (b - 2)
    # total = a * b
    total = brown + yellow
    array = [] # ๊ฐ€๋กœ x ์„ธ๋กœ๊ฐ€ ๋  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜ ๋ชจ์Œ
    for i in range(total):
        if i > 0:
            if total % i == 0:
                array.append(i)
                if i * i == total:
                    array.append(i)
    print(array)
    
    # ๊ทธ์ค‘์—์„œ ๋‘๊ฐ€์ง€ ์กฐ๊ฑด์„ ์ถฉ์กฑํ•˜๋Š” ๊ฐ€๋กœ, ์„ธ๋กœ ๊ธธ์ด ๊ตฌํ•˜๊ธฐ
    for p in range(len(array)):
        for t in range(p+1,len(array)):
            if array[p] * array[t] == total:
                if (array[p] - 2) * (array[t] - 2) == yellow:
                    answer = [array[p],array[t]]
                    answer.sort(reverse=True)
                    return answer
๋ถ„์„ > ์šฐ์„  ์ „์ฒด ๊ฒฉ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ํ† ๋Œ€๋กœ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” (๊ฐ€๋กœ x ์„ธ๋กœ) ์Œ์„ ๊ตฌํ•ด array์— append ํ•˜์˜€๋‹ค. ๊ทธ ํ›„ ๋‘ ๊ฐ€์ง€ ์กฐ๊ฑด์„ ์ถฉ์กฑํ•˜๋Š” (๊ฐ€๋กœ x ์„ธ๋กœ) ์Œ์„ ๊ตฌํ•ด ๋ฐ˜ํ™˜ํ•ด์ฃผ์—ˆ๋‹ค. 

 

ํšจ์œจ์ ์ธ ์ฝ”๋“œ 
def solution(brown, yellow):
    total = brown + yellow
    for n in range(1, total+1):
        if total%n != 0:
            continue
        m = total//n
        if (n-2)*(m-2) == yellow:
            return sorted([n, m], reverse = True)
๋ถ„์„ > ์ „์ฒด์ ์ธ ํ๋ฆ„ ์ž์ฒด๋Š” ๋‚ด๊ฐ€ ์ง  ์ฝ”๋“œ์™€ ํฌ๊ฒŒ ๋‹ค๋ฅด์ง€ ์•Š์•˜๋‹ค. ๋‹ค๋งŒ ๋‚˜๋Š” ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  (๊ฐ€๋กœ x ์„ธ๋กœ) ์Œ์„ ๋ชจ๋‘ ๊ตฌํ•ด์ฃผ์—ˆ๋Š”๋ฐ, ์ด ์ฝ”๋“œ๋Š” continue๋ฅผ ์‚ฌ์šฉํ•ด ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰์— ์ž…๋ ฅ๋œ n๊ฐ’์„ ๊ธฐ๋ฐ˜์œผ๋กœ m์„ ๊ตฌํ•ด์ฃผ์—ˆ๊ณ  ์ด ๋‘ ๊ฐ’์ด ์กฐ๊ฑด์„ ์ถฉ์กฑํ•˜๋ฉด ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ „๊ฐœํ•˜์˜€๋‹ค. ์ด๋ ‡๊ฒŒ ๊ตณ์ด ํ•„์š”ํ•˜์ง€ ์•Š๋Š” ๋ถ€๋ถ„์€ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•˜๊ณ . ์ตœ๋Œ€ํ•œ ํšจ์œจ์ ์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์งœ๋Š” ๋ฒ•์„ ํ•™์Šตํ•  ํ•„์š”์„ฑ์„ ๋Š๊ผˆ๋‹ค.