Divide a two-dimensional array into square sections and calculate the total of the highest value in each section using Javascript

I am trying to divide a matrix into square regions of specified dimensions (k) starting from the upper left corner and then calculate the sum of the maximum value in each region. Here is my progress so far.

arr = [
  [ 0, 8, 1, 1, 10, 6 ],
  [ 6, 8, 7, 0, 3, 9],
  [ 0, 7, 6, 8, 6, 5],
  [ 4, 0, 2, 7, 2, 0],
  [ 4, 4, 5, 7, 5, 1]
], l = console.log, j = JSON.stringify

result = [0, 3].map(i => arr.map(a => a.slice(i, i+3)))  // mapping over indexes to split by for segmenting

l(j(result ))

I am not very experienced with javascript but I am eager to learn. Any assistance would be greatly appreciated.

Answer №1

While this solution may seem a bit complex, it is indeed functional. It aims to extract a specific region from the given data, but will adjust accordingly if the desired region size is not available. For example, in our case, it divides the array into two regions of 3x3 and two regions of 2x3. (Please note: this method will fail if all elements in the region are less than -100. To make it work in such cases, you need to modify the value of 'runningMax' as needed)

function getMaxValue(arr){
    var runningMax = -100;
    for(var i = 0; i < arr.length; i++) {
        runningMax = Math.max.apply(null, arr[i].concat(runningMax));
    }
    return runningMax;
}

var arr = [
      [0, 8, 1, 1, 10, 6],
      [6, 8, 7, 0, 3, 9],
      [0, 7, 6, 8, 6, 5],
      [4, 0, 2, 7, 2, 0],
      [4, 4, 5, 7, 5, 1]
    ];

var result = [0, 3].map(function(i) {
    return arr.map(function(a) {
        return a.slice(i, i + 3);
    });
});

var finalResult = [0, 3].map(function(i) {
    return result.map(function(a) {
        return a.slice(i, i + 3);
    });
});

var sum = 0;
finalResult.forEach(function(e){
    e.forEach(function(q){
        sum += getMaxValue(q);
    })
});

console.log(sum);

Answer №2

You can divide your matrix into regions by utilizing the reduce() and forEach() methods

const arr = [
    [0, 8, 1, 1, 10, 6],
    [6, 8, 7, 0, 3, 9],
    [0, 7, 6, 8, 6, 5],
    [4, 0, 2, 7, 2, 0],
    [4, 4, 5, 7, 5, 1]
  ], l = console.log, j = JSON.stringify

function splitMatrix(data, n) {
  let row = 0;
  return data.reduce(function(r, a, i) {
    if (i && i % n == 0) row++;
    let col = 0;
    a.forEach(function(e, j) {
      if (j && j % n == 0) col++;
      if (!r[row]) r[row] = [];
      if (!r[row][col]) r[row][col] = [];
      r[row][col].push(e)
    })
    return r;
  }, [])
}

const s = splitMatrix(arr, 3);
console.log(j(s))

To determine the maximum value of each region, you can achieve that within the forEach loop and then utilize reduce() to sum up those values.

const arr = [
    [0, 8, 1, 1, 10, 6],
    [6, 8, 7, 0, 3, 9],
    [0, 7, 6, 8, 6, 5],
    [4, 0, 2, 7, 2, 0],
    [4, 4, 5, 7, 5, 1]
  ], l = console.log, j = JSON.stringify

function splitMatrix(data, n) {
  let row = 0;
  return data.reduce(function(r, a, i) {
    if (i && i % n == 0) row++;
    let col = 0;
    a.forEach(function(e, j) {
      if (j && j % n == 0) col++;
      if (!r[row]) r[row] = [];
      if (!r[row][col]) r[row][col] = [e];
      if (r[row][col][0] < e) r[row][col][0] = e;
    })
    return r;
  }, [])
}

const max = splitMatrix(arr, 3)
const result = [].concat(...max).reduce((r, [e]) => r + e, 0);
console.log(j(max))
console.log(result)

