2017-05-07 59 views
1

数组A = [1,0,1,1,1,1,0,1,1]]; 结果将是B B = [1,0,4,3,2,1,0,2,1]; 给出了A的元素,结果为B. A中的元素只能是0和1. 我们需要从A中的最后一个元素向后计数,如果有连续的1,那么A和B中的元素将会是1但是连续第二次1在A中它将会在2中并且对于第三个在A中元素将会在B中为3 但是0它将会是0.我已经尝试了下面的方式,但我不是获得输出。应该从数组A中获得数组B的正确算法

<script> 

var A= [1,0,1,1,1,1,0,1,1]]; 
var B =[]; 
//var B= A.length; 

var lastValueOne; 
var consecutiveOnes = 0; 

for (i = A.Length - 1; i >= 0; i--) 
    { 
     if (lastValueOne== false) 
     { 
       consecutiveOnes = 0; 
       B[i] = 0; 
     } 
     else 
     { 
      consecutiveOnes++; 
      B[i] = consecutiveOnes; 
     } 

     if (A[i] == 1) 
     { 
      lastValueOne = true; 
     } 

     else 
     { 
      lastValueOne = false; 
     } 
    } 

    //console.log(B[i]); 
document.getElementById("demo").innerHTML = B; 
+2

问题是什么?你的解决方案出了什么问题? – Meier

+0

我没有得到输出。 –

+0

你会得到哪个输出? – Meier

回答

2

如果在实际索引处给出真值,则可以迭代给定数组并映射计数值。然后迭代,直到找到一个falsy值并返回计数。

var array = [1, 0, 1, 1, 1, 1, 0, 1, 1], 
 
    result = array.map(function (_, i, a) { // take only index and array as parameter 
 
     var count = 0;      // declare and initialize counter with zero 
 
     while(a[i++]) {      // check value at actual index and inc index 
 
      count++;      // increment counter while true/truthy 
 
     } 
 
     return count;      // return count 
 
    }); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

移动le_manswer位超前的想法不使用sum变量和使用该结果阵列r[0]的第一元件,用于保持的累积和。

var array = [1, 0, 1, 1, 1, 1, 0, 1, 1], 
 
    result = array.reduceRight(function (r, a) { 
 
     return [a && (r[0] || 0) + a].concat(r); 
 
    }, []); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

非常感谢你,只需要一个请求,你可以请详细说明一下函数(_,i,a)@ninaScholz –

+0

谢谢,顺便说一下,它是如何向后添加? –

+0

如果你的意思是第一种方法,它使用一个循环来看看下一个元素和dexide是否添加或离开计数循环。第二个从右侧进行迭代,并使用最后一个元素的值来为实际值进行添加。 –

0

您应该只增加consecutiveOnes如果说去年值为1,当前值也为1 但逻辑可以simplier,因为当最后一个值是假的,你连续值也应为0

var A= [1,0,1,1,1,1,0,1,1]; 
var B = []; 
var consecutiveOnes = 0; 

for (i = A.length - 1; i >= 0; i--) 
    { 
     if (A[i] == 1) 
     { 
      consecutiveOnes += 1; 
     } 
     else 
     { 
      consecutiveOnes = 0; 
     } 
     B[i] = consecutiveOnes; 
    } 

console.log(B); 
1

更具描述性的Array.reduceRight很适合您的从右向左计算累计总和的任务。

// Return cumulative sums from right, reset on zero: 
 
function cumSumRight(array, sum = 0) { 
 
    return array.reduceRight((result, a) => { 
 
    sum = a > 0 ? sum + a : 0; 
 
    result.unshift(sum); 
 
    return result; 
 
    }, []); 
 
} 
 

 
// Example: 
 
console.log(cumSumRight([1,0,1,1,1,1,0,1,1])); // [1,0,4,3,2,1,0,2,1]

要解决当前的解决方案,写A.length而不是A.Length。您可以简化为:

let sum = 0; 
for (let i = A.length - 1; i >= 0; i--) { 
    sum += A[i]; 
    if (A[i] === 0) { 
    sum = 0; 
    } 
    B.unshift(sum); 
} 
+0

你可以使用'result [0]'来省略'sum'。 –

+1

@NinaScholz是的,但是保存一个'Number'分配真的值得吗? ;) –

+2

这是一个味道的问题... –

相关问题