ํ‚คํŒจ๋“œ ๋ˆ„๋ฅด๊ธฐ - ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Swift)

2022. 10. 3. 16:35ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ‚คํŒจ๋“œ ๋ˆ„๋ฅด๊ธฐ - ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://school.programmers.co.kr/learn/courses/30/lessons/67256?language=swift 

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

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

 

ํ‚คํŒจ๋“œ๋ฅผ ์ขŒํ‘œ๊ฐ’์œผ๋กœ ๋†“๊ณ  ํ’€๊ณ ์žˆ๋Š”๋ฐ ๊ฐ’์ด ์…‹๋˜๋Š” ๋ถ€๋ถ„์„ ์ฒ˜๋ฆฌํ•˜์ง€ ๋ชปํ•ด์„œ ์ฐธ๊ณ ํ–ˆ๋‹ค.

 

https://jeong9216.tistory.com/222

 

[Swift ์•Œ๊ณ ๋ฆฌ์ฆ˜] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Lv.1) - ํ‚คํŒจ๋“œ ๋ˆ„๋ฅด๊ธฐ / 2020 ์นด์นด์˜ค ์ธํ„ด์‹ญ

์•ˆ๋…•ํ•˜์„ธ์š”. ๊ฐœ๋ฐœ ์ค‘์ธ ์ •์ฃผ์ž…๋‹ˆ๋‹ค. ์˜ค๋Š˜์€ ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํ‚คํŒจ๋“œ ๋ˆ„๋ฅด๊ธฐ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค. ๋ชฉ์ฐจ Github GitHub - jeongju9216/SwiftAlgorithm: ์Šค์œ„ํ”„ํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์Šค์œ„ํ”„ํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜. Contribute to jeongj..

jeong9216.tistory.com

 

๊ฐ™์€ ์ƒ๊ฐ์œผ๋กœ ์ ‘๊ทผํ–ˆ์ง€๋งŒ ๋‚˜๋Š” ํ•ด๊ฒฐํ•˜์ง€ ๋ชปํ–ˆ๊ธฐ์— ๊ตฌํ˜„๋Šฅ๋ ฅ์ด ์•„์ง ๋งŽ์ด ๋ถ€์กฑํ•œ ๊ฒƒ ๊ฐ™๋‹ค. (..๋…ธ๋ ฅํ•˜์ž!) 

 

import Foundation

func solution(_ numbers:[Int], _ hand:String) -> String {
    
    func setupCursor(_ num: Int) -> (Int, Int) {
        var cursor = (0, 0)
        switch num {
            case 0: cursor = (1, 0)
            case 1: cursor = (0, 3)
            case 2: cursor = (1, 3)
            case 3: cursor = (2, 3)
            case 4: cursor = (0, 2)
            case 5: cursor = (1, 2)
            case 6: cursor = (2, 2)
            case 7: cursor = (0, 1)
            case 8: cursor = (1, 1)
            case 9: cursor = (2, 1)
            default: break
        }
        return cursor
    } 
    
    func addString(_ num: Int, _ leftDistance: Int, _ rightDistance: Int) -> String {
        switch num {
            case 1, 4, 7: return "L"
            case 3, 6, 9: return "R"
            case 2, 5, 8, 0:
                if leftDistance > rightDistance {
                    return "R"
                } else if leftDistance < rightDistance {
                    return "L"
                } else {
                    return hand == "left" ? "L" : "R"
                }
            default: break
        }
        return ""
    }
    
    var leftCursor = (0, 0)
    var rightCursor = (2, 0)
    var result = ""
    for num in numbers {
        let cursor = setupCursor(num)      
        let leftDistance = abs(cursor.0-leftCursor.0) + abs(cursor.1-leftCursor.1)
        let rightDistance = abs(cursor.0-rightCursor.0) + abs(cursor.1-rightCursor.1)
        let str = addString(num, leftDistance, rightDistance)
        result += str
        if str == "L" {
            leftCursor = cursor
        } else {
            rightCursor = cursor
        }
    }
    
    return result
}