Determining the total of each sub-array with a size of k in a given array by employing the sliding window technique

Is it possible to calculate the sum of all k-sized sub-arrays in an array using a sliding window algorithm? Is this approach valid, and if not, what are the reasons behind it?

var sumOfSubArrays = function(arr, k) {
    let currentSubArray = 0;
    for(let i=0; i<k; i++) {
        currentSubArray += arr[i];
    }

    let sum = currentSubArray;

    for(let i=0; i<arr.length-k; i++) {
    sum += currentSubArray - arr[i] + arr[i+k];
    currentSubArray = currentSubArray - arr[i] + arr[i+k];
    }

    return sum;
};

let arr = [1,2,3,4,5]
let k = 3;

console.log(sumOfSubArrays(arr, k));

Expected output should be 27

Answer ā„–1

Upon examining your code, I noticed that it implements the window sliding algorithm, albeit in a slightly different manner than what I am accustomed to. Personally, I would adjust the movement of the "window" by starting from the last visited index instead of going from the 0 index twice.

The main variation lies in how we handle moving "the tail" - while you add the value of 'k', I prefer to subtract it.

If I were to implement this, my approach would look like this:

// This is an O(n) solution for finding the sum of all k-sized sub-arrays within an array of size k using the window sliding algorithm
function sumOfSubArrays(arr, k) {
    let arrayLength = arr.length;
    let sum = 0;
    let finalSum = 0;
    
    // Calculate the initial sum of the first k elements
    for (let i = 0; i < k; i++) {
        sum += arr[i];
        finalSum = sum;
    }
    
    // Iterate through the array and increment the right edge
    for (let i = k; i < arrayLength; i++) {
        // Move the "window" to the next element 
        sum += arr[i] - arr[i - k];

        // Add the sum of the new sub-array to finalSum
        finalSum += sum;
    }
    
    return finalSum;
}

let arr = [1, 2, 3, 4, 5]
let k = 3;

console.log(sumOfSubArrays(arr, k));

Answer ā„–2

When dealing with the array, keep reducing it until the index is less than the specified value k. Simply add the current number to both the total and subTotal. Then, calculate the new value for newSubTotal by adding the current number to the previous sum while removing the first number used in creating the initial subTotal. Finally, combine the newSubTotal with the total to obtain the updated total.

const findSumOfSubArrays = (arr, k) =>
  arr.reduce(([total, subTotal], n, i) => {
    if(i < k) return [total + n, subTotal + n];
    
    const newSubTotal = subTotal + n - arr[i - k];
    
    return [total + newSubTotal, newSubTotal]
  }, [0, 0])[0];

const inputArray = [1, 2, 3, 4, 5];
const windowSize = 3;

console.log(findSumOfSubArrays(inputArray, windowSize));

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 feasible to utilize the draw_buffer extensions in THREE.js?

Trying to work on a project using THREE.js, but needing to utilize the draw_buffers extensions. After extensive searching, I have come up empty-handed in finding a solution to directly implement the draw_buffers extension. UPDATE Is there a way to use the ...

What is the best method to include numpy array or float values in an AWS API response?

Is it possible to get a numpy ndarray in the response of an AWS REST API? Are there any other supported formats besides JSON for the API response? ...

JavaScript - Endless State Loop - Panning Operation

I am currently immersing myself in the book "Pro HTML5 Games" authored by Aditya Ravi Shankar during my leisure time. One particular line of code that I am struggling to comprehend is as follows: var deltaX = Math.round((newCenter - game.offsetLeft - gam ...

The array subscript cannot be of type `int[int]`

While attempting to compile the following code, I encountered an error on the specified line: "Invalid types `int[int]' for array subscript " Code: template<typename T> class Stack { private: static const int GROW_FACTOR = ...

Adjusting Specific Time for Jquery to Change Date if Less Than X Value

Creating a carousel to display featured content for Friday nights. Initially, upon loading the page, I automatically trigger a click to show the upcoming Friday night's content based on the current date and time using new Date(). However, our clients ...

Executing a C# function from an HTML hyperlink

I am in the process of developing a website using ASP.NET C#. The site will feature a GridView with data that can be exported, such as to Excel or other formats. To handle the export functionality, I plan to utilize code from this resource. When a user c ...

Angular Material's input field is not correctly binding to localeString

I'm currently utilizing Angular Material 11.2, and I have a specific need to convert the inputted string into US dollars format. My attempts so far include: <input matInput formControlName="test" (onkeyup)="onKeyUpTest($event)" ...

Do not try to render objects as a React child. If you intended to display a group of children, make sure to use an array instead

I am encountering difficulty in accessing the required data from an array, and consistently receiving this error message: Objects are not permissible as a React child (found: object with keys {id, name, country, logo, flag, season, standings}). If you ...

lua update/swap 2D array

I'm facing an issue with my array2d. I am looking to implement a refresh command in my code. The data is stored in data.txt test1:30:1 test2:40:2 Whenever I call the ReadData function, it should populate my Array2d like this : line_data = {{"test1 ...

I could really use some assistance with this script I'm working on that involves using ($

Using Ajax for Form Submission: $.ajax({ url: 'process.php', type: 'post', data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(), dataType: 'json', success: func ...

Is it possible for search engines to crawl and index specific pages within a web application that is powered by

I have created a web application with a dynamic JavaScript interface that communicates with the server through AJAX requests. The content of the page is determined by the data after the hashtag in the URL, which is fetched from the server and displayed acc ...

Submit a form to transfer information to a different page, authenticate the data, and finally submit it

Within my form, After the user clicks on Submit, they will be redirected to another page displaying all the entered data for verification purposes. This allows the user to ensure the accuracy of their input before proceeding. Once verified, the user can ...

Redis appears to be missing the expected results

After following an express demo which involved storing and retrieving values with Redis, I attempted to implement the code in my own Express app. However, I encountered issues as the req.online variable was returning null when I tried to retrieve its lengt ...

Issue with three.js: animations not playing when changing characters

Hello everyone, I am new to this. I managed to load an .fbx character along with additional animation clips from Mixamo. My goal is to have the animations switch when a key ("Q") is clicked. Currently, the character loads and plays the first animation clip ...

Locating the position of data within an array using PHP

Looking for the whereabouts of names in a PHP array? Meet my array: $array = Array("Name1","Name2","Name3","Name4","Name5"); Your mission: Find the position of these names within the array. I'm after 0 for Name1 and 2 for Name3. Any bright ideas ...

Resolving the issue of "Mixed Active Content" CORS error detection

When using Firefox, if JavaScript tries to make a Cross-Origin Request (CORS) to an http server from a page hosted on https, an error is thrown: Blocked loading mixed active content I am trying to capture these errors, but I'm having trouble. For ex ...

Is there a better method to organize an Array of Objects?

Greetings my fellow developers, Iā€™m looking to rearrange the Array of objects (array1) to match the order provided in array2. As you can see, array2 is a simple array with values that correspond to key names in array1, making it the reference for organi ...

set a value to a global array within a function

After writing the following javascript code: <script language="javascript" type="text/javascript"> var name = new Array(); var i = 0; function doSomething() { name[i] = "a"; alert(name[i]); i++; } < ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

Utilizing Express middleware to serve routes in Sails.js

I am currently working on a sails app where the routes and static assets are served from the root location, which is functioning properly. However, I am looking to integrate an express middleware to serve these routes and assets from a specific path. To s ...