Having trouble with my approach to Project Euler #8, it seems to have stopped working

After tackling a challenging problem online, I successfully discovered the largest product of any 5 consecutive numbers within a 1000-digit number:

        var bignumber = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749303589072962904915604407723907138105158593079608667017242712188399879790879227492190169972088809377665727333010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145358866881164271714799244429282308634656748139191231628245861786645835912456652947654568284891288314260769004224219022671055626317761111093705442175069416589604080719840385096241334462981230987879927244283625438";
    var bigarray = bignumber.split("");
    var prod = [];
    var buy = 1;
    var z = 4;
    for (var i = 0; i < bigarray.length; i+=z) {
      mult = bigarray[i];
      for (var x = 1; x <= z; x++) {
        mult *= bigarray[i+x];
      }
      prod.push(mult);
    }
    prod.sort(function(a, b){return b-a});
    document.write(prod[0]);

Fascinated by my discovery, I posted about it here, realizing later that this intriguing problem originated from Project Euler. Curious to explore further, I visited the official page here. It puzzled me that when I attempted to adjust the consecutive digits to 13 instead of 5 by changing z to 12, the solution was incorrect. Why did this modification lead to an unexpected outcome?

Answer №1

The error lies in this specific portion of code:

for (var i = 0; i < bigarray.length; i+=z) {
:

  1. To rectify the issue, adjust the loop condition to i < bigarray.length - z. This modification is necessary because the inner loop progresses up to z indices, so the outer loop must ensure that there are at least z elements remaining from index i.

  2. Furthermore, modify the loop increment to i+=1. The rationale behind this adjustment is illustrated by considering the task of identifying the largest product of two successive digits in the input "1221". Your current algorithm calculates 1*2 = 2 and 2*1 = 2, while the correct solution should be 2*2 = 4, which can only be achieved by examining each input digit as a potential starting point.

After implementing these changes, you have the opportunity to optimize your algorithm further. One approach involves leveraging the mult value from the previous iteration.

Answer №2

Below are the steps you can take:

function calculateMaxProduct(s,n){
  return Math.max(...s.split("")
                      .map((_,i,a) => a.slice(i,i+n))
                      .slice(0,s.length-n+1)
                      .map(subArray => subArray.reduce((prev,curr) => +prev * +curr)));
}

var bigNum = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330100533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
console.log(calculateMaxProduct(bigNum,13));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to implement a "load more" feature with JSON data using the getJSON method?

Currently, I am working on the task of extracting objects from a JSON file and arranging them in a grid layout similar to masonry using Salvattore. While I successfully utilized this helpful tutorial to retrieve the data, my next challenge is to implement ...

What is the best method for changing color using an HTML input with type=color?

I'm currently working on a project that involves user interaction with a canvas. I have an interface set up where users can click on shapes that are filled with a color, and the input color value should update to match the color of the selected shape. ...

What method is most effective for duplicating objects in Angular 2?

Is it just me, or does Angular 1.x have methods on the global angular object like angular.copy and angular.shallowCopy that are missing in Angular 2? It seems like there is no equivalent version in Angular 2 documentation. If Angular 2 doesn't plan on ...

The emission from Socket.io is originating from the recipient's browser without being transmitted to the sender's browser

Hey there, I'm fairly new to socket.io and not completely sure if what I'm doing is the standard way, but everything seems to be working fine so I guess it's okay. I've been working on a chat application where messages are stored in a d ...

Upon upgrading to Angular 8, the function this._delegate.setNgStyle is not recognized

Following the update of my project from Angular 7 to Angular 8 and resolving all errors caused by breaking changes, I am encountering a new issue: <div fxFill ngStyle.xs="overflow:auto"> This line is resulting in the following error: ERROR Type ...

Is there a way to retrieve the transaction specifics for the initial 50 clients from a MongoDB database?

In my PC's local server, there is a cluster with approximately 240,000 entries of transaction data. The abbreviation Cust_ID represents Customer ID. https://i.sstatic.net/5g65l.png Each file contains transactions made by different customers, with a ...

Enclose every line of the paragraph within a <span> element

My <div> element is configured to display a paragraph without any line breaks, similar to the example below: <div> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dum ...

Tips on extracting information from an AJAX call using JQuery

My current project involves utilizing a webapi in asp.net that outputs JSON data. I am looking to integrate this webapi with JQuery within a php-created website. The following is the JQuery code I am using to retrieve information from the webapi: $.ajax( ...

How to Retrieve the Text Content of a Button When Clicked in a Button Group Handler

My goal is to create two button groups. When a button in the second group is clicked, I want to dynamically add a new button to the first group with the same label as the clicked button. Using var name = this.textContent works well when the click handler ...

Issue with passing parameter to ASP.NET MVC Controller results in null value being received

I am facing an issue with the parameter clientId in my ASP.NET MVC Controller as it always seems to be null. I have found that I can only pass data successfully if I create a class, but this becomes cumbersome as I cannot create a class for every backend ...

The fitBounds() method in Google Maps API V3 is extremely helpful for adjusting

I am trying to display a map on my website using this code: function initialize() { var myOptions = { center: new google.maps.LatLng(45.4555729, 9.169236), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP, panControl: true, mapTyp ...

Scope isolation prevents variables from being accessed in higher levels of the scope chain

In my search for answers, I came across some similar questions on SO: Isolate scope variable is undefined unable to access rootscope var in directive scope However, my question presents a unique scenario. I am facing an issue with a directive that has a ...

Is there a way to convert a character array of digits representing a whole number less than 100 into its corresponding word form in C programming?

I'm looking to develop a C program that prompts the user to input a number below 100 and then displays it in written form. For instance, if the input is '53', I want the output to be 'fifty three'. In case the input is equal to or ...

Implementing an inline cache for <script> tags that load AJAX content

Looking for a way to cache <script src> received through AJAX requests? Currently, each call attempts to load the src via AJAX by default. However, the issue is that this script remains constant throughout the session and only needs to be re-evaluate ...

Exploring the intricacies of using jquery text() with HTML Entities

I am having difficulty grasping the intricacies of the jquery text() function when used with HTML Entities. It appears that the text() function converts special HTML Entities back to regular characters. I am particularly uncertain about the behavior of thi ...

Divide a single array into several smaller arrays based on a specific condition

I am working with a 1D array of values, for example: ind = array([1,200,1999,2333,5000,....], dtype=int64) My goal is to split this array based on certain conditions. For instance, I want the first array to contain values less than 2000, and the nex ...

What is the reason for innerHTML not functioning properly when trying to include HTML?

Apologies for my poor English, but I am determined to solve this issue using HTML code. <body> <div id="booklist"> <?php include("../templates/nav.php"); ?> <div class="hero"> <?php include("../templates/aside.ph ...

Failed attempt to create a React project using TypeScript

Encountering a problem while using create-react-app with the typescript template, even though it worked previously. However, when attempting to use create-react-app without a template like JSX, everything sets up smoothly. The cause of this issue eludes me ...

Is there a way to send a Map object to a script file using EJS?

I am facing an issue with passing a Map object to my client-side code. I have successfully used EJS and JSON.stringify(...) in the past for arrays, but it doesn't seem to work for Maps. When I try to console.log(myMap.keys()), I receive the following ...

Displaying JSON data in VUE.js

I have created an API using Node.js where sending certain parameters results in a response with information about the same person but in different languages. I am struggling to present it as shown in the second example. This is how I currently receive the ...