Display the matrix in a semi-spiral pattern

I am working with a 3 by 5 matrix, filled with numbers from 1, presented as follows:

 1  2  3  4  5
 6  7  8  9 10
11 12 13 14 15

The task is to print the values in a half-spiral order, starting from the bottom left vertically: 11 6 1 5 10 15 12 7 2 4 9 14 13 8 3.

After numerous attempts, I realize my current solution is too complicated. Even after 2 days of trying, I still can't figure out how to alternate between printing the opposing side columns.

var c = 0;
var i, j, k, l;
do {
  if (c == 0) {
    c++;
    for (j = 0; j < farm[0].length; j++) {
      for (i = farm.length - 1; i >= 0; i--)
        document.write(farm[i][j] + " ");
      break;
    }
  } else {
    c--;
    for (l = farm[0].length - 1; l >= 0 ; l++) {
      for (k = 0; k < farm.length; k++)
        document.write(farm[k][l] + " ");
      break;
    }
  }
} while (j < l);

Answer №1

To simplify the process of printing specific columns, consider creating a function dedicated to this task. This function can take an argument called dir to determine the direction in which the column should be printed.

const matrix = [[1,  2,  3,  4,  5],
 [6,  7,  8,  9, 10],
[11, 12, 13, 14, 15]];

function printColumn(matrix, column, direction){
  
  for(let i = 0; i < matrix.length; i++){
    let row = direction === 1 ? i : matrix.length - 1 - i;
    console.log(matrix[row][column]);
  }
}
for(let i = 0; i < Math.ceil(matrix[0].length)/2; i++){
  let col1 = i;
  let col2 = matrix[0].length - 1 - i;
  if(col1 !== col2){
    printColumn(matrix, col1, -1);
    printColumn(matrix, col2, 1);
  }
  else printColumn(matrix, col1);
}

Answer №2

const matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]];
const spiralOrder = arr => {
// determine the order in which columns should be followed, [0, 4, 1, 3, 2]
const columnsOrder = [...Array(arr[0].length)].map((val, index) => index % 2 === 0 ? index / 2 : arr[0].length - Math.ceil(index / 2));
// reverse the column of the matrix if its index is less than or equal to half of row length
return columnsOrder.reduce((accumulator, currentValue, currentIndex) => currentIndex % 2 === 0 ? accumulator.concat(arr.map(column => column[currentValue]).reverse()) : accumulator.concat(arr.map(column => column[currentValue])), []);
}
console.log(...spiralOrder(matrix));

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

In Internet Explorer 11, the Content-Type setting is not functional and may cause issues with certain functionalities

