Re: C Programming: A Modern Approach - Chapter 15 Exercise 5



Simon Morgan <me@xxxxxxxxxxx> writes:

> Hi,
>
> Does anybody have a solution or a hint for Exercise 5 of Chapter 15 of
> K.N. King's book C Programming: A Modern Approach? I spent all of
> yesterday evening staring at it and drooling. The author sure does have a
> knack for making me feel like a dumbass, or maybe it's just that I am.
>
> The following code pads out sentences with extra spaces between words so
> that each line takes up the same amount of space on screen. As is, the
> code will favour the end of the line when distributing the extra spaces.
> The task is to modify it so that it alternates between distribution of the
> extra spaces favouring the end of the line and the beginning of the line.
>
> void write_line(void)
> {
> int extra_spaces, spaces_to_insert, i, j;
>
> extra_spaces = MAX_LINE_LEN - line_len;
> for (i = 0; i < line_len; i++) {
> if (line[i] != ' ')
> putchar(line[i]);
> else {
> spaces_to_insert = extra_spaces / (num_words - 1);
> for (j = 1; j <= spaces_to_insert + 1; j++)
> putchar(' ');
> extra_spaces -= spaces_to_insert;
> num_words--;
> }
> }
> putchar('\n');
> }
>
> I cannot for the life of me figure out a solution beyond parsing the
> sentence first and adding the number of spaces to an array to be used when
> printing the sentence to screen, but this feels like an awful kludge. The
> closest I've come to a decent solution is to add extra_spaces % (num_words
> - 1) to spaces_to_insert but this results in the extra spaces not being
> distributed evenly.

What I think you want is, if the number of extra spaces is N, and the
number of separations (ie, 'num_words-1') is S, then there should be

N/S spaces between every word, and also
1 extra space at each of the N%S gaps at the
{beginning,end} of the line.

If the gap number is g, 0 <= g < num_words-1, then the expressions

g < extra_spaces%(num_words-1)

and

g + extra_spaces%(num_words-1) >= num_words-1

should, when added to extra_spaces/(num_words-1), give the number of
spaces that should be printed at each gap, for favoring the beginning
of the line and the end of the line respectively.
.



Relevant Pages