Answer №3

When considering the example given, where the array is 6x5, it becomes evident that splitting it evenly into square regions is not possible. However, this detail is somewhat tangential to the main issue at hand. The first imperative step in approaching the problem is to devise a function capable of extracting and summing up a specific section of a matrix.

Imagine having a matrix and the need for a function that can take parameters such as x, y, width, and height to determine the area requiring summation:

const m = [
 [1,2,3,4,5],
 [2,3,4,5,6],
 [3,4,5,6,7],
 [8,9,10,11,12]
];

const sumArea = (m, x, y, w, h) => {
  let sum = 0;
  
  if (y + h > m.length) {
    throw new Error('Matrix is not tall enough for the requested area');
  }
  
  if (x + w > m[0].length) {
    throw new Error('Matrix is not wide enough for the request area');
  }
  
  for (let j = y; j < y + h; j++) {
    for (let i = x; i < x + w; i++) {
      sum += m[j][i];
    }
  }
  
  return sum;
}

console.log(sumArea(m, 0, 0, 3, 3));

This function allows traversal through any specified region within a matrix and calculates the total sum within that area. By utilizing a `for` loop from the initial point (x, y) to the final point (x + width, y + height), this task is efficiently accomplished.

An added precaution includes boundary checks to ensure the area remains within the matrix dimensions; otherwise, an error is thrown. Alternatively, you could choose to treat out-of-bounds areas as zeroes and proceed without interruption by incorporating conditions within the `for` loop.

Subsequently, to calculate the squares of all values, a straightforward iteration process is employed.

const m = [
 [1,2,3,4],
 [2,3,4,5],
 [3,4,5,6],
 [8,9,10,11]
];

const sumArea = (m, x, y, w, h) => {
  let sum = 0;
  
  if (y + h > m.length) {
    throw new Error('Matrix is not tall enough for the requested area');
  }
  
  if (x + w > m[0].length) {
    throw new Error('Matrix is not wide enough for the request area');
  }
  
  for (let j = y; j < y + h; j++) {
    for (let i = x; i < x + w; i++) {
      sum += m[j][i];
    }
  }
  
  return sum;
}

const sumSquares = (m, w, h) => {
  let result = [];
  
  for (let y = 0; y < m.length / h; y++) {
    result[y] = [];
    
    for (let x = 0; x < m[0].length / w; x++) {
      result[y][x] = sumArea(m, x * w, y * h, w, h);
    }
  }
  
  return result;
}

console.log(sumSquares(m, 2, 2));

This particular approach involves iterating through each square segment within the matrix. The number of squares corresponds to the size of the matrix divided by the width of each square. For instance, in a 4x4 matrix with 2x2 squares, there would be 2 squares across and down respectively. These values are then collated into another matrix to showcase their cumulative sum.

Answer №4

    
const myArray = [
  [ 10, 5, 8, 4, 7, 1 ],
  [ 3, 7, 2, 9, 6, 0],
  [ 5, 4, 7, 1, 3, 6],
  [ 8, 2, 4, 6, 9, 5],
  [ 1, 6, 3, 4, 7, 1]
];

const sizeX = 3, sizeY = 3;

// Iterating through squares
for(let startX = 0; startX < myArray.length - sizeX; startX++){
  for(let startY = 0; startY < myArray[0].length - sizeY; startY++){
     // Finding the sum of elements in each square
     let sum = 0;
     for(let x = startX; x < startX + sizeX; x++)
        for(let y = startY; y < startY + sizeY;  y++)
            sum += myArray[x][y];
      // Performing operations with the sum
      console.log(sum)
   }
}

Answer №5

When working with arrays of the same length and height, it's possible to iterate through the arrays and extract the indices for grouping and counting purposes.

