'Printing Out Repeated Numbers

so I'm working on a program that takes two strings. For instance [2,3,4] and [1,4,5] and outprints 1,1,4,4,4,5,5,5,5. I don't really have a working code. So, I'm just looking for tips, not a complete code.



Solution 1:[1]

if you really want to take in strings, I would take two strings and convert each of them into array as you have written e.g.[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.

Solution 2:[2]

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.

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 forJ
Solution 2 g1eny0ung
Solution 3 guest271314