平均填充数组

时间:2014-06-28 20:35:45

标签: javascript arrays

给出2个数组(最大长度为15):

var a = [1,2,3];
var b = [5,6,7,8,9,10,11,12];
var data = [13,14,15,16,17,18,19,20,21,22,23,24,25,26];

"填充"最好的方法是什么?数组ab与来自data数组的数据一样,所以它们的长度相同(或接近它)但不超过最大长度?

必需的结果可以看起来像这样:

var a = [1,2,3,13,14,15,16,17,18,19,20,21];
var b = [5,6,7,8,9,10,11,12,22,23,24,25,26];

<小时/> 我的情况更复杂,我正在寻找一种有效的方式:我在屏幕上有两面,每一面都可能有来自FB的ppl的个人资料照片。如果一方没有足够的照片,我需要添加&#34;假的&#34;照片填充它,所以双方看起来或多或少均匀地填充照片

7 个答案:

答案 0 :(得分:1)

var a    = [1,2,3];
var b    = [5,6,7,8,9,10,11,12];
var data = [13,14,15,16,17,18,19,20,21,22,23,24,25,26];

for( var i = data.length; i--; ){
  if (a.length > b.length)
      b.push(data[i])
  else
      a.push(data[i])
}

console.log(a.length, b.length);

答案 1 :(得分:1)

这是另一种不必遍历元素的方法:

var a = [1,2,3],
    b = [5,6,7,8,9,10,11,12],
    data = [13,14,15,16,17,18,19,20,21,22,23,24,25,26];

var targetLength = (a.length + b.length + data.length)/2,
    aCnt = Math.ceil(targetLength) - a.length,
    bCnt = Math.floor(targetLength) - b.length;

a = a.concat(data.slice(0, aCnt));
b = b.concat(data.slice(aCnt, data.length));

// a is [1, 2, 3, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
// b is [5, 6, 7, 8, 9, 10, 11, 12, 23, 24, 25, 26]

答案 2 :(得分:1)

根据布拉德的评论,我想你可以这样做:

ab=[];
ab=ab.concat(a,b,data);
del = (a.length + b.length + data.length) / 2;
a = [];
b = [];
for (var i = 0; i < Math.ceil(del); i++) {
    a.push(ab[i]);
    b.push(ab[Math.ceil(del) + i]);
}

答案 3 :(得分:0)

算法就像:

1)确定a

中的元素数量

2)确定b

中的元素数量

3)确定data

中的元素数量

4)如果a中的元素小于b,则从data填充a直到它等于b,反之亦然

5)如果ab元素相等且data仍然具有元素,则填充数组ab

答案 4 :(得分:0)

你想要a和b的最后一个索引有12个deference而len的最终数组是12 !!!我想你可以使用这个算法! :

for j in data:
  while ( j-max(a)) == 12 ):
   x++
for i in range(x):
 data[i]=a[i]

之后删除索引号为mor的索引!

答案 5 :(得分:0)

我的解决方案是:

var a    = [1,2,3];
var b    = [5,6,7,8,9,10,11,12];
var data = [13,14,15,16,17,18,19,20,21,22,23,24,25,26];

var howManyToFill = (data.length + (b.length + a.length)/2)/2;
// take half of the "data" and put it in "a"
a = a.concat(data.slice(0,howManyToFill));
// what's left goes to "b"
b = b.concat(data.slice(howManyToFill));

console.log(a);
console.log(b);

答案 6 :(得分:0)

var b = [1,2,3];
var a = [5,6,7,8,9,10,11,12];
var data = [13,14,15,16,17,18,19,20,21,22,23,24,25,26];

// find how many more elements need to be added to the smaller array 
var diff = Math.abs(b.length - a.length);

// get the elements to add to the smallest array
var data1 = data.splice(0, diff + ((data.length - diff) / 2));

// data now only contains the elements that will not be added to the smallest array

if (a.length < b.length) {
    // a is the smallest array
    a.push.apply(a,  data1);
    b.push.apply(b, data);
} else {
    // b is the smallest array
    b.push.apply(b,  data1);
    a.push.apply(a, data);
}