简体   繁体   中英

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. 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. 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]

 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 ].

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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