javascripthtml5-canvas

how to I find the Right most value in a linear matrix?


this is JavaScript in HTML using 2d context

If I have a linear matrix, how do I find the right most value? Currently I'm guessing my way around Wave function collapse and I need to add boundaries when they are checking their neighbors. but what I want to know is how to check the position to the right exist?

//3 columns and rows
var DIM = 3;

//30 pixels wide
var size = 30;

//making an empty array for matrix
var matrix = [];

//filling in the matrix with identifier for drawing
for(let i=0; i<DIM*DIM; i++)
{
   matrix[i] = 0;
};

//checking the neighbors
//gonna add more rules later
//i have more indetifier other than 1 and 0
//id like to add rules like a 1 can only have 2 or 5 above it
for(let i=0; i<DIM*DIM; i++)
{
   let cell = grid[i];
   //if the neighbor is null ignore
   let aboveCell = null;
   let belowCell = null;
   let rightCell = null;
   let leftCell = null;

   //Boundaries
   if(i <= DIM)
      aboveCell = matrix[i-DIM];

   if(i <= grid.length-DIM)
      belowCell = matrix[i+DIM];

   if(i % DIM != 0)
      leftCell = matrix[i-1];

   //HERE IS WHERE I WANT TO KNOW HOW TO CHECK THAT IT DOESNT HAVE A RIGHT NEIGHBOR

}

//this draws the matrix on the canvas
function draw()
{
  //running through the matrix to draw the tiles in the right spot
  for(let x=0; x<DIM; x++)
  {
     for(let y=0; y<DIM; y++)
     {
         if(matrix[x+(y*DIM)] == 0)
         {
            ctx.fillStyle= "black";
            ctx.fillRect(x*size, y*size, size, size);
         }
         if(matrix[x+(y*DIM)] == 1)
         {
            ctx.fillStyle= "white";
            ctx.fillRect(x*size, y*size, size, size);
         }
      };
   };


}

I've tried a few equations(made by me) but clearly the haven't worked


Solution

  • You can check if the remainder of the global index per the width of the matrix is equal to the width minus one:

    const WIDTH = 30;
    // By default an ImageData is such a flat "matrix".
    const img = new ImageData(WIDTH, 50);
    // But its initial Uint8 buffer gives us access to
    // the 4 channels of each RGBA pixel.
    // Using an Uint32 view each index represents a full pixel,
    // matching OP's situation.
    const data = new Uint32Array(img.data.buffer);
    
    for (let i = 0; i<data.length; i++) {
      data[i] = i % WIDTH === WIDTH - 1
        ? 0xFFFF00FF // Right-most: purple
        : Math.random() * 0xFFFFFF + 0xFF000000; // random
    }
    
    document.querySelector("canvas").getContext("2d").putImageData(img, 0, 0);
    canvas {
      width: 300px;
      height: 500px;
      image-rendering: pixelated;
    }
    <canvas width="30" height="50"></canvas>