I'm teaching myself C and working through K&R. I'm doing exercise 1-21:
Write a Program entab that replaces strings of blanks by the minimum number of tabs and blanks to acheive the same spacing. Use the same tab stops as for detab.
I was having trouble doing this exercise so I found a solution online but I do not understand it. Can someone explain how this code works?
#include<stdio.h>
#define TABINC 8
int main(void)
{
int nb,nt,pos,c;
nb = 0;
nt = 0;
for(pos=1;(c=getchar())!=EOF;++pos)
if( c == ' ')
{
if((pos % TABINC) != 0)
++nb;
else
{
nb = 0;
++nt;
}
}
else
{
for( ; nt > 0 ; --nt)
putchar('\t');
if( c == '\t')
nb = 0;
else
for( ; nb > 0; --nb)
putchar(' ');
putchar(c);
if(c == '\n')
pos = 0;
else if ( c == '\t')
pos = pos + ( TABINC - (pos -1) % TABINC) - 1;
}
return 0;
}
The code is to
put a tab ('\t') when a space () is encountered at a position that is a multiple of TABINC, i.e, the size of the tab.
when a tab is encountered, the number of spaces is reset. This is to prefer a tab to reach a tabstop
To illustrate:
- a space shown in *
- a tab is shown in
column: 1 2 3 4 5 6 7 8 9 10
input : * * * * h e l * * w
output: <tab>hel<tab>*w
In this example, when a space is encountered at every column position which is divisible by the TABINC, i.e 4 (in this case), a tab '\t' is inserted. Otherwise space.
Hope this will give you some idea.
Related
Exercise 1-21 C Programming Language Kernighan
Please explain the final line.
#include <stdio.h>
#define TABINC 8
/* replace strings of blanks with tabs and blanks */
int main()
{
int c, nb, nt, pos;
nb = 0; /* number of blanks necessary */
nt = 0; /* number of tabs necessary */
for (pos = 1; (c = getchar()) != EOF; ++pos)
if (c == ' ') {
if (pos % TABINC != 0)
++nb; /* increment # of blanks */
else {
nb = 0; /* reset # of blanks */
++nt; /* one more tab */
}
} else {
for ( ; nt > 0 ; --nt)
putchar('\t') /* output tab(s) */
if (c == '\t') /* forget the blank(s) */
nb = 0;
else
for ( ; nb > 0; --nb)
putchar(' ');
putchar(c);
if (c == '\n')
pos = 0;
**else if (c == '\t')
pos = pos + (TABINC - (pos-1) % TABINC) - 1;
}
}**
I am having difficulties interpreting the final line . . . can you please explain how to decipher the arithmetic?
What does this mean?
else if (c == '\t')
pos = pos + (TABINC - (pos-1) % TABINC) - 1;
else if (c == '\t')
tests if the current character is a Tab character.
pos = pos + (TABINC - (pos-1) % TABINC) - 1;
calculates the next multiple of TABINC columns from the current pos column.
(pos-1) % TABINC is the number of characters between the last tab stop and the current position; e.g. if pos == 10, pos-1 is 9, and 9 % 8 is 1. The next tab stop is 16, which is 10 + (8 - 1) - 1.
I have a text file of combinations without repetition of 6 number ranging from 1 to 10, like this:
2 3 8 9 6 4
8 3 1 4 7 9
1 3 5 7 6 9
1 5 7 9 8 4
1 3 5 4 8 7
2 4 6 8 7 1
6 7 8 3 5 9
3 1 6 2 7 9
1 7 4 2 5 8
3 4 9 2 1 7
...
and I have a gold combination, let's say: 2, 1, 3, 9, 8, 5
I want to check how many times I have a combination in my text file that matches 5 numbers of the gold combination. This is my code attempt:
// Including C Standard Libraries
#include <stdint.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
// Gold Combination
int n1 = 2;
int n2 = 1;
int n3 = 3;
int n4 = 9;
int n5 = 8;
int n6 = 5;
// Numbers of Matching Combinations
int match_comb = 0;
// Creating a file to see combinations content
char ch, file_name[25];
FILE *fp;
fp = fopen("combinations.txt", "r"); // Read Mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
int j = 0;
int mn = 0; // Number of matched numbers
int x[6] = {0,0,0,0,0,0};
char c;
while((c = fgetc(fp)) != EOF)
{
if(c == ' ' || c == '\n')
{
}
else
{
x[j] = c;
if (j == 5)
{
if(x[0]==n1 || x[0]==n2 || x[0]==n3 || x[0]==n5 || x[0]==n6){
mn += 1;
}if(x[1]==n1 || x[1]==n2 || x[1]==n3 || x[1]==n5 || x[1]==n6){
mn += 1;
}if(x[2]==n1 || x[2]==n2 || x[2]==n3 || x[2]==n5 || x[2]==n6){
mn += 1;
}if(x[3]==n1 || x[3]==n2 || x[3]==n3 || x[3]==n5 || x[3]==n6){
mn += 1;
}if(x[4]==n1 || x[4]==n2 || x[4]==n3 || x[4]==n5 || x[4]==n6){
mn += 1;
}if(x[5]==n1 || x[5]==n2 || x[5]==n3 || x[5]==n5 || x[5]==n6){
mn += 1;
}
if ( mn == 5)
{
match_comb += 1; // Adding One the the Match Combinantions counter
}
for (int i = 0; i < 6; ++i) // Resetting x array
{
x[i] = 0;
}
mn = 0; // Resetting
j = -1; // Resetting j
}
j += 1;
}
}
printf("Number of Matching Combinations:");
printf("%d", match_comb);
printf("\n");
fclose(fp);
return 0;
}
But, I think the code is not working, because it always says that there are 0 matched combinations .. Are there ways to simplify or make my code work?
also, this only works for the case of numbers with one digit, but in the case I have bigger range, let's say 1-20, I am not really sure how to gather the numbers from the text file .. I was thinking in a condition where there was a counter after every space, if the counter is one, take the character as a number of one digit, if the counter is two, gather the two characters and do something to tell the code to gather the two characters and use the resulted number, but I don't know how to do that ..
Edit:
int main()
{
// Gold Combination
int n1 = 20;
int n2 = 1;
int n3 = 35;
int n4 = 9;
int n5 = 18;
int n6 = 5;
// Numbers of Matching Combinations
int match_comb = 0;
// Creating a file to see combinations content
char ch, file_name[25];
FILE *fp;
fp = fopen("combinations.txt", "r"); // Read Mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
int j = 0;
int mn = 0; // Number of matched numbers
int x[6] = {0,0,0,0,0,0};
int c;
while((c = fgetc(fp)) != EOF)
{
//x[j] = fscanf(fp, "%d", &c);
fscanf(fp, "%d %d %d %d %d %d", &x[0], &x[1], &x[2], &x[3], &x[4], &x[5]);
printf("%d", x[0]);
printf(" ");
printf("%d", x[1]);
printf(" ");
printf("%d", x[2]);
printf(" ");
printf("%d", x[3]);
printf(" ");
printf("%d", x[4]);
printf(" ");
printf("%d", x[5]);
if(x[0]==n1 || x[0]==n2 || x[0]==n3 || x[0]==n5 || x[0]==n6){
mn += 1;
}if(x[1]==n1 || x[1]==n2 || x[1]==n3 || x[1]==n5 || x[1]==n6){
mn += 1;
}if(x[2]==n1 || x[2]==n2 || x[2]==n3 || x[2]==n5 || x[2]==n6){
mn += 1;
}if(x[3]==n1 || x[3]==n2 || x[3]==n3 || x[3]==n5 || x[3]==n6){
mn += 1;
}if(x[4]==n1 || x[4]==n2 || x[4]==n3 || x[4]==n5 || x[4]==n6){
mn += 1;
}if(x[5]==n1 || x[5]==n2 || x[5]==n3 || x[5]==n5 || x[5]==n6){
mn += 1;
}
if ( mn == 5)
{
match_comb += 1; // Adding One the the Match Combinantions counter
}
for (int i = 0; i < 6; ++i) // Resetting x array
{
x[i] = 0;
}
mn = 0; // Resetting
printf("\n");
}
printf("Number of Matching Combinations:");
printf("%d", match_comb);
printf("\n");
fclose(fp);
return 0;
}
The problem lies with:
x[j] = c;
This assigns a char to an integer. You need to convert c to an integer. For example by subtracting the character code of zero:
x[j] = c-'0';
You can use isdigit(c) to check whether c is really a digit.
Either with the help of the debugger or by using printf to show the exact values of the x[0], x[1], ... you get a clearer view of what was going wrong.
As for reading numbers of more than 1 digit, the best idea is to use a function such as fscanf(fp, "%d", &c) which automatically converts the read characters to a number. Note that if you use &c here, c needs to be an int, not a char.
If you want to work with fscanf, you need to remove the calls to fgetc (in your while-loop), because otherwise fgetc everytime removes a character. Removing a character is no problem when that's a space or a newline, but it is a problem for the first digit in the line. When fgetc can not be used anymore for checking end-of-file, use the return value of fscanf as explained in this post. For example:
while (true) // endless loop, but will end via a 'break'
{
// remove if(c == ' ' || c == '\n')
if (fscanf(fp, "%d", &c) != 1) // check whether fscanf found 1 input
break; // this jumps out of the while loop
.... // rest of your code
}
If you really want to use fgetc for reading the numbers, you need something like:
if (isdigit(c))
num = num * 10 + (c - '0');
and not yet putting num in the X-array until you encounter a non-digit. num needs to be reset to 0 thereafter.
As for the code you use for calculating the number of matches, it looks quite clever if you're fully new to programming. An improvement would be to also put the n values in an array and to use for-loops to check the number of matches.
Whenever I run this (part of a much larger file), when I get asked for inputs, if they are not numbers (letters or words) the code seems to loop and I'm not sure why.
while(rembox>=1){
printf("%c> ", p );
s=scanf("%d %d %c",&r , &k, &orin);
if (r = 5 || k =10){
*statement*
rembox --;
}
else{
rembox --;
continue;
}
At this line :
if (r = 5 || k =10){
You are assigning values 5 and 10 to r and k variables.
What you wanted to do :
if (r == 5 || k ==10){
Here is the question:
Write the program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab. When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?
I did the exercise myself, and the book's answer has a different solution. I'm not understanding a mathematical formula that executes when a tab is read from the input stream. Here is the code:
#include <stdio.h>
#define TABINC 8
main()
{
int c, nb, nt, pos;
nb = 0;
nt = 0;
for (pos = 1; (c =getchar()) != EOF; ++pos)
if (c == ' '){
if (pos % TABINC != 0)
++nb;
else {
nb = 0;
++nt;
}
}
else {
for ( ; nt > 0; --nt)
putchar('\t');
if (c == '\t')
nb = 0;
else
for ( ; nb > 0; --nb)
putchar(' ');
putchar(c);
if ( c == '\n')
pos = 0;
else if (c == '\t')
pos = pos + (TABINC - (pos - 1) % TABINC) - 1;
}
}
The part I'm not understanding is the following:
else if (c == '\t')
pos = pos + (TABINC - (pos - 1) % TABINC) - 1;
I can see through debugging in visual studio that this construct brings the pos to the next tab stop when a tab occurs from the input stream. Is this correct?
What I really don't understand is how this formula works or how they came up with it. is this a common formula that occurs in programming? Is it useful? Does it have a name?
Edit: I do understand what the modulo operator does. I'm sorry I didn't specify that.
There is no specific name to this formula - it is a relatively straightforward way of applying math from the elementary school to everyday problems. Here is what's going on: '\t' character advances the pos by a number of positions ranging from one to TABINC, inclusive.
When pos is a multiple of TABINC, you jump the full TABINC
When pos is one below the next multiple of TABINC, you jump by one,
When pos is two below the next multiple of TABINC, you jump by two,
and so on - when pos is x, where 0 < x < TABINC, below the next multiple of TABINC, you jump x
Now the problem of calculating a jump is reduced to computing the difference between pos and the next multiple of TABINC. This can be done by computing a division remainder of the pos and TABINC, and subtracting that remainder from the TABINC. This is done with the % operator.
Since pos is one-based *, the first thing the formula does is making it zero-based for the purpose of calculating the remainder. Next, the formula computes the remainder, which is a mathematical way of saying "the number of positions above the last TABINC stop". Now all you need is subtracting that remainder from TABINC to get your result.
* The assignment pos=0 on discovering '\n' seemingly contradicts the assertion that pos is one-based. However, the loop header performs pos++ after each iteration, so the next iteration of the loop sees pos=1 on the next iteration.
It does not have a name or something like that.
In detail:
First of all, how much pos has to be increased depends on pos%TABINC,
ie. TABINC is 8, so if pos is a multiple from 8, add 8,
if pos%8 is 1 (like 9, 17...) then add 7,
if pos%8 is 2 (10, 18...) add 6 and so on.
Full list:
pos%8 -> number to add
0 -> 8
1 -> 7
2 -> 6
3 -> 5
4 -> 4
5 -> 3
6 -> 2
7 -> 1
That would be 8 - pos%8 or, more general TABINC - pos%TABINC
Important: A negative number modulo something in C is mathematically not correct
In C, for a,b >= 0: (-a)%b == -(a%b)
What is added in the code is (TABINC - (pos - 1) % TABINC) - 1
With some basic math and the fact above, this is
(TABINC - (pos - 1) % TABINC) - 1
= TABINC - ((pos - 1) % TABINC)) - 1
= TABINC - ((pos % TABINC) - 1) - 1
= TABINC + 1 - (pos % TABINC) - 1
= TABINC - (pos % TABINC)
which is the same as my short formula above, only more complex for no reason.
i am having a problem figuring out an algorithm for this problem,been trying for few days without success,here is a pic of what im trying to obtain:
http://i.stack.imgur.com/X70nX.png
Here is my code tried many differents solutions but always get stuck at the same point:(Sorry for mixed language the important part is in english)
ps
im not supposed to use functions to solve this problem only loops and array.
EDIT
after much fixing it does the walk but seldomly crashes
any idea?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
char box[10][10];
int i,j;
int move,row,col;
char letter='A';
srand(time(NULL));
printf("\n\tSTART\n\n");
for(i=0;i < 10 ;i++)/* righe */
{
for(j=0;j < 10;j++) /* colonne */
{
box[i][j] = '.'; /* assegno . a tutti gli elementi dell array */
if(j == 9)
printf("%c%c\n", box[i][j]); /* giustifico ogni 10 elementi dell array j(0-9) */
else
printf("%c%c", box[i][j]);
}
}
/* LETS START */
printf("\n\n Inizia il gioco\n\n");
/* random place to start */
row = rand() % 9;
col = rand() % 9;
box[row][col]= 'A';
while(letter <= 'Z')
{
if(box[row+1][col] == '.' || box[row-1][col] == '.' || box[row][col+1] == '.' || box[row][col-1] == '.' )
{
move=rand() % 4;
switch(move){
case 0: /* Going UP */
if((row != 0) && (box[row-1][col] == '.'))
{
box[row-1][col]=++letter;
box[row--][col];
}else{
move=rand() % 4;
}
case 1:/* Going Down */
if((row != 9) && (box[row+1][col] == '.'))
{
box[row+1][col]=++letter;
box[row++][col];
}else{
move=rand() % 4;
}
case 2: /*Going Left */
if((col != 0) && (box[row][col-1] == '.'))
{
box[row][col-1]=++letter;
box[row][col--];
}else{
move=rand() % 4;
}
case 3: /* Going Right */
if((col != 9) && (box[row][col+1] == '.') )
{
box[row][col+1]=++letter;
box[row][col++];
}else{
move=rand() % 4;
}
}
}else{
printf("\n\nBloccato a %c\n\n", letter);
break;
}
}
/* FINE */
for(i=0;i<10;i++)/* righe */
{
for(j=0;j<10;j++) /* colonne */
{
if(j == 9)
printf("%c%c\n", box[i][j]); /* giustifico ogni 10 elementi dell array j(0-9) */
else
printf("%c%c", box[i][j]);
}
}
return 0;
}
You need to update row and col inside the loop.
Otherwise you'll always attempt to walk from the position of the 'A'.
... and once all 4 directions are filled, you're stuck in a infinite loop
. . . . .
. . B . .
. E A C .
. . D . .
Even when you update row and col inside the loop (and correct the == mistake), you have to handle a problem: suppose the first spot (the 'A') is the top left corner and the next random directions are East, South, South, West, and North. ... now what? :)
A B .
F C .
E D .
. . .
It's not a good idea to "reroll" the random number when you discover that you cannot go in some direction, because if you have bad luck, you get the same number twice (or even 3 or 4 or more times) - so even if you generated 4 random numbers and they all failed, that doesn't mean that you're stuck.
You can solve this problem by generating one number, and trying all 4 possible directions starting from it:
If the random number generator returned 0: check 0, 1, 2, 3
If the random number generator returned 1: check 1, 2, 3, 0
If the random number generator returned 2: check 2, 3, 0, 1
If the random number generator returned 3: check 3, 0, 1, 2
Implemented by the following code:
desired_move = rand();
success = 0;
for (i = 0; i < 4 && !success; ++i)
{
move = (desired_move + i) % 4;
switch (move)
{
case 0: // Go up
if (row > 0 && box[row - 1][col] == '.')
{
row = row - 1;
success = 1;
}
break;
case 1: // Go down
...
}
}
if (!success) // Tried all 4 directions but failed! You are stuck!
{
goto START_OVER; // or whatever else
}
Note that this algorithm is not very random: if you cannot go up, there is a greater chance that you go down than right or left. If you want to fix it, you can pick a random permutation of 4 directions instead of checking the directions sequentially:
const int permutation_table[24][4] = {
{0, 1, 2, 3},
{0, 1, 3, 2},
{0, 2, 1, 3},
...
{3, 2, 1, 0}
};
index = rand() % 24;
for (i = 0; i < 4; ++i)
{
move = permutation_table[index][i];
switch (move) {
... // As above
}
}
When you're in for loop.
Draw a possible direction
int direction = rand()%4;
Check all possible directions if the drawed one is invalid (not in array or not a ".")
int i=-1;
while( ++i < 4 )
{
switch(direction)
{
case 0:
if( row-1 >= 0 && box[row-1][col] == '.' ) {
--row;
i = -1;
}
break;
case 1:
if( col+1 < 10 && box[row][col+1] == '.' ) {
++col;
i = -1;
}
break;
case 2:
if( row+1 < 10 && box[row+1][col] == '.' ) {
++row;
i = -1;
}
break;
case 3:
if( col-1 >= 0 && box[row][col-1] == '.' ) {
--col;
i = -1;
}
break;
}
if( i != -1 ) {
direction = (direction+1)%4;
}
else {
break;
}
}
If there's no valid move end the for loop>
if( i == 4 ) {
break;
}
Otherwise write a letter to the table cell and update row/col position.
box[row][col] = letter;
And... that's all I guess. This is greedy algorithm so you don't need any optimizations (at least I don't see any in exercise requirements.
It looks like you are breaking out of your switch statement if you try to go in a direction that isn't valid, but you increment your counter anyway. Try to check another random direction if that happens.
where exactly does it break?
from what I can see at a glance is that you have a chance that It_that_walks gets in position from witch it cant go anywhere:
A B C D .
. I J E .
. H G F .
where after J?
There is no need for the && (box[row][col-1]= '.')
Allso, it is wrong (assignment instead of comparison), it should be: && (box[row][col-1]== '.') (but you dont need it alltogether)