var array = [[0, 8, 1, 1, 10, 6], [6, 8, 7, 0, 3, 9], [0, 7, 6, 8, 6, 5], [4, 0, 2, 7, 2, 0], [4, 4, 5, 7, 5, 1], [0, 1, 0, 1, 0, 1]],
    result = array.reduce((r, a, i) => {
        a.forEach((b, j) => {
            r[Math.floor(i / 3)] = r[Math.floor(i / 3)] || [];
            r[Math.floor(i / 3)][Math.floor(j / 3)] = (r[Math.floor(i / 3)][Math.floor(j / 3)] || 0) + b;
        });
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №6

It seems like your goal is to analyze all the possible 3x3 sub-matrices within the provided matrix. To clarify, in your matrix example, you are interested in examining:

[ 0, 8, 1 ]    [ 8, 1, 1 ]    [ 1, 1, 10]    [ 1, 10, 6 ]
[ 6, 8, 7 ]    [ 8, 7, 0 ]    [ 7, 0, 3 ]    [ 0, 3, 9 ]
[ 0, 7, 6 ]    [ 7, 6, 8 ]    [ 6, 8, 6 ]    [ 8, 6, 5 ]

[ 6, 8, 7 ]    [ 8, 7, 0 ]    [ 7, 0, 3 ]    [ 0, 3, 9 ]
[ 0, 7, 6 ]    [ 7, 6, 8 ]    [ 6, 8, 6 ]    [ 8, 6, 5 ]
[ 4, 0, 2 ]    [ 0, 2, 7 ]    [ 2, 7, 2 ]    [ 7, 2, 0 ]

[ 0, 7, 6 ]    [ 7, 6, 8 ]    [ 6, 8, 6 ]    [ 8, 6, 5]
[ 4, 0, 2 ]    [ 0, 2, 7 ]    [ 2, 7, 2 ]    [ 7, 2, 0]
[ 4, 4, 5 ]    [ 4, 5, 7 ]    [ 5, 7, 5 ]    [ 7, 5, 1]

Your objective appears to be identifying the maximum values (12 maximums for 12 matrices):

8    8   10   10

8    8    8    9

7    8    8    8

The total sum of these maxima is 100. If this outcome aligns with your expectations, below is a functional approach to compute it:

const arr = [
  [ 0, 8, 1, 1, 10, 6 ],
  [ 6, 8, 7, 0, 3, 9],
  [ 0, 7, 6, 8, 6, 5],
  [ 4, 0, 2, 7, 2, 0],
  [ 4, 4, 5, 7, 5, 1]
];

const sum = arr.slice(2).reduce( 
    (sum, row, i) => row.slice(2).reduce( 
        (sum, a, j) => sum + Math.max(...arr[i].slice(j,j+3), 
                                      ...arr[i+1].slice(j,j+3), 
                                      ...row.slice(j,j+3)),
        sum
    ), 0
)

console.log(sum);

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

Include all the items from the directory into the array in the form of an object

https://i.sstatic.net/48gCi.png I am currently dealing with a file structure similar to the one shown in the image, and I have code that reads folders content as follows: var array = [] fs.readdir(__dirname + '/static/katalogi', function (err ...

Comparing Phone Applications: Cloud Storage versus Local Storage

My current project involves developing applications using JavaScript along with Adobe PhoneGap for cross-platform integration. I have encountered an architectural dilemma when it comes to storing application data and could use some advice. One of my apps ...

How can I generate two directory-based slider instances?

Update: Finally, I discovered the root of the problem within my stylesheet. Despite both sliders being loaded, they were overlapping due to their positioning, causing the second slider (or any additional ones) to remain hidden. I've been striving to ...

What is the best way to automatically create a PDF file that includes interactive JavaScript charts?

My goal is to create a word document or PDF containing charts from various JavaScript chart libraries. I've successfully implemented these libraries on websites, but now I want to include them in my documents as well. My initial attempt involved usin ...

What is the process for a developer to utilize Ajax in order to send and receive numerous requests across multiple div elements simultaneously?

I have created a page where I implement an Ajax post request to a PHP file and receive a response as shown below. <input type="hidden" id="qid" value ="2" /> <div id="scores"></div> <sc ...

Combining user input with React's useState function

I have a form with three Quantity inputs. (Although more can be added dynamically, let's keep it simple for now and stick to three.) | - | - | Quantity | |---|---|----------| | - | - | 3 | | - | - | 4 | | - | - | 5 | Now, I want ...

Having trouble dynamically inserting a row into a Jquery datatable

When working with jQuery Datatable, I am currently involved in two main functions: Filtering and searching the table based on select tags. Dynamically adding rows to the datatable using Ajax. However, when adding a row dynamically, the row count increase ...

Mastering Backbone - Incorporating JSON information with backbone

I am currently in the initial stages of transitioning my application to the backbone framework. One of the tasks involves handling data that is fetched as JSON from an ajax call. {f1:"f1_value", f2:"f2_value", f3:"f3_value"}, {f1:"f1_value", f2:"f2_value ...

Is there a way to shut down a browser tab without being asked, "Are you sure you want to close this window"?

Is there a way to gracefully close a browser window without being interrupted by the annoying Do you want to close this window prompt? I've noticed that whenever I attempt to use the window.close(); function, this prompt always pops up. ...

javascript + react - managing state with a combination of different variable types

In my React application, I have this piece of code where the variable items is expected to be an array based on the interface. However, in the initial state, it is set as null because I need it to be initialized that way. I could have used ?Array in the i ...

Display four unique automobile insignias using Webcomponent/Stencil.js

Exploring Web Components and Stencil.js for the first time, I'm currently developing an application that offers detailed car information based on the user's selection of car type. The challenge I'm facing involves displaying four different l ...

Discover the Power of Node.js with the @aws-sdk/client-s3 Package, Leveraging AWS CLI Credentials Stored in

A Nodejs project has been set up with media files stored in an S3 Bucket and utilizing the @aws-sdk/client-s3 as the AWS SDK Client. The project consists of two important files, namely .env and S3Bucket.js. The content of .env (located in the root directo ...

Using jquery to toggle the visibility of input fields

I'm encountering an issue with this straightforward code snippet: $("#additional-room").hide(); var numAdd = 0; $("#add-room").click(function(e) { e.preventDefault(); $("#additional-room").show(""); if (numAdd >= 3) return; numAd ...

Aligning the menu links to the right on a horizontal CSS menu

I have created a horizontal menu using CSS and HTML with the following code: .nav > li:hover { background: #666666; text-decoration:none; } .active { background: #666666; text-decoration:none; } nav, ul, li, a { margin: 0; paddi ...

Current time must be before the scheduled date

Currently, I am utilizing Joi in conjunction with express for request validation. Specifically, I am focusing on validating the date field within the request body. The code snippet I have implemented is as follows: const dateSchema = Joi.date().greater(Dat ...

Tips for dividing and locating the final index in Google Sheets

Is there a way to accomplish this in Google Sheets? tag_name A_B_C C A_B_C_D D I have been using the following formula: =INDEX(SPLIT(B2, "__"), 0, 3) My goal is to automatically select the last index of the values returned by the split fu ...

Can an in-progress NPM package be tested using NPX?

I am currently developing an NPM package that is designed to be used exclusively through npx *, similar to packages like create-nuxt-app. Is there a method to test my package using npx *? Essentially, I want to run my bin script without actually installin ...

Array fed with Mongoose query

Currently experiencing challenges with a section of my code. I am utilizing Mongoose to retrieve data from my database, where I intend to push a portion of that data into an array titled 'authors' for further manipulation. Although I am able to ...

The combination of subtracted geometries creates unusual lighting effects

When working with three.js, I have been experimenting with the concept of cutting out a window from a box geometry, which represents a wall. I came across a helpful csg (constructive solid geometry) extension on this GitHub repository. After successfully ...

What is the best method for accessing JSONArray elements in JSP?

The JSONArray I have is as follows: [ {"id":1, "programs_idprograms":3, "description":"course description", "idCourse":"course title" }, {"id":2, "programs_idprograms":3, "description":"course description2", "idCourse":"co ...