首页 > 解决方案 > 在 Javascript 中遇到 cellCompete 问题,需要一些帮助

问题描述

所以这个指令是:

有8个细胞排列成一条直线的菌落,每天每个细胞都与它的相邻细胞(邻居)竞争。每天,对于每个单元格,如果其邻居都处于活动状态或都处于不活动状态,则该单元格在第二天变为不活动状态,否则在第二天变为活动状态。

假设两端的两个单元有一个相邻的单元,因此可以假设另一个相邻的单元始终处于非活动状态。即使在更新单元状态之后。考虑其先前的状态以更新其他单元的状态。同时更新所有小区的小区信息。

编写一个函数 cellCompete,它接受一个 8 元素整数数组,代表 8 个单元的当前状态,一个整数天代表模拟的天数。整数值 1 表示活动单元格,值 0 表示非活动单元格。

我编写了一个递归函数,它将状态传播到 newStates 中,并通过遍历状态和检查相邻元素来修改 newStates。

我的结果与测试用例所说的不匹配应该输出。

例如:

cellCompete([1,1,1,0,1,1,1], 2)) //-> 应该返回 [0,0,0,0,1,1,0],而是返回 [ 0, 0 , 0, 0, 0, 0, 0 ]

我的代码是

function cellCompete(states, days){
    //base case, if days === 0, return states.
    if(days === 0) return states;
    let newStates = [...states];
      // iterate through states with i
      for(let i = 0; i < states.length; i++){
          //if i is not on first or last element in the array
          if (i !== 0 && i !== states.length - 1){
            if(states[i-1] === states[i+1]){
               newStates[i] = 0
            } else {
              //if not equal, cell becomes inactive
              newStates[i] = 1
            }  
          }
          //if first element check next against 0
          if(i === 0){
            if(states[i+1] === 0){
              newStates[0] = 0
            } else {
              newStates[0] = 1
            }
          }
          //if last element check previous against 0
          if(i === states.length - 1){
            if(states[i-1] === 0){
              newStates[i] = 0
            } else {
              newStates[i] = 1
            }
          }
      }
    return cellCompete(newStates, --days)
}

标签: javascript

解决方案


cellCompete([1,1,1,0,1,1,1], 2) 应该返回 [0,0,0,0,0,0,0]

第 1 天:[1,0,1,0,1,0,1]

第 2 天:[0,0,0,0,0,0,0]

我认为您提供了错误的输入,因为您的输入仅包含 7 个单元格,而问题说明了 8 个单元格。

cellCompete([1,1,1,0,1,1,1,1], 2) 返回 [0,0,0,0,0,1,1,0]


推荐阅读