简体   繁体   English

重复的数字

[英]Repeated Numbers

我删除了这个,因为我不相信这是一个很好的问题

if you really want to take in strings, I would take two strings and convert each of them into array as you have written eg[2,3,4] and [1,4,5] then concatonate them. 如果你真的想要接受字符串,我会取两个字符串并将它们中的每一个转换成数组,如你所写的那样[2,3,4]和[1,4,5]然后将它们连接起来。 Then arrange them in order using simple data structure algorithm. 然后使用简单的数据结构算法按顺序排列它们。 So for example, go through each item in the array and move it to the 0 position if it is the smallest number. 因此,例如,遍历数组中的每个项目,如果它是最小的数字,则将其移动到0位置。 Then go to the next position and also try to move the lowest number in the array except the first position to the second position, etc. 然后转到下一个位置,并尝试将除第一个位置之外的数组中的最小数字移动到第二个位置,等等。

I have an idea, I think there should be a repeat function. 我有一个想法,我认为应该有重复功能。 For example, it can repeat 'a' 3 times.Like a => [a, a, a] 例如,它可以重复'a'3次。就像a => [a, a, a]

 function repeat(a, times) {
     if (times === 0) return [];
     return [a].concat(repeat(a, times - 1));
 }

Then I using it to finish this question. 然后我用它来完成这个问题。

 function repeatAndConcat(times, arr) {
   return arr.map(function(item, index) {
     return repeat(item, times[index]);
   }).reduce(function(a, b) {
     return a.concat(b);
   });
 }

repeatConcat([2, 3, 4], [1, 4, 5]) with return [ 1, 1, 4, 4, 4, 5, 5, 5, 5 ]. repeatConcat([2,3,4],[1,4,5])返回[1,1,4,4,4,5,5,5,5]。

The last reduce flat a nested array. 最后一个减少扁平嵌套数组。

You can use Array.prototype.entries() , for..of loop, spread element, Array.prototype.fill() to create array having .length set by value of element at first array, filled with value at second array at same index 您可以使用Array.prototype.entries()for..of循环,spread元素, Array.prototype.fill()来创建数据,其中.length由第一个数组的元素值设置,在第二个数组处填充值指数

 let [len, arr, res] = [[2,3,4], [1,4,5], []]; for (let [key, prop] of arr.entries()) res.push(...Array(len[key]).fill(prop)); console.log(res); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM