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

后端 未结 3 2035
孤独总比滥情好
孤独总比滥情好 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:17

    Since they were opposed to recursion (don't ask) and I was opposed to messy case statements (which, as it turned out, were hiding a bug) I went with this:

    procedure register_combination( items : vararray of vararray of An_item)
        possible_combinations = 1
        for each item_list in items
            possible_combinations = possible_combinations * item_list.length
        for i from 0 to possible_combinations-1
            index = i
            this_combination = []
            for each item_list in items
                item_from_this_list = index mod item_list.length
                this_combination << item_list[item_from_this_list]
                index = index div item_list.length
            register_combination(this_combination)
    

    Basically, I figure out how many combinations there are, assign each one a number, and then loop through the number producing the corresponding combination. Not a new trick, I suspect, but one worth knowing.

    It's shorter, works for any practical combination of list lengths (if there are over 2^60 combinations, they have other problems), isn't recursive, and doesn't have the bug.

    0 讨论(0)
  • 2020-12-16 08:27

    Recursion.

    Or, better yet, trying to eliminate recursion using stack-like structures and while statements.

    For your problem you stated (calling a function with variable arguments) it depends entirely on the programming language you're coding in; many of them allow for passing variable arguments.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题