Archive/Questions

[programmers/Swift] 영어 끝말잇기

Marco 2022. 5. 31. 17:48
728x90

programmers.co.kr - 코딩테스트연습 - Lv.2 - Summer/Winter Coding(~2018) - 영어 끝말잇기

Constraints :

  • 끝말잇기에 참여하는 사람의 수 n은 2 이상 10 이하의 자연수입니다.
  • words는 끝말잇기에 사용한 단어들이 순서대로 들어있는 배열이며, 길이는 n 이상 100 이하입니다.
  • 단어의 길이는 2 이상 50 이하입니다.
  • 모든 단어는 알파벳 소문자로만 이루어져 있습니다.
  • 끝말잇기에 사용되는 단어의 뜻(의미)은 신경 쓰지 않으셔도 됩니다.
  • 정답은 [ 번호, 차례 ] 형태로 return 해주세요.
  • 만약 주어진 단어들로 탈락자가 생기지 않는다면, [0, 0]을 return 해주세요.

 

Solution.swift :

//
//  Created by Yongwoo Marco on 2022/04/15.
//  Copyright © 2022 Yongwoo Marco Kim. All rights reserved.
//

func solution(_ n:Int, _ words:[String]) -> [Int] {
    var check = [String]()
    
    for (index, word)  in words.enumerated() {
        if !check.isEmpty, check.contains(word) || check.last!.last! != word.first! {
            return [index%n + 1, index/n + 1]
        }
        check.append(word)
    }
    
    return [0, 0]
}

print(solution(3, ["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"]))   
// [3,3]
print(solution(5, ["hello", "observe", "effect", "take", "either", "recognize", "encourage", "ensure", "establish", "hang", "gather", "refer", "reference", "estimate", "executive"]))    
// [0,0]
print(solution(2, ["hello", "one", "even", "never", "now", "world", "draw"]))   
// [1,3]

How I tried this :
결과를 어떤 두 값을 출력하는지 헷갈려서 살짝 시간을 끌었다.

[틀린사람번호, 틀린사람의 몇번째 단어]

 

index를 이용해서 두 값을 모두 구했다.

3명이라고 가정하면 

0 1 2 (+1) -> 1 2 3 

 

총 5번째면

5/3 = 1 (+1) -> 2

1 : 1, 4

2: 2, 5

3: 3

 

형태로 두 값을 구했다.

 

if-else 겹치는 경우가 있기 때문에

check 배열이 채워진 경우에만 이미 나온 단어가 있는지 (1), 끝말잇기가 성립되지 않는지 (2)

체크해서 게임을 진행했다. 

 

문제에 관한 모든 저작권 : https://programmers.co.kr/

728x90