Created
December 21, 2023 04:08
-
-
Save happyduck-git/d3f482b3c76df5e7981df3997c4f5f98 to your computer and use it in GitHub Desktop.
Ladder Game Solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Personal solution for an algorithm practice | |
import Foundation | |
func solution(_ n: Int, _ ladder: [[Int]]) -> [String] { | |
var boolLadder = Array(repeating: Array(repeating: false, count: n), | |
count: ladder.count) | |
let start = UnicodeScalar("A").value | |
let end = UnicodeScalar("Z").value | |
var alphabetArr = Array(repeating: "", count: Int(end - start) + 1) | |
for i in 0..<alphabetArr.count { | |
alphabetArr[i] = String(UnicodeScalar(i + Int(start))!) | |
} | |
// 1. 옆으로 지나가는 막대가 있는 경우 true 표시 | |
for i in 0..<ladder.count { | |
for j in ladder[i] { | |
boolLadder[i][j-1] = true | |
} | |
} | |
// 2. 사다리 타기 및 위치 반환하기 | |
var finalLocation: [String] = Array(repeating: "", count: n) // 학생 수와 동일한 크기의 String array 생성 | |
for studentIndex in 0..<n { | |
var currentIndex = studentIndex | |
for row in 0..<boolLadder.count { | |
if boolLadder[row][currentIndex] { | |
currentIndex += 1 | |
} else if !(currentIndex - 1 < 0) && boolLadder[row][currentIndex - 1] { | |
currentIndex -= 1 | |
} | |
} | |
finalLocation[currentIndex] = alphabetArr[studentIndex] | |
} | |
return finalLocation | |
} | |
print(solution(5, [[1,3], [2,4], [1,4]])) | |
print(solution(7, [[1,3,5], [1,3,6], [2,4]])) | |
print(solution(8, [[1,5], [2,4,7], [1,5,7], [2,5,7]])) | |
print(solution(12, [[1,5,8,10], [2,4,7], [1,5,7,9,11], [2,5,7,10], [3,6,8,11]])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment