Where who wants to meet someone

그림 확대 본문

728x90

문제

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

내 답안 / 다른 사람들의 답안

import Foundation

func solution(_ picture:[String], _ k:Int) -> [String] {
    var multiplyPicture = [[String]]()

    picture.map { $0.map { String($0) } }.forEach { pixel in
        var newPixel = [String]()

        for i in pixel {
            for _ in 0..<k {
                newPixel.append(i)
            }
        }

        for _ in 0..<k {
            multiplyPicture.append(newPixel)
        }
    }

    return multiplyPicture.map { $0.joined() }
}

- 각 픽셀별로 배수만큼 더해주면 되겠다는 생각으로 진행

- picture.map 내에서 각 항목을 다시 map을 사용해서 String으로 타입캐스팅 해주었다. 이렇게 하면 기존 picture의 원소들이 각각의 String으로 쪼개진다.

- 이제 [String]이 [[String]]이 되었고, 각 [String]을 작업하기 위해서 forEach를 사용했으며 각각을 pixel이라 지칭

- 대체할 새로운 pixel인 newPixel 배열을 생성하고, 픽셀 내부 원소를 돌면서 배수만큼 newPixel에 더해준다.

- 위의 작업이 끝나면 pixel 하나에 대한 배수 작업이 끝났지만, 전체 그림 배수 작업을 위해서는 배수만큼의 pixel이 더 필요하기 때문에 다시 한 번 for문으로 배수만큼 최종 그림 배열인 multiplyPicture에 더해준다.

- 위 과정이 끝나면 [[String]]의 형태를 [String]으로 만들기 위해 multiplyPicture의 각 항목을 joined()로 묶어준다.

 

// 답안 1
import Foundation

func solution(_ picture:[String], _ k:Int) -> [String] {
    return picture.flatMap { Array(repeating: $0.map { String(repeating: $0, count: k) }.joined(), count: k) }
}

// 답안 2
import Foundation

func solution(_ picture:[String], _ k:Int) -> [String] {
    var li = picture.map { $0.map{String($0)} }

    for i in 0..<picture.count {
        li[i] = li[i].map { j in
            (0..<k).map { _ in j }.joined()
        }
    }

    var ans = [String]()
    for i in 0..<picture.count {
        for _ in 0..<k {
            ans.append(li[i].joined())
        }
    }

    return ans
}

 

 

점수: +1