๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ–ฅ Computer Science/Algorithm

[Algorithm] ์ˆœ์—ด(Permutation)์ด๋ž€? (feat.Swift)

by Fomagran ๐Ÿ’ป 2021. 6. 27.
728x90
๋ฐ˜์‘ํ˜•

 

์•ˆ๋…•ํ•˜์„ธ์š” Foma ๐Ÿ‘Ÿ ์ž…๋‹ˆ๋‹ค!

 

์˜ค๋Š˜์€ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ์—์„œ ์ •๋ง ๋นˆ๋ฒˆํ•˜๊ฒŒ ์‚ฌ์šฉ๋˜๋Š” "์ˆœ์—ด"์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๋ฐ”๋กœ ์‹œ์ž‘ํ• ๊ฒŒ์š”!


์ˆœ์—ด์ด๋ž€?

 

์„œ๋กœ ๋‹ค๋ฅธ n๊ฐœ์˜ ์›์†Œ์—์„œ r๊ฐœ๋ฅผ ์ค‘๋ณต์—†์ด ๊ณจ๋ผ ์ˆœ์„œ์— ์ƒ๊ด€์žˆ๊ฒŒ ๋‚˜์—ดํ•˜๋Š” ๊ฒƒ์„ ์ด๋ฅธ๋‹ค. - ๋‚˜๋ฌด ์œ„ํ‚ค -

 

์‰ฝ๊ฒŒ ์„ค๋ช…ํ•˜๋ฉด ์ค„ ์„ธ์šฐ๊ธฐ์™€ ๋˜‘๊ฐ™์•„์š”.

 

A,B,C๋ผ๋Š” ํ•™์ƒ์„ ์ค„ ์„ธ์šฐ๋Š” ๋ฐฉ๋ฒ•์€ ABC,ACB,BAC,BCA,CAB,CBA ๋“ฑ์ด ์žˆ๊ฒ ์ฃ ?

 

์ด ์ค‘์—์„œ 2๋ช…์˜ ํ•™์ƒ์œผ๋กœ ์ค„ ์„ธ์šฐ๋Š” ๋ฐฉ๋ฒ•์€ AB,AC,BA,BC,CA,CB ๋“ฑ์ด ์žˆ์„๊ฑฐ์—์š”.


์ฝ”๋“œ ๊ตฌํ˜„

 

๊ฒฝ์šฐ์˜ ์ˆ˜๋“ค์„ ๋‹ด์„ ์ด์ค‘ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค.

 

var cases:[[Int]] = []

 

๋ช‡ ๊ฐœ๋ฅผ ๋ฝ‘์„์ง€ ์ •ํ•ด์ค๋‹ˆ๋‹ค.

 

let pickCount = 3

 

๋ณธ๊ฒฉ์ ์œผ๋กœ ์ˆœ์—ด ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค.

 

ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ๋Š”

 

์ „์ฒด ์ธ๋ฑ์Šค๊ฐ€ ๋‹ด๊ธด numbers

 

ํ˜„์žฌ ์ธ๋ฑ์Šค๋ฅผ ๋‚˜ํƒ€๋‚ผ current

 

๋ช‡๊ฐœ๋ฅผ ๋ฝ‘์•„์•ผ ํ• ์ง€๋ฅผ ์ •ํ•  pickCount

 

๋ฐฉ๋ฌธ์—ฌ๋ถ€๋ฅผ ๋‚˜ํƒ€๋‚ผ visited

 

๋ฝ‘์€ ์ธ๋ฑ์Šค๋ฅผ ๋‹ด์„ picked ๋กœ ์„ค์ •ํ•ด์ค๋‹ˆ๋‹ค.

 

func permutaion(indexes:[Int],current:Int,pickCount:Int,visited:[Bool],picked:[Int]) {...}

 

๊ทธ๋ฆฌ๊ณค ์ดˆ๊ธฐ ๋ฐฉ๋ฌธ์ด ๋น„์–ด์žˆ๋‹ค๋ฉด ์ธ๋ฑ์Šค์˜ ๊ฐฏ์ˆ˜๋งŒํผ ์ดˆ๊ธฐ ๋ฐฉ๋ฌธ์„ ์„ค์ •ํ•ด์ค๋‹ˆ๋‹ค.

 

let initialVisited = visited.isEmpty ? Array(repeating: false, count: indexes.count) : visited

 

๋งŒ์•ฝ ํ˜„์žฌ ์ธ๋ฑ์Šค๊ฐ€ pickCount๋ผ๋ฉด cases์— ๋‹ด๊ณ  return ํ•ด์ค๋‹ˆ๋‹ค.

 

 if current == pickCount {
        cases.append(picked)
        return
    }

 

๋งŒ์•ฝ ์ธ๋ฑ์Šค๊ฐ€ pickCount ์ „์ด๋ผ๋ฉด

 

indexes๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ ๋ฐฉ๋ฌธํ–ˆ๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•ด์„œ

 

๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด ๋ฐฉ๋ฌธ์„ ์ฒดํฌํ•˜๊ณ  ์ƒˆ๋กœ์šด ์ธ๋ฑ์Šค๋ฅผ ๋„ฃ๊ณ  ํ˜„์žฌ ์ธ๋ฑ์Šค์— + 1 ํ•ด์ฃผ๊ณ 

 

์žฌ๊ท€ํ•˜์—ฌ ์ค๋‹ˆ๋‹ค.

 

 indexes
        .enumerated()
        .forEach{
            if !initialVisited[$0.offset] {
                var newVisited = initialVisited
                newVisited[$0.offset] = true
                var newPicked = picked
                newPicked.append($0.element)
                permutaion(indexes: indexes, current: current+1, pickCount: pickCount,visited: newVisited,picked: newPicked)
            }
        }

 

์•„๋ž˜์™€ ๊ฐ™์ด ์›ํ•˜๋Š” ์กฐ๊ฑด์„ ๋„ฃ๊ณ  ๊ฒฝ์šฐ์˜ ์ˆ˜๋“ค์„ ์ถœ๋ ฅํ•ด๋ณด๋ฉด ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ๋‹ด๊ธด ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

permutaion(indexes: [1,2,3], current: 0,pickCount: 2,visited:[],picked: [])
print(cases)

//[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

์ „์ฒด ์†Œ์Šค ์ฝ”๋“œ

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€