SoFunction
Updated on 2024-11-13

Example of non-recursive output of full permutations 1-N (recommended)

One of the NetEase game written test questions algorithm questions, you can use C++,Java,Python, due to Python code size is smaller, so I choose Python language.

The general idea of the algorithm is to start with the permutation 1,2,3......N and keep calculating the next permutation until you output N,N-1,......1

So how do you calculate the next permutation of a given permutation?

Consider the sequence [2, 3, 5, 4, 1] and look for the first pair of increasing neighboring numbers from back to front, i.e., 3, 5. Then 3 is the replacement number and the position where 3 is located is the replacement point.

Swap 3 with the smallest number after the replacement point that is greater than 3, in this case 4, to get [2,4,5,3,1]. Then exchange the first and last numbers after the substitution point, i.e., exchange 5, 1. You get the next sequence [2,4,1,3,5].

The code is as follows:

def arrange(pos_int):
  # Putting 1-N into tempList has facilitated processing
  tempList = [i+1 for i in range(pos_int)]
  print(tempList)

  while tempList != [pos_int-i for i in range(pos_int)]:
    for i in range(pos_int-1,-1,-1):
      if(tempList[i]>tempList[i-1]):
        #Consider the smallest of the elements after tempList[i-1] that are larger than it, swap.
        minmax = min([k for k in tempList[i::] if k > tempList[i-1]])
        # Get minmax's position in tempList
        index = (minmax)
        #Exchange
        temp = tempList[i-1]
        tempList[i-1] = tempList[index]
        tempList[index] = temp

        # Swap tempList[i] and the last element again to get the next permutation of tempList
        temp = tempList[i]
        tempList[i] = tempList[pos_int-1]
        tempList[pos_int-1] = temp

        print(tempList)
        break
          
  
  
arrange(5)  

Above this non-recursive output 1-N full permutation example (recommended) is all that I have shared with you, I hope to give you a reference, and I hope that you will support me more.