 # Convert Color image to greyscale coding challenge

Codewars coding challenge (Convert Color image to greyscale) instrucions

An array of size N x M represents pixels of an image. Each cell of this array contains an array of size 3 with the pixel’s color information: `[R,G,B]`

Convert the color image, into an average greyscale image.

The `[R,G,B]` array contains integers between 0 and 255 for each color.

To transform a color pixel into a greyscale pixel, average the values of that pixel:

``````p = [R,G,B] => [(R+G+B)/3, (R+G+B)/3, (R+G+B)/3]
``````

Note: the values for the pixel must be integers, therefore you should round floats to the nearest integer.

## Example

Here’s an example of a 2x2 image:

``````[
[ [123, 231, 12], [56, 43, 124] ],
[ [78, 152, 76], [64, 132, 200] ]
]
``````

Here’s the expected image after transformation:

``````[
[ [122, 122, 122], [74, 74, 74] ],
[ [102, 102, 102], [132, 132, 132] ]
]
``````

I have question. How can I loop through An array of size N x M. N is anonymous and M is anonymous !!!?

N and M can be determined by taking the supplied array and determining the length of the array (M… aka height of the image in the number of rows of pixels) and the length of a row (N… aka the number of pixels in each row).

So first thing is to find the length of the array and then the length of a row in that array (again which is also an array).

Just think of it is as a spreadsheet, that is the best way to think of it. The outer array is the number of rows, and the inner arrays are the number of columns. 1 Like

There are multiple ways to iterate/work with arrays in JavaScript

The basic code is to loop over the array with a standard for loop

``````const image = …. Your array here
for(let y=0; y<image.length; y++)
{
let row=image[y];
for(let x=0; x<row.length; x++)
{
let pixel=row[x];
let grayValue=Math.round((pixel+pixel+pixel)/3);
pixel=pixel=pixel=grayValue;
}
}
``````

A little more modern is the foreach loop

``````image.foreach(row =>
{
row.foreach(pixel =>
{
…. Same code as above
}
}
``````

The actual most used is the map function

``````let newImage = image.map(row =>
{
return row.map(pixel =>
{
let grayValue=Math.round((pixel+pixel+pixel)/3);
pixel=pixel=pixel=grayValue
return pixel;
}
}
``````
2 Likes

I would suggest in future not providing full answers when replying to topics about “How do I do this codewars challenge” immediately.

The challenge is for the person to create the code, not to scrape an answer off of an internet forum for codewars ‘points’ or whatever.

3 Likes

You are CORRECT !!!

I want to understand the challenge, have an answer for my question and get tips and hints.