试图找出这个描述为递归搜索的ruby代码片段

时间:2016-12-13 19:14:53

标签: ruby recursion

代码段是我尝试改进和修改的裁切表算法的一部分。

这里是前一个编码器留下的注释代码。我试图弄清楚代码是如何找到最合适的。'。我期待对结果进行某种数组比较,但我从来没有遇到过递归搜索,因为它已经描述过,并且不了解结果是如何实现的,以及我如何改进结果:

# use a recursive search to find the best spot for a part
# best fit means least wastage ie: the area of the piece to place comes closes to the area of the space
# from the given Node, return a result if it is a leaf node, otherwise go left, then go right recursively.
# returns the chosen best leaf node


def findBestFit(node, part_length, part_width)
    return nil      if node==nil    # nothing here if this is a nil node
    # am i in a node or a leaf
    leaf=false
    leaf=true       if node.getNodeType=="leaf"

    if leaf # look at the leaf if we are a leaf
        # won't fit if length is too short
        # Note: make the comparisons here after applying the length transformation.
        # This gives the same level of accuracy as the model units - which is what is relevant for layout
        # Otherwise, there may be inaccurate comparisons between internal numbers which have been
        # subjected to scaling, multiplication etc which can make round numbers into floats thus preventing
        # parts from fitting when by all practical measures, they do.

        return nil  if part_length.to_l > node.rect[:length].to_l               # won't fit if length is too narrow
        return nil  if part_width.to_l > node.rect[:width].to_l                 # won't fit if width is too narrow
        return node                                                             # fits, so return as a potential best fit
    end

    # it's a node
    bestLeft=findBestFit(node.left, part_length, part_width)    #go left
    bestRight=findBestFit(node.right, part_length, part_width)  #go right

    return nil          if bestLeft==nil && bestRight==nil  # now determine which is the best. No brainer if one or both are nil
    return bestLeft     if bestRight== nil
    return bestRight    if bestLeft==nil

    # otherwise both are potentials and we have to choose one
    # pick based on best fit  ie: least amount of waste left or the one further to the origin of the board or both. User can select
    # the bias, otherwise we use both rules and try to pack the parts from left to right
    # (note area on the board must >= the part size because of earlier decisions)

    part_area=part_length*part_width
    ruleA=(((bestLeft.rect[:length]*bestLeft.rect[:width])-part_area)<=((bestRight.rect[:length]*bestRight.rect[:width])-part_area)) && @layoutOptions[:layoutRuleA]
    ruleB=(bestLeft.rect[:xy][0]<bestRight.rect[:xy][0]) && @layoutOptions[:layoutRuleB]

    return bestLeft     if ruleA || ruleB
    return bestRight
end

0 个答案:

没有答案