Algorithm for Generating Cubes

My current task involves working with a dynamically generated array of cubes, each having its distinct position and color. These cubes are situated on a 5x5 field, where each cube is connected to at least one other cube. Now, I am looking to introduce a new "floating cube feature". This entails randomly incorporating a cube that does not have any other cube above or below it but remains connected to another cube on one side (refer to the image).

Here is the visual representation of what needs to be added: https://i.sstatic.net/ChFxS.png

Below is the array showcasing the cubes on the image:

var cube_arr = [{posX: -2, posY: 0, posZ: 1, color: "red", row: 1},
{posX: -2, posY: 1, posZ: 1, color: "red", row: 1},
{posX: -2, posY: 2, posZ: 1, color: "green", row: 1},
{posX: -2, posY: 3, posZ: 1, color: "purple", row: 1},
...
{posX: 2, posY: 2, posZ: 0, color: "yellow", row: 5}]

Answer №1

Testing this out can be difficult without visualization. It's important to test the code properly to ensure it works as expected.

The function randomFloatingCube takes in an array of cubes, as well as minimum and maximum values for posX and posZ to prevent the floating cube from being generated outside a specific area.

At the end of the randomFloatingCube function, a single random cube is returned. If you want all possible floating cubes, return the array floatingCubes instead.

If you try out the code, please let me know if it meets your expectations.

// Function to get a floating cube within a specified range
function randomFloatingCube(A, x0, x1, z0, z1){
  let floatingCubes = [];
  
  const B = A.sort((a, b) => b.posY - a.posY).filter((b) => b.posY > 0);
  
  for(let i=0; i<B.length; i++){
    const a = B[i];
    
    let adjacent = getAdjacentCubes(a.posY, a.posX, a.posZ);
    
    let candidates = adjacent.filter((c) => {
    
      if(c.posX < x0 && c.posX > x1 && c.posZ < z0 && c.posZ > z1){
        return false;
      }
      for(let j=0; j<A.length; j++){
        const b = A[j];
        
        if(b.posY >= c.posY - 1 && b.posY <= c.posY + 1 && c.posX == b.posX && c.posZ == b.posZ){
          return false;
          break;
        } else if(b.posY == c.posY && b.posZ == c.posZ && b.posX == c.posX) {
          return false;
          break;
        }
      }
      
      return true;
      
    });
    
    floatingCubes.push(...candidates);
  }

  return floatingCubes[ Math.round(Math.random() * (floatingCubes.length - 1)) ];
}

function getAdjacentCubes(posY, posX, posZ){
  let ret = [];
  
  [posX-1, posX+1].forEach((x)=>{
    ret.push({
      posY,
      posX: x,
      posZ
    });
  });
  [posZ-1, posZ+1].forEach((z)=>{
    ret.push({
      posY,
      posX,
      posZ: z
    });
  });

  return ret;
}

