Guide to making a matrix as outlined in the instructions


Is there an algorithm to create a matrix with the following output format?
1, 3, 5, 7, 9
2, 4, 6, 8, 10
11, 13, 15, 17, 19
20, 22, 24, 26, 28
I'm particularly interested in a JavaScript solution, but what I need most is the algorithm itself.
Thank you.
I attempted this approach:

let arr = [];

for(let i = 0; i < 2; i++){
  arr[i] = []
  for(let j = 0; j < 5; j++){
    if(j % 2 ==0){
      arr[j] = i
    }
  }
}

console.log(arr)

Answer №1

Upon observation, it is evident that a common digit 2 is added each time once the starting point is fixed. I have identified two starting points: one at even at 2 and another at odd at 1. In every iteration, both values are incremented by 2 and appended to the final output after adding them to the respective arrays (evenArray and

oddArray).</p>

<p>It is important to remember to <code>reset
the evenArray and oddArray after each inner loop iteration.

let even = 2;
let odd = 1;
let arr = [];

for(let i = 0; i < 2; i++){
  let evenArr = []
  let oddArr = []
  for(let j = 0; j < 5; j++){
    evenArr[j] = even;
    oddArr[j] = odd;
    even +=2;
    odd +=2;
  }
  even = (even-2) * 2;  
  arr.push(oddArr.join(' '),evenArr.join(' '))
}

console.log(arr)

Answer №2

Begin by understanding the building rule

                          row   start  comment
---- ---- ---- ---- ---- ------ ------ -------------------
  1    3    5    7    9   odd      1
  2    4    6    8   10   even     2
 11   13   15   17   19   odd     10   requires adjustment
 20   22   24   26   28   even    20

Next, form an array with the specified rows and populate it with values. Alternate the starting value for each line between 2 and 5, based on the index of the row.

For each row, take the initial value, make adjustments for numbers that are not even or odd, and then add double the inner index.

var array = Array.from(
        { length: 4 },
        (start => (_, i) => Array.from(
            { length: 5 },
            (v => (_, j) => v + (v % 2 === i % 2) + j * 2)
            (start *= (i % 2 ? 2 : 5))
        ))
        (0.2)
    );

console.log(array.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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 there a way to retrieve all the items from the array?

I've been on the hunt for this information but unfortunately, I haven't found a satisfactory answer yet. Currently, I am utilizing Json encode to transfer my array to JavaScript: In PHP while($row = mysql_fetch_assoc($select)) { $event_day = $ ...

How can the 'selected' attribute be assigned to 'select/option' tags depending on the option value?

In my code, I have a select input with various options and values. I want to set the 'selected' attribute for the option that corresponds to a specific value X. Here is an example: // If x=3, I want the option with value=3 to be marked as 's ...

Having trouble decoding the stream image into a fragment

I am encountering an issue with the Permission Denied error even though I have added READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions to the Android Manifest. Any suggestions on how to resolve this? I have already attempted the solution mention ...

Discovering the largest value within an array comprising multiple lists using Scala

Having an array of lists works like this: val myArray = Array( List(1, "120", "a"), List(3, "97", "v"), List(7, "110", "d") ) The goal is to identify the array element with the highest second element. I can achieve this by running: myArray.maxBy(_(1).to ...

Tips for sending a form using ajax in Safari browser within a Grails framework

I am attempting to use an ajax function to submit a form when the button is clicked, however, in Safari browser it submits the form like a normal form submission. In other browsers, it works correctly with the ajax function. <g:form action="addEmpHis ...

Welcome to the Kickme command in Discord.js!

I am attempting to create a command that enables any user to trigger the !kickme command, which will result in them being kicked from the server. Additionally, I want the command to send a direct message to the user who initiated it. However, I am facing ...

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

What is the most effective way to retrieve the children and ID of an item in the jQuery Nestable plugin following a drag-and-drop action,

I'm currently implementing the jQuery Nestable plugin to build a menu editor for a website. After users click on menu items and rearrange their positions, I need to retrieve the item's ID and its Children.   Challenge: I'm struggling with ...

Prototype/PHP AJAX is experiencing a problem where two separate AJAX processes are hanging until the first one is completed

Following up on my previous question, I have set up my page to initiate an ajax call for processing records. After each record is processed, a row in another table is updated to track the status of the process. Following the initial ajax call, there is ano ...

The functionality of one button triggering the opening of two dropdown menus simultaneously is being successfully implemented

My issue is that I have created two different dropdowns, but they both open the same dropdown menu. Here is my code; <div class="d-flex"> <button class="btn btn-icon btn-group-nav shadow-sm btn-secondary dropdown-toggle" type="butto ...

What is the best method for transferring HTML tables to Excel with multiple tabs?

I have created a code that exports an HTML table into an Excel file. However, I now need to export multiple HTML tables into different tabs within a single Excel file. Here is the current code: Currently, when I click "Export To Excel," the Excel file is d ...

Displaying error message if the size of the uploaded file surpasses the maxRequestLength limit

In the web.config file, I have set the maximum request length to 10240 and execution timeout to 30: <httpRuntime maxRequestLength="10240" executionTimeout="30" /> Using valum's AjaxUpload plugin on the client side, I encountered an issue with ...

What is the most efficient way to transfer a string to a python program using ajax and retrieve a string in return?

I'm experiencing a problem with my ajax request where I am sending an object to a python program using JSON: $.ajax({ url: "http://localhost/cgi-bin/python.cgi", type: "POST", data: JSON.stringify(myobject), dataType: ...

Using JQuery's div.show() function is causing the fields on my page to resize

I am facing an issue with a hide div that is supposed to show when a checkbox is clicked. The problem I'm encountering is that when the div shows up, the height of the input fields becomes too small. Here is the structure of my div: <div id=" ...

Unable to view image when using material-ui CardMedia component

Hello, I've encountered a problem with rendering an image in my application. Let me explain the issue in a simplified manner. So, I have a card component (MyCardComponent) where I need to pass a string prop containing the image file location. The goa ...

Encountering an error with Angular-NG8001 due to an unknown element. Any suggestions on how

I am encountering an issue with my Angular project. The project structure I am working with can be found here: app structure. Within my app.module.ts file, the code appears as follows: import { NgModule } from '@angular/core'; import { BrowserMod ...

Display jqgrid with borders and insert extra headers text at the top of the grid

function generateTableWithText(){ $("#active_grid").jqGrid("exportToHtml",{ includeLabels : true, includeGroupHeader : true, includeFooter: true, autoPrint : true ...

Efficient method to generate a sorted array from a pre-sorted array of elements in C++

Is there an alternative method to create a sorted array of member variables from a sorted array of custom objects in C++? For example, consider the following: class People{ public: //Could potentially contain multiple parameters. What are the possible ...

I am having trouble with the browser detection not accurately identifying the browser I am currently using

Currently, I am working on a JavaScript code that will simply display the name of the browser being used to view the web page. Despite me using Safari, none of the navigators seem to recognize it as the current browser. The information displayed in my brow ...

Transform the string by eliminating any spaces and new lines before converting it into a JSON object

I need assistance with converting the given string into a JSON object. Here is the string: {\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": ...