Search code examples
cswapcs50

PSET4 CS50 Reflect Assignment; Code is failing the tests


I can't find a way to fix these two errors despite my pic turns out fine. Would appreciate it if anyone can enlighten me.

This is the report I get:

:( reflect correctly filters 1x2 image
expected "0 0 255\n255 0...", not "255 0 0\n0 0 2..."

:) reflect correctly filters 1x3 image
:) reflect correctly filters image that is its own mirror image
:) reflect correctly filters 3x3 image
:( reflect correctly filters 4x4 image
expected "100 110 120\n7...", not "100 110 120\n4..."

And this is my code:

RGBTRIPLE tmp[width];
for (int i = 0; i < height; i++)
{
    for (int j = 0; j <= width / 2; j++)
    {
        tmp[j] = image[i][j];
        image[i][j] = image[i][width - 1 - j];
        image[i][width - 1 - j] = tmp[j];
    }
}
return;

Solution

  • Solution;

    Condition in the for loop needs a small tweak;

    j < width / 2
    

    Understanding why;

    For 1x2 image, you have 2 pixels in one row. Width is 2. Just 1 iteration is enough for this. In the old scenario, 1st iteration is executed when j=0. But then 2nd iteration is also executed because j=1 is still within the condition (equals to width/2). 2nd iteration is unnecessary. You are just reflecting twice which results in no change in the image.

    For 4x4 image, the similar issue. You should finish reflection with 2 iterations when j = 0, and when j = 1. However, when j = 2 (j is still equal and smaller than width/2), 3rd iteration is executed and replaces 3rd pixel with 1st pixel which is wrong. Because you had already replaced them once.