// Array of cube objects
var cube_arr = [{posX: -2, posY: 0, posZ: 1, color: "red", row: 1},
{posX: -2, posY: 1, posZ: 1, color: "red", row: 1},
{posX: -2, posY: 2, posZ: 1, color: "green", row: 1},
{posX: -2, posY: 3, posZ: 1, color: "purple", row: 1},
...

console.log(randomFloatingCube(cube_arr, -2, 2, -1, 2));

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

What is the best way to prevent clicking and scrolling on a webpage?

I have added a "more" button to the bottom left of my website to reveal a menu. Upon clicking the button, the plus sign changes to an x. I would like the page to disable click and scroll actions when the plus sign is clicked. <div class="dropup"> ...

Issues with AngularJS have arisen, as it is currently unable to recognize and access variables as needed

As a newcomer to web design and Angular, I am trying to replicate this example, where I consume a RESTful web service and use AngularJS to display the JSON data. However, I'm facing issues with my implementation. Here's how my main.jsp file look ...

Create a basic single page application with Node.js and Express

Currently, I am working on developing a web application utilizing Node.js for the Back End and HTML/CSS/JS for the Front End. My goal is to create a single page app using the Express framework. I am interested in building a single page application with ju ...

Sending all form input data to Ajax for GET request

Today, my goal is to iterate through each textbox with an ID of setting_value, set its name and value to a key-value array, and then send that data in an Ajax request. The problem I'm facing is that it only seems to be inspecting the first instance o ...

MUI React - Issue with changing SvgIcon color using override

Currently, I am utilizing MUI version 5 within a React project. My objective is to customize the icon color for the Error Alert by using General StylesOverrides. Although I successfully altered the color on the Alert component, I am unable to discover a ...

Searching in binary for the number closest to the target float value

Seeking assistance with a float array conundrum! I am trying to identify the closest float value to a target number within the array. My attempt involved utilizing a basic binary search algorithm in JavaScript, but I've hit a roadblock. function bina ...

Leveraging Vue 3 Composition API with accessors

I'm currently in the process of refactoring some of my components using the composition API. One component is giving me trouble, specifically with asynchronous state when trying to retrieve data from one of its getters. Initially, the component was u ...

Submitting information in a Node.js application

I'm encountering an issue with posting data from an HTML file to my Node app. Here's the relevant code snippets: <form method="post" action="localhost:3000/post"> <input name="user[name]" type="text"/> <button type="submit"& ...

Retrieving data from MySQL through AJAX does not yield any information

I have been following a tutorial from W3 schools on PHP and AJAX database. Majority of the content is working fine, however it seems that there is no data being retrieved from the MySQL database I created called "exercises" in the "exercisedb" database. B ...

Disconnection between client and server communications

Can communication between two entities be established in this scenario? For example, if a server receives a file upload and determines it is incorrect, can it send an event to the client? The client would then catch the event and manipulate the DOM to dis ...

Setting the default value in setState in React Native allows you to initialize state

const fetchData = async (key) => { try { const jsonData = await AsyncStorage.getItem(key) return jsonData != null ? JSON.parse(jsonData) : false; } catch(error) { console.log(error); } } useEffect ...

Utilize the inherited background color for a linear-gradient effect

Here is the code snippet I am working with: <label className={classes.trigger} htmlFor={uniqueId} ref={labelRef} style={{ background: val, borderColor: val }} /> This is the corresponding CSS: .trigger { display: block; posit ...

Turn on the text field when the enter key is pressed

I've searched online for solutions, but none of them have resolved my issue. Upon loading my page, I am able to successfully have my JS file select the first textfield. However, I am struggling with getting it to proceed to the next textfield when th ...

Tips for defining a distinct series of key-value pairs in typescript

Having experience with a different language where this was simple, I am finding it challenging to articulate a sequence of pairs: Each pair is made up of two basic elements (such as strings or numbers) Each element may appear multiple times within the lis ...

Arrange an array in JavaScript according to the value of its keys

I am looking to rearrange an array of Objects with status 'Pass' & 'Fail'. I want to move all Fail ones to the top and Pass ones to the bottom. Is there a specific array method that can help achieve this? let a = [ { name: 'x&apo ...

Learn how to send data from a MySQL server to a Node.js application using Socket.IO

I've been facing a challenge recently. I am attempting to listen for events from the @rodrigogs/my-sql events node package and then emit those events through socket-io to the react client. However, there seems to be a disconnect that I can't see ...

What is the process for validating dates using JavaScript?

I'm currently working on a birthday validation form using JavaScript and I'm facing some issues. For instance, the date 40/40/2012 should be considered invalid but no alert is being triggered. Here is the JavaScript code: function validateBirth ...

Numerous images with clickable features

Currently, I am in the process of designing a screen that will showcase around 50 toggle buttons to be displayed on a monitor within a building. My goal is to incorporate a variety of images as toggles to ensure they are easily visible and identifiable. I ...

The concept of JavaScript variable scope

I am working on a script that has a structure similar to this $(function(){ var someVariable; function doSomething(){ //need to figure out how to access someVariable here } $('#something').click(function(){ //need to figur ...

Creating multiple instances of an object

When using Javascript, I am trying to create an object in the following way: var testObject = { value: "this is my initial value", setup: function() { value: "foo" } }; Now, my goal is to instantiate this object and have different val ...