我正在尝试解决CodeWars Kata:Zeros和Ones。 我的代码解决了1800多个Attempt测试,并且失败了100多个。 我的问题是我看不到测试数据,因为它太大了。 要查看其他katas中的测试数据,我可以使用console.log语句。 但是,这次挑战中的测试数据太大了。我得到一个输入数组的第一部分列表,然后是"以及另外400个项目。"
下面是对kata和我的代码以及一些测试用例的描述。 我试图创建在代码运行时失败的测试用例;但是,我无法创造任何失败。
给定一个只包含0和1的数组,找到的索引 零,如果转换为一,将成为最长的序列 那些。例如,给定数组...... [1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,0,0,1,1],......取代零点 索引10(从0开始计数)形成9个序列。你的任务是 编写确定替换位置的函数replaceZero() 零用一个来制作最大长度的子序列。注意:如果 是多个结果,返回最后[1,1,0,1,1,0,1,1] // => 5 数组将始终包含0和1。
function replaceZero(arr){
var highestCt = 0;
var returnIdx = 0;
var onesCt = 0;
var currentHighOnesCt = 0;
function countOnes(currentIZ){ // The input should be the current index of the ZERO.
for(var j = currentIZ - 1; j >= 0; j--){ // Go backwards until a zero is found, or to the beginning of the array.
if(arr[j] === 1){
onesCt = onesCt + 1;
}
else { // if arr[j] === 0
break;
}
}
for(var k = currentIZ + 1; k < arr.length; k++){ // Go forwards to a zero or the end of the array.
if(arr[k] === 1){
onesCt = onesCt + 1;
}
else { // if arr[k] === 0
break;
}
}
if(onesCt >= currentHighOnesCt){
currentHighOnesCt = onesCt;
returnIdx = currentIZ;
}
onesCt = 0;
}
for(var i = 0; i < arr.length - 2; i++)
if(arr[i] === 1 && arr[i + 1] === 0 && arr[i + 2] === 1){
countOnes(i + 1); // Send the index of the ZERO.
}
// console.log("returnIdx: " + returnIdx);
return returnIdx;
}
/*
replaceZero([0,0,1,1,1,0,1,1,0,0,1,0]); // 5
replaceZero([0,0,0,1,1,1,0,1,1,0,0,0]); // 6
replaceZero([1,1,1,1,0,1]); // 4
*/
replaceZero([1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1]); // 9
replaceZero([1,0,0,0,1,0,1,1]); // 5
/*
replaceZero([0,0,1,1,1,1,0,1,1,1,0,1,1,0,0,1,1,0,1,1,0,1,1]); // 6
replaceZero([0,0,1,0,0,1,1,1,0,1,1,0,0,1,1,0,1,1,0]); // 8
replaceZero([0,0,1,0,0,1,1,0,1,1,0,0,1,1,1,0,1,1,0]); // 15
replaceZero([1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,0,0,1,1]); // 10;
replaceZero([1,1,0,1,1,0,1,1]); // 5;
replaceZero([1,1,1,0,1,1,0,1,1,1]); // 6);
*/
答案 0 :(得分:0)
好吧,我实际上并没有重构您的代码,但这可能会对您有所帮助:
Zero
介于两个Ones
之间?
你的if语句在这件事上是有缺陷的。您的代码:
if(arr[i] === 1 && arr[i + 1] === 0 && arr[i + 2] === 1){ //WHY IN BETWEEN??
countOnes(i + 1); // Send the index of the ZERO.
}
代码:
replaceZero([0,0,0,0,0,0,1]); // 0
replaceZero([0,0,0,0,0,1,1]); // 0
replaceZero([0,0,0,0,1,1,1]); // 0
//.. and so on
//Also
replaceZero([1,1,1,1,1,0,0]); // 0
replaceZero([1,1,1,1,0,0,0]); // 0
如果在这种情况下对[0,0,0,0,0,0,0]
进行测试,那么数组中的最后一个索引就是预期的答案,并不会感到惊讶。