Linear table Applications
Solution to the problem of--josephus (Python version)
Josephus problem Description: Suppose that there are n people sitting around a circle, now request from the K -person began to count off, the number of people reporting on the exit. Then from the next person start the count and follow the same rules to exit until everyone quits. the number of each dequeue is required to be lost sequentially.
- Solution based on Array concept
1. Create a table with n individuals
2. Find the K-Man and start there
3. The process of using the corresponding element modified to 0 means that has exited, repeated:
4. A few m (still sitting) person, encounter the end of the table turn back to subscript 0 continue
4. Change the table element representing the M person to 0
5. N individual out of the end
1 defJosephus (n,k,m):2People = List (range (1,n+1))#Initialize, sequence designator,..., n3i = K-1#I recorded the subscript of the K person4 forNuminchRange (N):#Loop n times5Count =06 whileCount <m:7 ifPeople[i] > 0:#Skip the person who has exited8Count + = 19 ifCount = = m:#Note here: I have not yet +1Ten Print(People[i], end="") OnePeople[i] =0 Ai = (i + 1)% n#cycle of Control I - ifNum < n + 1 : - Print(", ", end="") the Else : - Print("")
- A solution based on sequential table
Take advantage of the nature of the list, pop up the person who counted m
1 #take advantage of the nature of the list, pop up the person who counted m2 3 defjosephus_l (n,k,m):4People = List (range (1,n+1))5num, i = N, k-16 forNuminchRange (n,0,-1):7i = (i + m-1)% num#The subscript of a man who counted M8 Print(People.pop (i), end="")#the person who counted the number of M pops up after I automatically points to the next9 return
- Solution based on circular single-link list
The solution of--josephus problem using linear table (Python version)