๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] Swift 2020 ์นด์นด์˜ค ์ธํ„ด์‹ญ ํ‚คํŒจ๋“œ ๋ˆ„๋ฅด๊ธฐ

by Jouureee 2022. 4. 8.

๋ฌธ์ œ :

https://programmers.co.kr/learn/courses/30/lessons/67256

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํ‚คํŒจ๋“œ ๋ˆ„๋ฅด๊ธฐ

[1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] "right" "LRLLLRLLRRL" [7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2] "left" "LRLLRRLLLRR" [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] "right" "LLRLLRLLRL"

programmers.co.kr

 

๋‚œ์ด๋„ level 1

 

๋ถ„์„ :

๊ฐ„๋‹จํ•œ ๊ตฌํ˜„ ๋ฌธ์ œ์˜€๋‹ค !

1, 4, 7๋ฒˆ์€ ์™ผ์†์œผ๋กœ 3, 6, 9๋ฒˆ์€ ์˜ค๋ฅธ์†์œผ๋กœ ๋ˆ„๋ฅด๊ณ  2, 5, 8, 0 ์ˆซ์ž๋Š” ํ˜„์žฌ ์žˆ๋Š” ์† ์œ„์น˜์—์„œ ๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ€๊นŒ์šด ์†์ด ๋ˆ„๋ฅด๋Š” ๊ตฌํ˜„ ๋ฌธ์ œ์˜€๋‹ค.

์ˆซ์ž๊ฐ€ ํ–‰๋ผ๋ฆฐ 3๋งŒํผ ์ฐจ์ด๊ฐ€ ๋‚˜๊ธฐ ๋•Œ๋ฌธ์— ์—ด๋ผ๋ฆฐ 1๋งŒํผ ์ฐจ์ด๊ฐ€ ๋‚˜๊ธฐ ๋•Œ๋ฌธ์— 

์œ„์น˜ ๊ฐ’์„ /, %๋กœ ํŒŒ์•… ํ•  ์ˆ˜ ์žˆ๋‹ค. 

์ด๋•Œ ํ˜„์žฌ ์† ์œ„์น˜๋Š” left = 10 (*), right = 12(#)๋กœ, 0๋ฒˆ = 11๋กœ ์ดˆ๊ธฐํ™” ํ•ด์ค€๋‹ค.

answer์— ๋ฌธ์ž์—ด์„ ๋ง๋ถ™์—ฌ์ค„๋•Œ๋งˆ๋‹ค left, right ์† ์œ„์น˜ (now_leftPosition, now_rightPosition)์„ ์—…๋ฐ์ดํŠธ ํ•ด์ค€๋‹ค.

 

swift ์ฝ”๋“œ :

//
//  main.swift
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2022/04/08.
//

import Foundation
var leftSet:Set = Set([1, 4, 7])
var rightSet: Set = Set([3, 6, 9])

var answer: String = ""
var now_leftPosition = 10 //*
var now_rightPosition = 12 //#

func solution(_ numbers:[Int], _ hand:String) -> String {
    for i in numbers {
        var target = i
        if(i == 0) { target = 11 } // ๊ณ„์‚ฐ์„ ์œ„ํ•ด 12๋กœ ์น˜ํ™˜
        if leftSet.contains(target) {
            answer += "L"
            now_leftPosition = target
        }else if rightSet.contains(target) {
            answer += "R"
            now_rightPosition = i
        }else { // 2, 5, 8 ,0 ๊ฑฐ๋ฆฌ ๊ณ„์‚ฐ
            let tempLeft = abs(now_leftPosition - target)
            let tempRight = abs(now_rightPosition - target)
            
            let distLeft = tempLeft / 3 + tempLeft % 3
            let distRight = tempRight / 3 + tempRight % 3
            if(distLeft < distRight){
                answer += "L"
                now_leftPosition = target
            }else if(distLeft > distRight) {
                answer += "R"
                now_rightPosition = target
            }else { // ๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ™์„ ๋•Œ
                if(hand == "right"){
                    answer += "R"
                    now_rightPosition = target
                }else {
                    answer += "L"
                    now_leftPosition = target
                }
            }
        }
    }
    return answer
}

๋Œ“๊ธ€