Search code examples
javamathmultidimensional-arrayprocessingpixel

Get twodimensional array positions out of integer


I am loading pixels out of an image. for every pixel I check the color and create an image, I now want to add this image inside of an two dimensional array.

int MAPWIDTH = 64; // in pixels
int MAPHEIGHT = 16; // in pixel
PImage[][] forGroundMap;

PImage file = loadImage(path);


file.loadPixels();
   
   int size = file.width * file.height;
   
   for (int i = 0; i < size; i++) {

    int y = divideBy(i, MAPWIDTH);

    //forGroundMap[y][x] == something what is x and y here
   }

For reference: The images are always 64 in height and 32 in width.

To get the position I have tried to divide the current iteration by the width to know what row I am currently at.

int divideBy(int number, int timesIn) {
int count = 0;

while (number >= timesIn) {
    number = number - timesIn;
    count++;
    println(number);
}

return count;

}

This however doesn't give me back the column inside my row And I am not sure if this will work at all and how to continue forward.


Solution

  • What you appears to be wanting is simple division math.

    int y = 1 / 64;
    System.out.println (y);
    y = 65 / 64;
    System.out.println (y);
    

    edit

    To get the x value as well use modulo

    int x = 1 / 64;
    int y = 1 % 64;
    System.out.printf ("you are at [%d,%d]%n", x,y);
    x = 65 / 64;
    y = 65 % 64;
    System.out.printf ("you are at [%d,%d]%n", x,y);