Within a lattice composed of variously hued cubes, how can one locate the corresponding clusters?

Explaining Clusters

A cluster is a group of cubes of the same color that are touching face planes, not their corners, forming a solid geometric shape.

To Aid in Visualization

Imagine each Lego piece to be 1x1 units in size.

https://i.sstatic.net/z9qFm.png

For instance, let's consider a 2x2x2 mesh composed of 1x1x1 cubes:

var mesh = [ 

  // First layer   ( x, y, z )
  new THREE.Vector3( 0, 0, 0 ),
  new THREE.Vector3( 0, 0, 1 ),
  new THREE.Vector3( 1, 0, 0 ),
  new THREE.Vector3( 1, 0, 1 )

  //Second layer   ( x, y, z )
  new THREE.Vector3( 0, 1, 0 ),
  new THREE.Vector3( 0, 1, 1 ),
  new THREE.Vector3( 1, 1, 0 ),
  new THREE.Vector3( 1, 1, 1 )
];

https://i.sstatic.net/7CCrT.jpg

Each cube within the mesh is assigned a color:

//Indexes of mesh array sorted by color
var colors = {
  red: [0, 1, 4, 6],
  green: [2, 3, 5, 7]
}

Answer №1

The solution to this problem lies in utilizing a technique called flood fill. The Wikipedia article provides comprehensive guidance for handling situations in two dimensions:

Flood-fill (node, target-color, replacement-color):
 1. If the target-color matches the replacement-color, stop.
 2. If the color of the current node does not match the target-color, do nothing.
 3. Change the color of the current node to the replacement-color.
 4. Apply Flood-fill (one step south of the node, target-color, replacement-color).
    Apply Flood-fill (one step north of the node, target-color, replacement-color).
    Apply Flood-fill (one step west of the node, target-color, replacement-color).
    Apply Flood-fill (one step east of the node, target-color, replacement-color).
 5. Finish.

To adapt this method to three dimensions, we can establish that two cells are considered adjacent if their separation is only 1. In simpler terms, if they differ by one dimension, you can navigate through all six neighboring cells rather than just four as in two-dimensional cases.

Answer №2

If you're looking for a practical demonstration on how to apply flood-fill to your mesh, check out my custom npm package n-dimensional-flood-fill:

// For a smoother approach, organize your mesh as nested arrays:
var mesh = [
  [
    // 0,0,0  0,0,1
    ["red", "red"],

    // 0,1,0  0,1,1
    ["red", "green"],
  ],
  [
    // 1,0,0  1,0,1
    ["green", "green"],

    // 1,1,0  1,1,1
    ["red", "green"]
  ]
];

var redFill = floodFill({
  getter: function (x, y, z) { return mesh[x][y][z] },
  seed: [0, 0, 0]
});

var greenFill = floodFill({
  getter: function (x, y, z) { return mesh[x][y][z] },
  seed: [1, 1, 1]
});

console.log("redFill: " + JSON.stringify(redFill.flooded));
// redFill: [[0,0,0],[0,1,0],[1,1,0],[0,0,1]]

console.log("greenFill: " + JSON.stringify(greenFill.flooded));
// greenFill: [[1,1,1],[1,0,1],[1,0,0],[0,1,1]]

If needed, you can customize the getter function to suit your mesh structure.

From the output, you can observe that floodFill should be executed separately for each region. To identify all regions within the mesh, you may run floodFill from various starting points, ensuring not to repeat coordinates already included in previous regions. While this method is effective, there are more advanced techniques for detecting all regions in a single iteration.

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

Form Validation behaving differently than anticipated

I have created a custom shopping cart system using PHP and implemented validation with JavaScript, but the validation process is not functioning as expected. Here is a snippet of my PHP script: $result = mysqli_query($conn, "SELECT * FROM products"); whi ...

Counting Slides in a Slick Carousel

I am currently working with the slick carousel in React.js using ES6 and I'm having trouble getting the slide count. In my function, I can successfully retrieve the count inside the event listener but outside it returns null. Can someone point out wha ...

Problem with RadioButton click event not triggering

Among my collection of RadioButton elements, there is an onclick event that should trigger. This event, named SecurityCheckedChanged, will display or hide other div containers (populated with RadioButton elements) based on the selected RadioButton. Howeve ...

