How to make each element of a number array multiply each of its digits within a substring?

Asked

Viewed 119 times

2

I came from Python and am trying to create a function whose goal is to calculate the largest product for a continuous substring of digits of length N. Ex: for the '102181952' input, the largest product for a 3-digit series is 90 (9 * 5 * 2)

I tried to create two loops with for (array[i][j]) equal in Python, but I was unsuccessful. The most I’ve managed so far is to at least create an array of substrings. I tried to use map and reduce, but I was not successful, probably because I do not know how to handle the functions well, although I have read the Documents and researched extensively here in English and Portuguese.

So far what I’ve been able to do, and I don’t think it’ll even do any good was just:

// Ainda não coloquei dentro de uma function(numero, tamanho) 
// para fins de monitoramento.

var numero = '123456789';
var tamanho = 3;
var listaNumeros = [ ];

for (var i = 0; i < numero.length; i += tamanho) {
    listaNumeros.push(numero.substr(i, tamanho));
};

console.log(listaNumeros); // [ '123', '456', '789' ]

Could someone at least point me in the right direction for the solution? I’m simply blank, I can’t think of anything else. Thank you very much!

1 answer

2


A path not worrying about validations and this is a minimal example:

var numero = '102181952';
var tamanho = 3;
var listaNumeros = [];

for (var i = 0; i < numero.length; i += tamanho) {
  let s = 1;
  const n = numero.substr(i, tamanho);
  for(var j = 0; j < n.length; j++) {
    s *= parseInt(n[j]);
  }
  listaNumeros.push({n, s});
};

console.log('Resultado:')
console.log(listaNumeros.sort(function(a,b) { return b.s - a.s })[0]);
console.log('Item gerados:')
console.log(listaNumeros);

as wanted the highest value was executed a sort from the largest to the smallest and indicated the first position, as said is a basic example that can help you create a much better example.

  • 1

    This is a great start for me, I will see if I can perfect it. I thank you immensely.

  • 1

    Just one more request, cajo be possible: I’m still in the transition of learning to use Arrow functions appropriately, so I tried to do a 'reverse engineering' with yours, but I couldn’t. Can you tell me what the 'normal' of listaNumeros.sort((a,b) => b.s - a.s)[0]? In case I tried listaNumeros.sort(function(a, b) {return (b.s - a.s)[0]}); and the code runs, but it doesn’t work as intended. Thank you very much, and excuse me.

  • 1

    Mudar is in the reply @Alecsandercamilo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.