https://programmers.co.kr/learn/courses/30/lessons/42587?language=swift
java로 풀었던 문제인데 하나도 기억이 안나서 30분간 고민하다가 결국 다른 사람의 코드를 참조하였다.
접근할 때 dictionary를 통해 index와 우선순위,출력순서를 할당하여 순서가 변할 때 마다 값을 변경하고 추적하려고 했으나 세가지의 요소를 어떻게 조합하여 추적할 지 막혀서 코드를 구현하는데 문제를 겪었다.
우선 매개변수로 전달된 값들은 상수형태이므로 값을 변화할 수 없으므로 새로운 변수에 할당해야 한다.
var priority = priorities
var nowIndex = location
var answer = 0
또한 변수 answer을 통해서 몇번째로 프린터되었는가를 추적하기 위한 변수를 선언했다.
while true {
if priority.first! == priority.max() {
priority.removeFirst()
answer += 1
if nowIndex == 0 {
break;
} else {
nowIndex -= 1
}
} else {
priority.append(priority.removeFirst())
if nowIndex == 0 {
nowIndex = priority.count-1
} else {
nowIndex -= 1
}
}
}
출력 순서를 구하는 코드이다.
1. 출력된 프린터가 우선순위가 제일 높은가를 확인
우선순위가 가장 높다면 출력, 아니라면 배열의 마지막으로
2. 우선순위가 가장 높다면
값을 제거하고 출력된 개수를 추적하는 변수 answer의 값을 +1
이때 내가 찾고자하는 location과 값이 동일하다면 ? return answer
찾고자하는 loaction이 아니라면 ? 대기번호가 하나 줄어들어서 nowIndex -= 1
3. 우선순위가 제일 높지 않다면
값을 제거하고 배열의 가장 마지막 자리에 append한다.
이러한 순서로 원하는 값이 출력될 때까지 반복문을 사용하면 된다.
값을 찾을 때 까지 계속 반복해야 하므로 for보다는 while이 적합하다
import Foundation
func solution(_ priorities:[Int], _ location:Int) -> Int {
var priority = priorities
var nowIndex = location
var answer = 0
while true {
if priority.first! == priority.max() {
priority.removeFirst()
answer += 1
if nowIndex == 0 {
break;
} else {
nowIndex -= 1
}
} else {
priority.append(priority.removeFirst())
if nowIndex == 0 {
nowIndex = priority.count-1
} else {
nowIndex -= 1
}
}
}
return answer
}