포스트

153. 암호 해독


1
2
3
4
5
6
7
8
9
10
11
12
import Foundation

func solution(_ cipher:String, _ code:Int) -> String {
    
    var answer = ""
    var arr = cipher.map{String($0)}
    
    answer = stride(from:code-1, to:cipher.count, by: code).map{arr[$0]}.joined()
    print(answer)
    
    return ""
}

일정한 간격으로 출력해주기위해 전에썼던 stride를 이용하였다. 다만 그냥stride()만 하게되면 숫자를 간격으로 하기때문에. 이걸인덱스로 가져오기위해 map을 사용하였다.

다른코드

1
2
3
4
5
6
7
8
9
10
func solution(_ cipher: String, _ code: Int) -> String { 
(0..<cipher.count).filter { $0 % code == code - 1 }.map { String(Array(cipher)[$0]) }.joined(separator: "") 
}

//
import Foundation

func solution(_ cipher:String, _ code:Int) -> String {
    return cipher.enumerated().filter{ ($0.offset + 1) % code == 0 }.reduce("") { $0 + String($1.element) }
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.