[Day02] 在PTT看到的排隊問題 - iT邦幫忙::IT知識分享社群
假設有一間超級好吃的麵包店,每次買東西都要排隊排很久,但是老闆又不願意大家一大早就來排隊。於是乎老闆就想出了一個方法,讓不是只有最前面的人才能買的到麵包,也不是排後面就一定買不到。
可以買到麵包的方式如下:
每個排隊的人都會有一個號碼牌,假設有 N 個人排隊,那麼號碼排就是從 1 一直到 N
接者會亂數取一個當作開始的號碼 s 和間隔的號碼 i 以及總共要可以買到麵包的人數 t
因此,就是有 N 個人在排隊,從號碼 s 開始算(含s)每隔 i 個人取一人,總共取 t 人
如果遇到最後,就再從頭算起
舉個例子來說:
有十個人在排隊 1 2 3 4 5 6 7 8 9 10
從第 2 個人開始每隔 4 個人取一人,共取 5 位。
則,選取到的幸運兒就是 [2 6 10 5 1]
https://github.com/Pajace/CodingPractice/blob/master/Leecodeoj/PeopleQueue.cs
Read full article from [Day02] 在PTT看到的排隊問題 - iT邦幫忙::IT知識分享社群
假設有一間超級好吃的麵包店,每次買東西都要排隊排很久,但是老闆又不願意大家一大早就來排隊。於是乎老闆就想出了一個方法,讓不是只有最前面的人才能買的到麵包,也不是排後面就一定買不到。
可以買到麵包的方式如下:
每個排隊的人都會有一個號碼牌,假設有 N 個人排隊,那麼號碼排就是從 1 一直到 N
接者會亂數取一個當作開始的號碼 s 和間隔的號碼 i 以及總共要可以買到麵包的人數 t
因此,就是有 N 個人在排隊,從號碼 s 開始算(含s)每隔 i 個人取一人,總共取 t 人
如果遇到最後,就再從頭算起
舉個例子來說:
有十個人在排隊 1 2 3 4 5 6 7 8 9 10
從第 2 個人開始每隔 4 個人取一人,共取 5 位。
則,選取到的幸運兒就是 [2 6 10 5 1]
https://github.com/Pajace/CodingPractice/blob/master/Leecodeoj/PeopleQueue.cs
| ||
| /// <param name="interval">間隔人數</param> | ||
| /// <param name="countOfSelected">總共選取人數</param> | ||
| /// <returns></returns> | ||
| public static int[] Select(int totalPerson, int startPerson, int interval, int countOfSelected) | ||
| { | ||
| List<int> personList = new List<int>(); | ||
| int[] selectedPerson = new int[countOfSelected]; | ||
| InitialPersonList(totalPerson, personList); | ||
| int selectedIndex = startPerson - 1; | ||
| for (int i = 0; i < countOfSelected; i++) | ||
| { | ||
| selectedPerson[i] = personList[selectedIndex]; | ||
| personList.RemoveAt(selectedIndex); | ||
| selectedIndex--; | ||
| selectedIndex = GetNextPersonIndex(interval, personList.Count, selectedIndex); | ||
| } | ||
| return selectedPerson; | ||
| } | ||
| private static int GetNextPersonIndex(int interval, int countOfPersonList, int currentSelectedIndex) | ||
| { | ||
| currentSelectedIndex += interval; | ||
| currentSelectedIndex %= countOfPersonList; | ||
| return currentSelectedIndex; | ||
| } | ||
| private static void InitialPersonList(int totalPerson, List<int> personList) | ||
| { | ||
| for (int i = 0; i < totalPerson; i++) | ||
| personList.Add((i + 1)); | ||
| } | ||
| } |