Jonathan Joseph
Jonathan Joseph

Reputation: 29

Find the largest sequence of five numbers in a string in Javascript

HI everyone hopefully an easy one. I have split a string example below in to 5 digit blocks I now need to find the largest 5 number sequence, and not sure how to do this any help much appreciated. "731671765313306249192251196744265747423553491949349698352036854250632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895

function solution(digits){


let output =  digits.match(/.{1,5}/g);
console.log(output);

}

Upvotes: -1

Views: 345

Answers (1)

trincot
trincot

Reputation: 350756

This approach (of splitting into chunks of 5), will not always give the optimal result, as you are not looking at every possible chunk of 5... only those that start at an index that is a multiple of 5.

So just iterate through every array index, and then take 5 characters from there, and compare...

let str = "731671765313306249192251196744265747423553491949349698352036854250632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895";

let best = "";
for (let i = 5; i <= str.length; i++) {
    let slice = str.slice(i - 5, i);
    if (slice > best) best = slice;
}

console.log(best);

Upvotes: 3

Related Questions