C++ - Variable Decrement

89 Views Asked by At

Heys.

I have this code, which sets a table for some mystery reason. Size is 6x60. Which means SIZEY defined as 6, and SIZEX as 60.

void set_table(char** table)
{
    int i,j,k=0;

    for(i=0;i<SIZEY;i+=3){
        for(j=0;j<SIZEX;j++){
            switch(k++%5){
                case 0:
                    table[i][j]='|';
                    break;
                case 1:
                    table[i][j]=' ';
                    break;
                case 2:
                    table[i][j]=(char)((((k-2)/50)%10)+48);
                    break;
                case 3:
                    table[i][j]=(char)((((k-3)/5)%10)+48);
                    break;
                case 4:
                    table[i][j]=' ';
                    break;
                default:
                    continue;
            }
        }
    }
}

I am doing this with 3 variables, as you can see. Question is, can i do that with 2 variables, or even with only 1 ?

Thanks in advance.

1

There are 1 best solutions below

0
On

Here's a simplification for you:

    switch(k++%5){
        case 0:
            table[i][j]='|';
            break;
        case 1:
        case 4:
            table[i][j]=' ';
            break;
        case 2:
        case 3:
            table[i][j]= '0';
            break;
        default:
            continue;
  }

With C++, one case can fall into another, such as with cases 1 and 2 above.

Your expressions for case 2 and 3 can be simplified. I'll use case 2 as an example:
((((k-2)/50)%10)+48)
Substituting 2 for k yields
((((2-2)/50)%10)+48)
Simplify:
((((0)/50)%10)+48)
Zero divided by anything is zero, simplifying again:
(((0)%10)+48)
Zero mod anything is zero, since it involves division:
((0)+48)
Simplifying:
(48)
Replacing with the equivalent character (since your array is char):
'0'