KenKen puzzle addends: REDUX A (corrected) non-recursive algorithm

后端 未结 9 1731
眼角桃花
眼角桃花 2021-01-03 05:24

This question relates to those parts of the KenKen Latin Square puzzles which ask you to find all possible combinations of ncells numbers with values x such that 1 <= x &

9条回答
  •  佛祖请我去吃肉
    2021-01-03 05:53

    Here is a naive, but succinct, solution using generators:

    def descending(v):
      """Decide if a square contains values in descending order"""
      return list(reversed(v)) == sorted(v)
    
    def latinSquares(max_val, target_sum, n_cells):
      """Return all descending n_cells-dimensional squares,
         no cell larger than max_val, sum equal to target_sum."""
      possibilities = itertools.product(range(1,max_val+1),repeat=n_cells)
      for square in possibilities:
        if descending(square) and sum(square) == target_sum:
          yield square
    

    I could have optimized this code by directly enumerating the list of descending grids, but I find itertools.product much clearer for a first-pass solution. Finally, calling the function:

    for m in latinSquares(6, 12, 4):
      print m
    

提交回复
热议问题