約瑟夫環(約瑟夫問題)是一個數學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數,數到m的那個人出列;他的下一個人又從1開始報數,數到m的那個人又出列;依此規律重複下去,直到圓桌周圍的人全部出列。如5個人,從編號為1的人開始報數,數到3的人出列,最後出列的人的編號為4。
編寫一個函式,總人數為50,從編號為1的人開始報數,數到3的人出列,計算出最後出列的人的編號。
NSUInteger printLastDequeuedNumberInRoundTable(NSUInteger allMembersCount, NSUInteger dequeueNumber) {
NSMutableDictionary<NSNumber *, NSString *> *dictM = @{}.mutableCopy;
NSUInteger startIdx = 1;//first idx is 1 in round table issue
//all members always dequeued finally
while (dictM.allKeys.count != allMembersCount) {
//members always sing from `1..dequeueNumber`
for (NSUInteger i = 1; i <= dequeueNumber; i++) {
//member at startIdx dequeued
if (dictM[@(startIdx)]) {
//ignore this, step next
i--;
} else {
if (i == dequeueNumber) {
//record every `round table number` when last member who sing `dequeueNumber`
dictM[@(startIdx)] = @"dequeued";
if (dictM.allKeys.count == allMembersCount) {
NSUInteger lastNum = (startIdx - 1)%allMembersCount + 1;
NSLog(@"last member at number %ld dequeued", lastNum);
return lastNum;
} else {
NSLog(@"member at number %ld dequeued", (startIdx - 1)%allMembersCount + 1);
}
}
}
++startIdx;
//the index in round table member varied from 1 to allMembersCount
startIdx = (startIdx - 1)%allMembersCount + 1;
}
}
return NSNotFound;
}
複製程式碼
結果
NSUInteger lastNumber = printLastDequeuedNumberInRoundTable(50, 3);
lastNumber = 11;
複製程式碼