编程技巧-索引标记法

在本周的Code Review中,从Pair学到一个技巧--索引标记法(暂且叫这个名称)

题目

以任意一个Cell中心,根据8个邻居状态,判断该Cell下一个状态:如果2个活着那么保持状态不变,3个邻居活者也为活,其他情况都是死。普通程序是这样的(0表示死,1表示活):

 public int nextStatus(int currentStatus, int liveCount) {
        switch (liveCount) {
            case 2:
                return currentStatus;
            case 3:
                return 1;
            default:
                return 0;
        }
    }

但是由于不能使用switch以及for怎么办呢?

如何解决

再分析一下静态的数据如下

[ 0->0 , 1->0 , 2->current_status , 3->1 , 4->0 , 5->0 , 6->0 , 7->0 , 8->0]

方法1:map

 public int nextStatus(boolean currentStatus, int liveCount) {
        Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
        map.put(0, 0);
        map.put(1, 0);
        map.put(2, currentStatus);
        map.put(3, 1);
        map.put(4, 0);
        map.put(5, 0);
        map.put(6, 0);
        map.put(7, 0);
        map.put(8, 0);
        return map.get(liveCount);
    }

有没有发现这样太傻,而且不太友好

方法2:bitmap

恭喜你上道了,开始思考了,使用BitSet,也可以

方法3:重点

 public int nextStatus(int liveCount) {
        return new int[]{0, 0, 0, 1, 0, 0, 0, 0, 0}[liveCount];
    }

有没发现被蒙到了,其实把数据是数据静态的结构多变的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值