C++ C, 411 400 388 367 characters
My first attempt ever at a code golf.
#include<stdio.h>
main(){char m[999],w[99];int r,c,l=-1,x=-1,y=-1,i=0,j,k;scanf("%s %d %d"
,w,&r,&c);for(;w[l+1];++l);for(;i<r*c;scanf("%s",&m[i++]));for(;y<2;++y)
for(;x<2;++x)if(x|y)for(i=(y<0)*l;i<r-(y>0)*l;++i)for(j=(x<0)*l;j<c-(x>0
)*l;++j)for(k=0;k<=l&&w[k++]==m[(i+k*y)*c+j+k*x];)k>l?printf(
"row %i, column %i --> row %i, column %i\n",i+1,j+1,i+y*l+1,j+x*l+1):0;}
It compiles without warnings on gcc with no additional flags.
Here's the version with whitespace:
#include<stdio.h>
main() {
char m[999], w[99];
int r, c, l = -1, x = -1, y = -1, i = 0, j, k;
scanf("%s %d %d", w, &r, &c);
for (; w[l+1]; ++l);
for (; i < r*c; scanf("%s", &m[i++]));
for (; y < 2; ++y)
for (; x < 2; ++x)
if (x | y)
for (i = (y<0) * l; i < r - (y>0) * l; ++i)
for (j = (x<0) * l; j < c - (x>0) * l; ++j)
for (k = 0; k <= l && w[k++] == m[(i+k*y) * c + j+k*x];)
k > l ? printf("row %i, column %i --> row %i, column %i\n",
i + 1, j + 1, i + y*l + 1, j + x*l + 1)
: 0;
}
Expected input on stdin looks like:
CODEGOLF 15 15
A I Y R J J Y T A S V Q T Z E
X B X G R Z P W V T B K U F O
...
where 15 15
are the numbers of rows and columns, respectively.
Since this is my first round of golf, and I could find precious little common tricks on the web, I'll list some that I found:
Try to keep loop bodies to a single statement to save on moustaches (2 chars).
Example: anything using the comma operator.
Use a conditional expression (?:
) instead of an if
when you can (1 char).
Example: instead of if(x)printf("");
, write x?printf(""):0;
. This works because printf
returns int
.
Use the fact that booleans are 0
or 1
when used as an int
(? chars).
Example: instead of (y>0?r-l:r)
, write r-(y>0)*l
. The savings here are in the parentheses, which were necessary in this situation.
while
loops are never shorter than for
loops, and longer most of the time (>= 0 chars).
Example: while(x)y;
is just as long as for(;x;y);
but with for
you get the loop body to play with as well, without paying for the extra ;
.
Put your loop increments into the last expression that uses the loop counter (1 char).
Example: instead of for(;x<b;++x)printf("%i",x);
, write for(;x<b;)printf("%i",x++);
.
Leave off main
's return type (4 chars).
Leave off main
's return
statement (9 chars).
Use &
and |
instead of &&
and ||
whenever possible (1 char).
Example: instead of if(x||y)
, write if(x|y)
. This only works if you don't depend on the short-circuit behaviour of &&
and ||
.
Inline the strlen
function and remove #include<string.h>
(11 chars).
If you don't care about compiler warnings:
- Do not include any headers (many chars).