javascript - 在 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)
}
解决方案
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]
推荐阅读
- spring - LDAP Spring Security 不会引发密码策略错误
- c++ - 在我的机器中使用多个 GPU (Intel + Nvidia) - 在它们之间复制数据
- c++ - Qt 应用程序找不到第 3 方 DLL 并崩溃
- python - 继续 for 循环而不进行迭代
- apache-spark - 是否可以使用 Spark Streaming SQL 实时解析来自 Kafka 主题的 JSON 字符串?
- c - 如何检查 % 无法识别的 scanf 输入
- linux-kernel - 可重入内核和抢占内核之间有什么关系?
- c# - 在不使用 IDataProtector 的情况下,在 ASP.NET Core 中加密 cookie 的简单/体面方法是什么?
- heroku - 在“应用程序”中找不到应用程序对象“服务器”
- php - MySQL 双表 INNER JOIN , LEFT JOINED 到第三张表,只有一行具有最低值