代码之家  ›  专栏  ›  技术社区  ›  InDaPond

脑筋急转弯:在六边形中找到正确的旋转方向(顺时针/逆时针)

  •  1
  • InDaPond  · 技术社区  · 7 年前

    假设我有一个六边形排列的数字。

         0
      5     1  
      4     2
         3
    

    从一个点到另一个点,我只能顺时针/逆时针穿过我的邻居。

    我想知道给定输入是顺时针还是逆时针(currentposition,targetposition)

    例如,要从1到3,顺时针更明智,因为它需要顺时针(1-2-3)2步和逆时针(1-0-5-4-3)4步。

    我不想做大的 if/else construct 必须有另一种方法。

    到目前为止我明显错误的解决方案:

    if ( ((currentPosition + 3) % 6) == nextStation) {
            //both - that part is correct - 
            return Direction.BOTH
    
    } else if ( ??? ) {
        //CL
        return Direction.CLOCKWISE
    } else {
        //CCL
        return Direction.COUNTERCLOCKWISE
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Paul    7 年前

    从确定顺时针所需的步数开始(您可以选择逆时针计数,但在这里我将使用顺时针):

    steps = (6 + end - start) % 6
    

    从这里开始,它相当直接:

    if steps < 3:
        return CLOCKWISE
    else if steps > 3:
        return COUNTERCLOCKWISE
    else
        return DONT_CARE