My initial attempt to solve the issue involved using the method beginQuoteFileUnquoteUpload1, which created a proper boundary and Content-Type. However, upon receiving the file, I discovered that it was corrupted :( var formData = new FormData(); formD ...

Identifying whether a webpage has integrated Google Analytics

I am working with a node server. I provide a Url in the request and utilize cherio to extract the contents. My current goal is to identify whether the webpage uses Google Analytics. How can I achieve this? request({uri: URL}, function(error, response, bod ...

Creating a Custom Class for a Custom Button in TinyMCE 4 Using addButton()

Is there a way to add a custom class to a custom button using the addButton() function in TinyMCE? Here is an example: editor.addButton('keywords', { text: 'Insert Keywords', class: 'MyCoolBtn', ...

Efficiently condense a sequence of ones and zeros into a more compact format, then effortlessly revert it back to the original sequence without any changes. Each time

I've been exploring different approaches in NodeJS and plain JavaScript to improve this task. Currently, I have developed some functions that count the repetition of characters, but I'm curious if there are more efficient methods or potential en ...

Add some text onto the Box Component in Material UI

I am looking to replicate the hover functionality (UI) seen in this example: Desired UI Source: Since adjusting background image styles can be complex, I have opted to use the Box Component from Material UI. Within the Box Component, I have implemented th ...

How to ensure a table in MaterialUI always maintains full width without requiring horizontal scrolling in CSS?

After attempting to allocate each widthPercent value on the TableHeader so they sum up to 100%, I am still experiencing the presence of a scroll bar. I have tried setting fixed widths for each column, but this results in excess space on the right side dep ...

Vue.js is displaying one less item

Recently I started working with Vuejs and encountered an unexpected issue in my application. The purpose of my app is to search for channels using the YouTube API and then display those channels in a list. However, when I try to render the list of subscri ...

Automatically populate select boxes with values from a different source using PHP

I'm in the process of setting up automatic population for 2 select boxes on a website. When a user chooses a class, the second select box automatically displays the main specialization of that class. If the user selects Tank (for example), the third ...

There seems to be a glitch preventing the Redis client from properly executing

Having some trouble with my Redis implementation in Node.js. Despite using async/await as recommended in the docs, I'm only seeing 'console log 1' being logged. Any ideas on what might be causing this issue? Any help or suggestions would be ...

Using DefaultSeo does not override NextSeo in every component

I am looking to dynamically change the Head tag using next-seo. While browser validation will show NEXTSeo for individual pages, Twitter, Firebase's card validation tool, and others will default to next-seo-config.js. Does anyone have a solution? S ...

Tips for creating read-only checkboxes with multipledropdown.js in Angular.js

I am trying to make all checkboxes in a multiple dropdown list readonly using Angular.js with the multipledropdown.js plugin. My code snippet is as follows: <div class="col-md-6" ng-show="sub_sub_menu"> <div class="input-group bmargindiv1 col-md- ...

Showing JSON information fetched from an AJAX request within an HTML page

I've been working on a project and I'm almost there with everything figured out. My main challenge now is to display an array of items on a web page after making an ajax call. Below is the code snippet I currently have: JQuery Code: var su ...

HTML5 Audio using AudioJS may not function reliably when loaded remotely

I have been encountering frustrating issues with loading audio tags for a while now. Despite spending nearly two weeks trying to solve the problems, every fix seems to create another one. My webpage includes an < audio > tag that utilizes audio.js t ...

Presentation comparing ng-show and ng-hide efficiency

Introduction:- There may be some who opt to use ng-show instead of ng-hide="!true", while others choose ng-hide over ng-show="!true". Technically, the ng-hide directive is not necessary. However, Angular introduced it for a standard coding structure. Plea ...

Security Error when using the JavaScript map function in FireFox

My current dilemma involves using a JavaScript code to extract the above-the-fold CSS from my websites. Surprisingly, it functions flawlessly on Google Chrome. However, when I attempt to execute it on Firefox, an infamous 'SecurityError' occurs: ...

Blurring isotopes within Google Chrome

While working with isotope in Google Chrome, I noticed that all items have the following CSS code: -webkit-transform: translate3d(properties); In Chrome, every even element [2,4,6,8,10,12,14...] appears blurred, whereas in Firefox everything looks normal ...

How can I incorporate a fade opacity effect into my Div scrolling feature?

I successfully implemented code to make div elements stick at the top with a 64px offset when scrolling. Now, I am trying to also make the opacity of these divs fade to 0 as they scroll. I am struggling to figure out how to achieve this effect. Below is ...

Looking for a script that automatically swaps out a div at set intervals? You'll need to tweak it so that it only

I created a js script that dynamically changes the content of certain div elements at specified intervals. While I appreciate how it functions, I now need to modify it so that the script only executes once. Can someone help me achieve this? <script typ ...

Trouble with sending input through Ajax in HTML form

I'm facing a dilemma that I can't solve. The issue arises from a page (index.php) that begins by opening a form, then includes another PHP page (indexsearch.php), and finally closes the form. The included page works with a script that displays d ...

Adding to object properties in Typescript

My goal is to dynamically generate an object: newData = { column1: "", column2: "", column3: "", ... columnN: "" } The column names are derived from another array of objects called tableColumns, which acts as a global variable: table ...