ashToronto
ashToronto

Reputation: 45

function to repeat same numbers y times

I am trying to write a function that returns the number x. y number of times. The function should be able to take in multiple 2d arrays. There will be only 2 elements per input array.

So for example: function([4,3][2,2][12,5]) //output should be exactly: 444, 22, 1212121212

I have solved most of the problem but I am stuck when x is a 2 digit number. would appreciate some help in solving this. I must return the solution as a string with a comma (' ,') that separates the different arrays. Here is my code as of now:

 function repeatnumber(data){
    var result = " "; 
    for (var i = 0; i < data.length; i++){
            if (Array.isArray(data[i])){
                var x = data[i][0]
                var y = data[i][1]
                for(var j = 1; j <= y; j++){
                    result = result + x;
                }
            }
        }
    var number = result
    var answer = number.match(/(\d)\1*/g)
    return console.log(answer);
}

repeatnumber([[10, 2][11,1]])// DOESN'T WORK!! output must be: 1010,11
repeatnumber([[1, 2], [2, 3]]) //works
repeatnumber([[1, 4], [3, 6], [9, 2]]) //works

Upvotes: 0

Views: 197

Answers (9)

Redu
Redu

Reputation: 26161

Single pass by nested template literals and .reduce() working hand to hand.

var a = [[10, 2], [11,1]],
    b = [[1, 2], [2, 3]],
    c = [[1, 4], [3, 6], [9, 2]],
    f = a => a.reduce((r,[v,c],i) => `${i ? `${r},`:``}${`${v}`.repeat(c)}`,``);

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

Upvotes: 0

Gaurav Gandhi
Gaurav Gandhi

Reputation: 3201

Small code that works,

// iterate > create array and join with char > join parent array with comma

function repeatnumber(data){
    if(!data || data.length < 1) return [];

  return data.map(arr => Array(arr[1] + 1).join(arr[0])).join(','); 
}

A better approach, thanks to Ariz

function repeatnumber(data) {
    if (!data || data.length < 1) return [];

    return data.map((arr) => `${arr[0]}`.repeat(arr[1])).join(',');
}

No creation of an extra array, so huge repetitions can be done with ease.

Upvotes: 0

arizafar
arizafar

Reputation: 3122

If you are using es6 this could be the simplest.


let repeatnumber = (inputArr) => {
  return inputArr.map((inp) => `${inp[0]}`.repeat(inp[1]));
}

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

You are missing a comma between two arrays, make it

repeatnumber([[10, 2],[11,1]])

Also, your regex won't work properly when you are adding two digit number, change your logic as

function repeatnumber(data) 
{
    var answer = [];
    for (var i = 0; i < data.length; i++)
    {
        if (Array.isArray(data[i]))
        {
            var x = data[i][0]
            var y = data[i][1]
            result = "";
            for(var j = 1; j <= y; j++)
            {
                  result = result + x;
            }
            answer.push(result)
        }
    }

    return answer;
}

Demo

function repeatnumber(data) {
  var answer = [];
  for (var i = 0; i < data.length; i++) {
    if (Array.isArray(data[i])) {
      var x = data[i][0]
      var y = data[i][1]
      result = "";
      for (var j = 1; j <= y; j++) {
        result = result + x;
      }
      answer.push(result)
    }
  }

  return answer;
}
console.log(repeatnumber([
  [10, 2],
  [11, 1]
])) ;

console.log(repeatnumber([
  [1, 2],
  [2, 3]
])) ;

console.log(repeatnumber([
  [1, 4],
  [3, 6],
  [9, 2]
])) ;

Edit

Or a more concise method using fill and reduce

function repeatnumber(data) 
{
    return data.map( s => Array( s[1] ).fill( "" ).reduce( (a,c) => a + s[ 0 ], "" ) )
}

Or using fill and join

function repeatnumber(data) 
{
    return data.map( s => Array( s[1] + 1 ).fill( "" ).join( s[ 0 ] ) )
}

Upvotes: 0

Cristian S.
Cristian S.

Reputation: 973

ES6 Solution

const repeat = (arr) => {
  arr.map( v => {
    const str = new Array(v[1] + 1).join(v[0]);
    console.log(str); // save this in array or wherever u want.
  })
};

repeat([[1, 4], [3, 6], [9, 2]])

Upvotes: 0

user9384488
user9384488

Reputation:

try this :

function repeatnumber(data) {

var result = "";

for (var i = 0; i < data.length; i++)
{
    if (Array.isArray(data[i]))
    {
        var x = data[i][0]
        var y = data[i][1]


        for(var j = 1; j <= y; j++)
          {

            {
              result = result + x;
            }

          }
    }
    if(i != data.length - 1)
       result += " ";
}

 var number = result
 var split = number.split(" ");
 //var answer = number.match(/(\d)\1*/g)
 return console.log(split);
}

repeatnumber([[10, 2][11,1]]) should be repeatnumber([[10, 2],[11,1]]);

Upvotes: 0

Andrew
Andrew

Reputation: 7545

As you've noticed, regex isn't the best option. You're making the question a lot more difficult than it needs to be. You can just make an array of each of those strings and then join them together. Also, more descriptive variable names will go a long way for you.

let data = [[10,2], [11,1]]
function repeatNumber(data) {
 let resultArray = []    
  for (let i=0; i < data.length; i++) {
    let num = data[i][0]
    let times = data[i][1]
    let newString = ""
    for (let j=0; j < times; j++) {
      newString += num
    }
    resultArray.push(newString)
  }
  return resultArray.join(", ")
}

console.log(repeatNumber(data))

If you're ok with a code golf solution, this will accomplish the same task:

data.map(([num, times]) => Array(times).fill(num).join("")).join(", ")

Upvotes: 0

fyasir
fyasir

Reputation: 2970

Here's one of the solution.

function repeatNumber(data) {
var results = '';
data.forEach(function(arr) {
    for(var i = 0; i< arr[1]; i++) results += arr[0].toString();
  results += ',';
})
return results.substring(0, results.length - 1);
}
console.log(repeatNumber([[10, 2], [11,1]]));
console.log(repeatNumber([[1, 2], [2, 3]]));
console.log(repeatNumber([[1, 4], [3, 6], [9, 2]]));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You could check if you got a nested array and map new values and join later all arrays with comma.

function repeatnumber(array) {
    return (Array.isArray(array[0]) ? array : [array])
        .map(([value, length]) => Array.from({ length }, _ => value).join(''))
        .join(', ');
}

console.log(repeatnumber([42, 7]));
console.log(repeatnumber([[10, 2], [11,1]]));
console.log(repeatnumber([[1, 2], [2, 3]]));
console.log(repeatnumber([[1, 4], [3, 6], [9, 2]]));

Upvotes: 2

Related Questions