ํฌ๋ ˆ์ธ ์ธํ˜•๋ฝ‘๊ธฐ - ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Swift)

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

ํฌ๋ ˆ์ธ ์ธํ˜•๋ฝ‘๊ธฐ - ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

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

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

programmers.co.kr

 

 ๋‚˜์˜ ํ’€์ด

 

๋ฐ‘์—์„œ๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•˜๊ธฐ ์œ„ํ•ด stride๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค

๋‚ด ํ’€์ด์—์„œ๋Š” ๋จผ์ € ๊ฒฐ๊ณผ๋ฐฐ์—ด์— ๋„ฃ๊ณ  ์ค‘๋ณต๋˜๋ฉด ์ œ๊ฑฐํ•ด์„œ ํ•ด๊ฒฐํ–ˆ๋‹ค

import Foundation

func solution(_ board:[[Int]], _ moves:[Int]) -> Int {
    var results:[Int] = []
    var array = board
    var deleteObj = 0
    for num in moves {
        var maxIdx = 0
        var selectedVal = 0
        for i in stride(from: board.count-1, through: 0, by: -1) {
            if array[i][num-1] > 0 {
                maxIdx = i
                selectedVal = array[i][num-1]
            }
        }
        array[maxIdx][num-1] = 0
        if selectedVal > 0 {
            results.append(selectedVal)    
        }
        if results.count > 1 {
            if results[results.count-1] == results[results.count-2] {
                deleteObj += 2
                results.removeLast()
                results.removeLast()
            }
        }
    }
    return deleteObj
}

 

 

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

 

๊ฒฐ๊ณผ๋ฐฐ์—ด์— ๊ฐ’์„ ๋„ฃ๊ณ  ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๋‚ด ํ’€์ด์™€ ๋‹ฌ๋ฆฌ ๋„ฃ๊ธฐ ์ „์— ์ฒ˜๋ฆฌํ•จ์œผ๋กœ์จ ๋” ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์งค ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ๋‹ค.

๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•  ๋•Œ lastํ”„๋กœํผํ‹ฐ๋ฅผ ์ด์šฉํ•จ์œผ๋กœ์จ ๋งจ ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค์— ์‰ฝ๊ฒŒ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ–ˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ๋ฐฐ์—ด์„ ์œ„์—์„œ๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•˜๋˜ ๊ฐ’์ด ์žˆ์œผ๋ฉด breakํ•จ์œผ๋กœ์จ ์‹œ๊ฐ„์ด ๋œ ๊ฑธ๋ฆฌ๊ธฐ ๋•Œ๋ฌธ์— ๋” ์ข‹์€ ์ฝ”๋“œ์ธ ๊ฒƒ ๊ฐ™๋‹ค.

import Foundation

func solution(_ board:[[Int]], _ moves:[Int]) -> Int {
    var results:[Int] = []
    var array = board
    var deleteObj = 0
    for num in moves {
        for i in 0..<board.count {
            if array[i][num-1] > 0 {
                if results.last == array[i][num-1] {
                    deleteObj += 2
                    results.removeLast()
                } else {
                    results.append(array[i][num-1])
                }
                array[i][num-1] = 0
                break
            }
        }
    }
    return deleteObj
}