2017-05-06 21 views
0

私はCodeFightsと私のjavascriptを練習していたし、私は結果として、この機能を見て、運動終了後:式 `p [i&1] + = v、p`はどういう意味ですか?

// Subject : 
// Several people are standing in a row and need to be divided into two teams. 
// The first person goes into team 1, the second goes into team 2, 
// the third goes into team 1 again, the fourth into team 2, and so on. 
// You are given an array of positive integers - the weights of the people. 
// Return an array of two integers, where the first element is the total weight of 
// team 1, and the second element is the total weight of team 2 
// after the division is complete. 

// Example : 
// For a = [50, 60, 60, 45, 70], the output should be 
// alternatingSums(a) = [180, 105]. 

// answer 
alternatingSums = a => a.reduce((p,v,i) => (p[i&1]+=v,p), [0,0]) 

を私は何p[i&1]+=v,p手段を理解していません。

+0

'P&1:pを返し、その後、このアクションを実行します」と言っています

(p[i&1]+=v,p) 

それはのための速記です'pの奇数と偶数については0と1の間で変化します(ビット位置0のみを値1で見ます)。これは名前とコメントが言っていることを正確に行い、2番目ごとに合計します。 – eckes

答えて

2

&シンボルはビット単位の2進演算子です。

何が起こるかを理解するには、各項目をバイナリに変換する必要があります。

| i (decimal) | i (binary) | i & 1 | 
    |-------------|------------|-------| 
    |   0 |   0 |  0 | 
    |   1 |   1 |  1 | 
    |   2 |   10 |  0 | 
    |   3 |   11 |  1 | 
    |   4 |  100 |  0 | 
    |   5 |  101 |  1 | 

事実上、すべての偶数が0に変換されます、と私はその結果を達成しようとしていた場合は、すべての奇数の1

に変換されます、私は個人的に(剰余演算子を使用しているだろう%

p[i%2] += v; 

しかし、それは私です。


他の部分は、カンマで区切られた2つの文があるということです:。

alternatingSums = a => a.reduce((p,v,i) => { 
               p[i&1]+=v; 
               return p; 
              }, 
           [0,0]) 
2

インデックスがi&1p配列の要素を探します。これはビット単位のAND演算です。次に、その値をvという変数で増分します。最後に、変数pの値を返します。

関連する問題