Monday, September 21, 2009

OOP344 Challenge 2

Our class was given the challenge "Modify io_display function to the shortest code possible."
After some brainstorming I was able to get each part of the function down to 1 line. The original code was:

void io_display(const char *str, int row, int col, int len){
io_move(row, col);
if(len <= 0){
io_putstr(str);
}
else{
int i;
for(i=0;i<len && str[i];i++){
io_putch(str[i]);
}
for(;i<len;i++){
io_putch(' ');
}
}
}

I moved the variable to the top since I was taking out the if else structure and left the io_move where it was since it was already only one line.
Then I turned the check for a len of 0 or less into a for loop that only executed if the length was less than 1 and had the io_putstr as an increment condition. This saved me 4 lines.
Then I basically just did the same thing for the other two for loops, making the output command part of the increment and closing the for with a semicolon instead of a set of braces. The final code is only 7 lines long compared to the original 15.
Were this a c++ program I could have made the int declaration part of the for loop bringing the line total down to 6 but since it's supposed to work as a standard c program that isn't an option.

Here is the final function.

void io_display(const char *str, int row, int col, int len){
int i;
io_move(row, col);
for(i=len; i <= 0;io_putstr(str),i=1);
for(i=0; i<len && str[i];io_putch(str[i]),i++);
for(;i<len;putch(' '),i++);
}

No comments:

Post a Comment