Spinning a rectangular grid with JavaScript

I am currently developing my own version of Tetris. My main focus at the moment is creating a function that can rotate a 2D variable array by 90 degrees (or -90).

For instance, if we have an array like:

"-T-",
"TTT"

The expected output should be:

"T-",
"TT",
"T-"

I attempted to implement this using the following function:

function rotateN90(a){
    var temp = [];
    for(var x = 0; x<a[0].length; x++){
        temp.push("");
        for(var y = 0; y<a.length; y++){
            temp[x] += a[y][x];
        }
    }
    
    return temp;
}

However, the current function is not producing the desired outcome. It does rotate the initial T-Block example by -90 degrees once, but then reverts back to its original orientation.

I would greatly appreciate any assistance with this problem!

(PS: I am working within KA's processing environment and do not have access to libraries or ES6 features.)

Answer №1

This particular snippet of code demonstrates how to rotate an array of size mxn by -90 degrees.

function rotateNegative90(array){

 var temp = new Array(array[0].length); // number of columns
 var i=0;

 for (i = 0; i < temp.length; i++) { 
     temp[i] = [];
 } 

 for(i=0;i<array.length;i++){
    
     for(let j = 0; j<array[0].length;j++){

         temp[j][i]= array[i][array[i].length-1-j];
     }
 }

 return temp;
}

For example, if your input array is: [[1, 2,3],[4, 5, 6]]

After rotating it by -90 degrees, the resulting array will be: [[3, 6],[2, 5],[1, 4]]

Answer №2

class Array2D extends Array {
  constructor(width, height, array) {
    super();
    this.width = width;
    this.height = height;
    for(let i = 0; i < width*height; i++) {
      this[i] = array ? array[i]:0;
    }
  }
  set(x, y, value) {
    this[x+y*this.width] = value;
  }
  get(x, y) {
    return this[x+y*this.width];
  }
  static swap(array2d) {
    const result = new Array2D(array2d.height, array2d.width);
    for(let x = 0; x < array2d.width; x++) {
      for(let y = 0; y < array2d.height; y++) {
        result.set(y, x, array2d.get(x, y));
      }
    }
    return result;
  }
  static flip(array2d) {
    const result = new Array2D(array2d.width, array2d.height);
    for(let x = 0; x < array2d.width; x++) {
      for(let y = 0; y < array2d.height; y++) {
        result.set(x, array2d.height-1-y, array2d.get(x, y));
      }
    }
    return result;
  }
  static spin(array2d) {
    const swapped = Array2D.swap(array2d);
    return Array2D.flip(swapped);
  }
}

const a2d = new Array2D(2, 2, [1, 1, 1, 0]);
console.log(Array2D.spin(Array2D.spin(a2d)));

This solution has been slightly modified for better clarity and organization.

// Code implementation with functions instead of classes (due to restrictions)
function create2D(width, height, array) {
  var arr = [];
  arr.width = width;
  arr.height = height;
  for(var i = 0; i < width*height; i++) {
    arr[i] = array ? array[i]:0;
  }
  return arr;
}

function set(array, x, y, value) {
  array[x+y*array.width] = value;
}

function get(array, x, y) {
  return array[x+y*array.width];
}

function swap(array2d) {
  var result = create2D(array2d.height, array2d.width);
  for(var x = 0; x < array2d.width; x++) {
    for(var y = 0; y < array2d.height; y++) {
      set(result, y, x, get(array2d, x, y));
    }
  }
  return result;
}

function flip(array2d) {
  var result = create2D(array2d.width, array2d.height);
  for(var x = 0; x < array2d.width; x++) {
    for(var y = 0; y < array2d.height; y++) {
      set(result, x, array2d.height-1-y, get(array2d, x, y));
    }
  }
  return result;
}

function spin(array2d) {
  return flip(swap(array2d));
}

var a1 = create2D(2, 2, [1, 1, 1, 0]);
var a2 = spin(spin(a1));

console.log(a2);

Answer №3

This solution is versatile and can handle rotations of both 90 degrees and -90 degrees.
A truthy value in the left parameter will rotate it by -90 degrees.
A falsey value in the left parameter will rotate it by +90 degrees.

//1 to rotate left, 0 to rotate right
function rotate(arr,left){
  var newArr=[]
  arr.forEach(function(a){newArr.push(a.toString())})
  arr=newArr //we gonna do some wild stuff so this is to not mess with the original array given to function
  arr=arr.map(function(a){return a.split``})
  var newArr=new Array(arr[0].length)
  for(var i=0;i<newArr.length;i++){newArr[i]=[]}
  arr.forEach(function(a,i){
    a.forEach(function(b,j){
      newArr[j][i]=b
    })
  })
  if(left){
    newArr=newArr.map(function(a){return a.join``})
    return(newArr)
  }
  //else(right)
  newArr.map(function(a){a.reverse()})
  newArr=newArr.map(function(a){a.join``})
  return(newArr)
}

//example 1 (-90 degrees)
console.log("example 1(-90 degrees)",rotate(["-T-","TTT"],1))
//same example but you can use truthy or falsy values not JUST 1 or 0
console.log("example 1(-90 degrees) with another truthy value",rotate(["-T-","TTT"],{a:true}))

//example 2(+90 degrees)
console.log("example 2(+90 degrees)",rotate(["-T-","TTT"],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

Transform the words in a string into an array

I'm scratching my head trying to find a solution on Stack Overflow, but nothing seems like the right fit. Can anyone provide some guidance? I need a regex that will enable me to use JavaScript split to break a string into an array. The test case is: ...

Resolving CORS issues: Troubleshooting communication between a React app and an Express server

After successfully running both the app and server locally, I encountered an issue upon deploying the express server. Whenever I try to make a request, I consistently receive the following error message: "has been blocked by CORS policy: Response to ...

Is it possible to swap out images using srcset attribute?

Currently, I am facing an issue regarding changing the img on mobile and tablet devices to display different images. As a beginner with jQuery, I couldn't resolve it using that framework, so I am exploring options with html5. I am wondering if there ...

Vue.js - experiencing issues with conditional styling not functioning as expected

Can someone help me with an issue I'm having? I've created a button with a heart symbol that is supposed to change color when clicked, but it's not working as expected. This is my current code: <template> <button v-bind: ...

Issues with the HTML required attribute not functioning properly are encountered within the form when it is

I am encountering an issue with my modal form. When I click the button that has onclick="regpatient()", the required field validation works, but in the console, it shows that the data was submitted via POST due to my onclick function. How can I resolve thi ...

Activate a module within a Vuex action only upon dispatching

Is there a way to import a package for use in a Vuex Action only when the Action is dispatched, in order to reduce the size of my entry bundle? Here's what I've tried: export const actions = { async createNewBin(store, bin) { const fireba ...

"Within the node.js framework, the search/query section of the URL appears

I am currently working on a website (client + server) that both operate from the same machine. Despite not encountering any issues in Chrome's developer tools, I am struggling to identify the source of a problem. My dilemma is with trying to POST a s ...

Creating an Active Link in Bootstrap 5.0 (Beta 3) Navbar Using JavaScript

I am currently working with Bootstrap 5 (Beta 3 - no JQuery) on a static website, and I am facing the challenge of making a navbar link appear active. I prefer to achieve this using JavaScript instead of creating a separate navbar for each page. For instan ...

Exploding a key value pair and grouping matching key values into one key - here's how to do it!

I have encountered a practical issue recently while working on ajax form submission. There are checkboxes involved and I need all checkboxes with the same name to be stored as key value pairs. For example, if there are 4 checkboxes with the name attribute ...

I'm having trouble getting the JADE tag to render in Express script. Can anyone help me

I am trying to include client-side script in my JADE template and so far I have: extends layout script. function collect_data() { var transitions = {}; $( ":checkbox:checked" ).each(function (index, element) { //// some code ...

Exploring the mechanics of an Ajax call

Feeling a little lost in the call flow of Ajax - can anyone provide some guidance? This is my HTML: <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="myFunction()">Change Content</but ...

The behavior of Quasar's q-drawer is quite unpredictable

Having made the transition from Vue.js 2 with Vuetify to Vue.js 3 with Quasar due to Vuetify not officially supporting Vue.js 3 yet, I am utilizing q-drawer and its mini property. This allows me to toggle between the mini state and the normal expanded stat ...

I can only use innerHTML once in my React application

I am attempting to clear my container div when the user clicks the search button in order to remove all existing search results. However, I am encountering an issue where using innerHTML to clear the container div only works the first time. If a second sea ...

What is the best way to implement a JavaScript pattern matching for both "aaaa" and "aaa aaa"?

Can anyone help me create a pattern that can accept both strings with spaces and without spaces in the same text box? I would appreciate any guidance on how to achieve this. Thanks! ...

Tips for hiding a soft keyboard with jQuery

Here is a text button: <input type="text" class="field" id="something" name="something" placeholder="text" autofocus /> I want to prevent the android soft keyboard from popping up and keep the focus on this field. I only want to do this for this ...

Getting the checkbox count value in a treeview upon successful completion of an AJAX request

After successful JSON Ajax response, a treeview structure with checkboxes is displayed. I need to capture the number of checkboxes checked when the save button is clicked. @model MedeilMVC_CLOUD.Models.UserView <script type="text/javascript"> ...

The Vue v-on:click event listener seems to be unresponsive when applied to a

I've been attempting to utilize the on-click directive within a component, but for some reason, it doesn't seem to be functioning. Whenever I click on the component, nothing happens, even though I should see 'test clicked' in the consol ...

Show information from an array

On the index.php page, there is a script that retrieves data from demo.php and presents the outcome in a div. <div class="leftbox"> <?php echo "<div id='proddisplay'>"; echo "</div>"; ?> </div&g ...

Ways to navigate to a new webpage in JavaScript without the need to click on a link

After going through various posts and trying different methods, I am still facing challenges. In a PHP page, I have an HTML form with an onClick command that triggers a JavaScript validation procedure when the user clicks a button. While everything funct ...

Bringing joy to a JS library: Embracing both Node and the Window

I have developed a JS library that I want to convert into a Node module for use with Node.js. This library extends the Canvas context API and relies on the use of getImageData(). Therefore, it begins with a defensive check to ensure compatibility: if (wi ...