What's a good way to structure variable nested loops?

后端 未结 3 2038
孤独总比滥情好
孤独总比滥情好 2020-12-16 07:51

Suppose you\'re working in a language with variable length arrays (e.g. with A[i] for all i in 1..A.length) and have to write a routin

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 08:28

    Either the recursive algorithm

    procedure register_combination( items )
            register_combination2( [], items [1:] )
    
    procedure register_combination2( head, items)
        if items == []
            print head
        else
           for i in items[0]
               register_combination2( head ++ i, items [1:] )
    

    or the same with tail calls optimised out, using an array for the indices, and incrementing the last index until it reaches the length of the corresponding array, then carrying the increment up.

提交回复
热议问题