从给定的

时间:2017-11-20 21:06:10

标签: algorithm language-agnostic

鉴于结构:

structure box_dimensions:
    int? left
    int? right
    int? top
    int? bottom
    point? top_left     
    point? top_right
    point? bottom_left
    point? bottom_right
    point? top_center
    point? bottom_center
    point? center_left
    point? center_right
    point? center
    int? width
    int? height
    rectangle? bounds

可以定义或不定义每个字段。

您如何实现函数check_and_complete(box_dimensions)

  • 如果没有足够的字段来定义框,或者太多,那么该函数应该返回错误。
  • 如果输入一致,则应计算未定义的字段。

您可以通过其中心,宽度和高度,或top_left和bottom_right角等来描述框。

我能想到的唯一解决方案包含许多if-elses。我确信这是一种聪明的方法。

修改

如果你想知道我最终是如何得到这样的结构,这就是原因:

我正在通过约束来解决布局问题"系统:

用户定义一堆框,并为每个框定义一组约束,如" box_a.top_left = box_b.bottom_right"," box_a.width = box_b.width / 2&#34 ;

实际结构字段实际上是表达式AST,而不是值。

所以我需要检查一个盒子是否是" underconstrained"或者"过度约束",如果可以的话,从给定的表达式中创建缺失的表达式AST。

1 个答案:

答案 0 :(得分:1)

是的,肯定会有太多if-else。 这是我试图让他们合理组织:

howManyLefts = 0

if (left is set) { realLeft = left; howManyLefts++; }
if (top_left is set) { realLeft = top_left.left; howManyLefts++; }
if (bottom_left is set) { realLeft = bottom_left.left; howManyLefts++; }
if (center_left is set) { realLeft = center_left.left; howManyLefts++; }
if (bounds is set) { realLeft = bounds.left; howManyLefts++; }

if (howManyLefts > 1) return error;

现在,重复centerrightwidth的代码块。 现在最终得到howManyLeftshowManyCentershowManyRightshowManyWidths,所有这些都是零或一,取决于是否提供了值。您需要完全两个值设置,两个未设置,所以:

if (howManyLefts + howManyRights + howManyCenters + howManyWidths != 2) return error

if (howManyWidths == 0)
{
  // howManyWidths is 0, so we look for the remaining 0 and assume the rest is 1s
  if (howManyCenters == 0)
    { realWidth = realRight - realLeft; realCenter = (realRight + realLeft) / 2; }
  else if (howManyLefts == 0)
    { realWidth = 2 * (realRight - realCenter); realLeft = realRight - realWidth; }
  else
    { realWidth = 2 * (realCenter - realLeft); realRight = realLeft + realWidth; }
}
else
{
  // howManyWidths is 1, so we look for the remaining 1 and assume the rest is 0s
  if (howManyCenters == 1)
    { realLeft = realCenter - realWidth / 2; realRight = realCenter + realWidth / 2; }
  else if (howManyLefts == 1)
    { realRight = realLeft + realWidth; realCenter = (realRight + realLeft) / 2; }
  else
    { realLeft = realRight - realWidth; realCenter = (realRight + realLeft) / 2; }
}

现在,重复垂直轴的所有内容(即用{left替换{centerrightwidthtop},{{1 }},centerbottom})。