首页 > 解决方案 > 将布尔数组转换为计数器

问题描述

我有一个大小为 12 的布尔数组。在任何时候,只有一个索引为真。数组连接到旋钮上的 12 位置,从 0 到 11。如果我们将旋钮从位置 5 顺时针移动到 6,数组中的索引 5 将变为 false,索引 6 将为 True。11 位后旋钮将移回 0。

我想创建一个随着旋钮顺时针或逆时针移动而增加或减少的计数器。如果位置从 11 变为 0,计数器也将继续增加。类似地,从 0 移动到 12 时,计数器将减小。

以非常简单的方式,我希望布尔数组表现得像一个旋转编码器。

标签: c#arraysbooleancounter

解决方案


I wouldn't do it with an array. Create an object that has this specific functionality

public class RotaryEncoder {
     private int totalPositions:
     public int ActiveIndex = { get; private set; }

     public RotaryEncoder(int totalPositions) {
          this.totalPositions = totalPositions;
          this.ActiveIndex = 0;
     }

     public void IncreasePosition() {
         ActiveIndex = ActiveIndex + 1 == totalPositions ? 0 : ActiveIndex + 1;
     }
}

You get the idea on how to decrease position. The boolean array itself has no extra properties as active index.

A different approach, would have you create a collection of new objects that held both a boolean and an index and change both the active and new active item at once. (Surely less efficient).

If course, you would again have to encapsulate then into a class, as you don't want implementation details to leak out and let consumers handle your data structure as they please.


推荐阅读