7kyu (难度系数kyu阶段数值越大难度越低) 数组分组及求和

https://www.codewars.com/kata/row-weights/train/java

public class Solution
{
    public static int[] rowWeights (final int[] weights)
    {
        int result1 = 0;
        int result2 = 0;
        int len = weights.length;
        if(len==0){
          return new int[]{0, 0}; // Do your magic!
        }
        for(int i=0;i<len;i++){
          if(i%2==0){
            result1+=weights[i];
          }else{
            result2+=weights[i];
          }
        }
        return new int[]{result1,result2};
        
    }
}

大神的Solution

public class Solution {
  public static int[] rowWeights (final int[] weights) {
    int totals[] = new int[2], idx = 0;
    for (int w : weights) totals[(idx++)%2] += w;
    return totals;
  }
  
}

 

js的解:

function rowWeights(array){
  //your code here
    let a = 0;
    let b = 0;
    for (let i=0;i<array.length;i++) {
      if (i % 2 == 0) {
        a += array[i];
      } else {
        b += array[i];
      }
    }
    return new Array(a, b);
    
}

js大神的Solution

function rowWeights(array){
  let t1 = array.filter((x, i)=>i%2==0).reduce((a,item)=>a+item,0);
  let t2 = array.filter((x, i)=>i%2!=0).reduce((a,item)=>a+item,0);
  
  return [t1, t2]
}
rowWeights=arr=>arr.reduce((a,b,i)=>(a[i%2]+=b,a),[0,0])
function rowWeights(array){
  var arr = [0, 0];
  for (var i = 0; i < array.length; i++) {
    i % 2 == 0 ? arr[0] += array[i] : arr[1] += array[i];
  }
  return arr;
}
const rowWeights = arr => arr.reduce((a, w, i) => (a[i%2]+=w, a), [0, 0]);
const rowWeights = a => a.reduce(([s1,s2],n,i)=> i%2 ? [s1,s2+n]: [s1+n, s2] , [0,0])
function rowWeights(array) {
  return array.reduce((t, x, i) => {
    t[i % 2] += x;
    return t;
  }, [0, 0]);
}
function rowWeights(array) {
  return array.reduce((a, b, i) => (a[i%2] += b, a), [0, 0]);
}
function rowWeights(a,f=0,s=0){
  return (a.map((x,i)=>i%2?s+=x:f+=x),[f,s]);
}

 

posted @ 2019-07-18 11:55  ukyo--BlackJesus  阅读(436)  评论(0编辑  收藏  举报