Can anyone tell me the best way to access the name attribute of an HTML element in TypeScript?

Currently, my code is utilizing the name attribute to verify whether the user has entered information in a specific field and validating the input. However, I am facing an issue where the submit button remains active even if there are empty fields presen ...

Encountering a problem when trying to dynamically change the value in a dropdown menu with Angular.js

Having an issue where two drop down lists have the same value. When I set a value to the first drop down list, the second one also takes that value. Below is my code for reference: <div class="col-md-6"> <div class="input-group bmargindiv1 col-md ...

How can I create a rectangular border around text using the HTML5 canvas?

How can I dynamically draw fitted rectangles around text labels (person's full name) without fixed sizes, taking into account that the labels vary in lengths? Below is the code used to draw the text labels: var ctx = document.getElementById('ma ...

Updating the redux state in react by passing a variable from a child component to the parent

I'm currently in the process of updating my Redux state within a component by utilizing a variable that has been passed up to the component from a child, specifically through a form submission callback. The form is responsible for submitting a user&ap ...

sending ajax information to create a pie chart displaying data percentages

I am currently facing confusion on how to pass or assign a value of my data-percent pie chart through my ajax data retrieved from the database. While I have successfully passed other fields using an id, I am stuck on how to incorporate the value for data p ...

Create a new column in Material UI Grid by adding an empty div element instead of using padding

I'm currently getting acquainted with Material UI Grid and I am interested in adding an empty column (a blank space on the right of the first element) without utilizing padding. How can this be achieved? Here's a snippet of the code being discus ...

Question: How can I use the jQuery datepicker to ensure that the selected date remains in the

I recently created a webpage using a combination of HTML, PHP, and jQuery. The PHP script is designed to load all data where the date matches the one selected in the text input field generated by the jQuery datepicker. However, I encountered a problem whe ...

Unable to locate the value of the query string

I need help finding the query string value for the URL www.example.com/product?id=23 This is the code I am using: let myApp = angular.module('myApp', []); myApp.controller('test', ['$scope', '$location', '$ ...

Develop a duplication of the selected text without the need for the clipboard

Looking to implement an internal clipboard with a history feature for my application. Unfortunately, using the clipboard API will require user permission which is not feasible. I want to ensure that formatting such as bold, italics, and strikethrough is p ...

The json loader in three.js gets an upgrade post r71

I have been a long-time user of three.js, sticking with version r71 until recently. I upgraded to r76 and encountered a strange issue with the JSON loader. The onLoadComplete function is no longer being triggered, unless I use a simple function like beep ...

The unattractive visual outcome of Three.js rendering

My goal is to generate a 3D map of buildings using Three.js, based on a 2D SVG file. The process involves taking each path from the SVG, utilizing transformSVGPath from d3.js to create a shape, and then extruding it as shown below: var material = new THRE ...

Enhancing JavaScript Asynchronous Programming with EventLoop and async/await

Exploring the intricacies of how JavaScript processes asynchronous methods led me to dive into async/await. In an effort to gain a complete understanding, I crafted the following example: async function first() { console.log(9); await Promise.resolv ...

Assign a class to an element depending on its position using JavaScript/jQuery

<ul> <li>Apple</li> <li>Banana</li> <li>Orange</li> </ul> How can I use jQuery to add a class to the second li element in the list without using an existing class or id? ...

Selenium unable to interact with Javascript pop-up box

I am currently working on automating a feature for our web application, specifically a form of @mentioning similar to Facebook. On the front end, when a user types @ into a text input, the API is called to retrieve the list of users and display them in a b ...

Bug in canvas rendering for Chrome versions 94 and 95

The Canvas drawing functionality in the Chrome browser seems to have some visible bugs. Here's an example of code that demonstrates this issue: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d&apo ...

"Struggling with a basic Javascript function to refresh parts of a web page by calling a .php

After spending several hours browsing the internet, I am still struggling to get this straightforward example to function properly. Could someone please lend me a hand? My goal is to use JavaScript to display the contents of a PHP file. The display should ...

Assign Monday as the selected day of the week in the MUI Datepicker 6

I am currently using version 6 of the material ui Datepicker and I am trying to configure it so that the week starts on Monday. import React from "react"; import { DatePicker as DatePickerDestop } from "@mui/x-date-pickers/DatePicker"; ...