码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-07-18 12:11:53      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:UNC   filter   数组   ref   red   reduce   ++   gic   ==   

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]);
}

 

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

标签:UNC   filter   数组   ref   red   reduce   ++   gic   ==   

原文地址:https://www.cnblogs.com/ukzq/p/11206366.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!