Initial checkin

This commit is contained in:
Bobbi Webber-Manners 2020-01-28 23:22:35 -05:00
parent c82b100904
commit 000d69c9ed
72 changed files with 36868 additions and 0 deletions

3
v7/TODO#b00000 Normal file
View File

@ -0,0 +1,3 @@
games/backgammon does not work yet
games/quiz does not work yet

31
v7/cmd/Makefile#b00000 Normal file
View File

@ -0,0 +1,31 @@
all: cal dd file find od rev units
cal: cal.c
occ -I /usr/include -o cal cal.c
dd: dd.c
occ -I /usr/include -o dd dd.c
file: file.c
occ -I /usr/include -o file file.c
find: find.c
occ -I /usr/include -o find find.c
od: od.c
occ -I /usr/include -o od od.c
rev: rev.c
occ -I /usr/include -o rev rev.c
units: units.c
occ -I /usr/include -o units units.c
clean:
cp -p rm -f *.a *.o *.root cal dd file find od rev units
install: all
cp units.database /usr/local/lib
cp cal dd file find od rev units /usr/local/bin
cp *.1 /usr/local/man/man1

27
v7/cmd/cal.1#000000 Normal file
View File

@ -0,0 +1,27 @@
.TH CAL 1
.SH NAME
cal \- print calendar
.SH SYNOPSIS
.B cal
[ month ] year
.SH DESCRIPTION
.I Cal
prints a calendar for the specified year.
If a month is also specified, a calendar
just for that month is printed.
.I Year
can be between 1
and 9999.
The
.I month
is a number between 1 and 12.
The calendar
produced is that for England and her colonies.
.PP
Try September 1752.
.SH BUGS
The year is always considered to start in January even though this
is historically naive.
.br
Beware that `cal 78' refers to the early Christian era,
not the 20th century.

204
v7/cmd/cal.c#b00008 Normal file
View File

@ -0,0 +1,204 @@
char dayw[] = {
" S M Tu W Th F S"
};
char *smon[]= {
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December",
};
char string[432];
main(argc, argv)
char *argv[];
{
register y, i, j;
int m;
if(argc < 2) {
printf("usage: cal [month] year\n");
exit(0);
}
if(argc == 2)
goto xlong;
/*
* print out just month
*/
m = number(argv[1]);
if(m<1 || m>12)
goto badarg;
y = number(argv[2]);
if(y<1 || y>9999)
goto badarg;
printf(" %s %u\n", smon[m-1], y);
printf("%s\n", dayw);
cal(m, y, string, 24);
for(i=0; i<6*24; i+=24)
pstr(string+i, 24);
exit(0);
/*
* print out complete year
*/
xlong:
y = number(argv[1]);
if(y<1 || y>9999)
goto badarg;
printf("\n\n\n");
printf(" %u\n", y);
printf("\n");
for(i=0; i<12; i+=3) {
for(j=0; j<6*72; j++)
string[j] = '\0';
printf(" %.3s", smon[i]);
printf(" %.3s", smon[i+1]);
printf(" %.3s\n", smon[i+2]);
printf("%s %s %s\n", dayw, dayw, dayw);
cal(i+1, y, string, 72);
cal(i+2, y, string+23, 72);
cal(i+3, y, string+46, 72);
for(j=0; j<6*72; j+=72)
pstr(string+j, 72);
}
printf("\n\n\n");
exit(0);
badarg:
printf("Bad argument\n");
}
number(str)
char *str;
{
register n, c;
register char *s;
n = 0;
s = str;
while(c = *s++) {
if(c<'0' || c>'9')
return(0);
n = n*10 + c-'0';
}
return(n);
}
pstr(str, n)
char *str;
{
register i;
register char *s;
s = str;
i = n;
while(i--)
if(*s++ == '\0')
s[-1] = ' ';
i = n+1;
while(i--)
if(*--s != ' ')
break;
s[1] = '\0';
printf("%s\n", str);
}
char mon[] = {
0,
31, 29, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31,
};
cal(m, y, p, w)
char *p;
{
register d, i;
register char *s;
s = p;
d = jan1(y);
mon[2] = 29;
mon[9] = 30;
switch((jan1(y+1)+7-d)%7) {
/*
* non-leap year
*/
case 1:
mon[2] = 28;
break;
/*
* 1752
*/
default:
mon[9] = 19;
break;
/*
* leap year
*/
case 2:
;
}
for(i=1; i<m; i++)
d += mon[i];
d %= 7;
s += 3*d;
for(i=1; i<=mon[m]; i++) {
if(i==3 && mon[m]==19) {
i += 11;
mon[m] += 11;
}
if(i > 9)
*s = i/10+'0';
s++;
*s++ = i%10+'0';
s++;
if(++d == 7) {
d = 0;
s = p+w;
p = s;
}
}
}
/*
* return day of the week
* of jan 1 of given year
*/
jan1(yr)
{
register y, d;
/*
* normal gregorian calendar
* one extra day per four years
*/
y = yr;
d = 4+y+(y+3)/4;
/*
* julian calendar
* regular gregorian
* less three days per 400
*/
if(y > 1800) {
d -= (y-1701)/100;
d += (y-1601)/400;
}
/*
* great calendar changeover instant
*/
if(y > 1752)
d += 3;
return(d%7);
}

192
v7/cmd/dd.1#000000 Normal file
View File

@ -0,0 +1,192 @@
.TH DD 1
.SH NAME
dd \- convert and copy a file
.SH SYNOPSIS
.B dd
[option=value] ...
.SH DESCRIPTION
.I Dd
copies the specified input file
to the specified output with
possible conversions.
The standard input and output are used by default.
The input and output block size may be
specified to take advantage of raw physical I/O.
.PP
.br
.ns
.TP 15
.I option
.I values
.br
.ns
.TP
if=
input file name; standard input is default
.br
.ns
.TP
of=
output file name; standard output is default
.br
.ns
.TP
.RI ibs= n
input block size
.I n
bytes (default 512)
.br
.ns
.TP
.RI obs= n
output block size (default 512)
.br
.ns
.TP
.RI bs= n
set both input and output block size,
superseding
.I ibs
and
.I obs;
also, if no conversion is specified,
it is particularly efficient since no copy need be done
.br
.ns
.TP
.RI cbs= n
conversion buffer size
.br
.ns
.TP
.RI skip= n
skip
.IR n ""
input records before starting copy
.br
.ns
.TP
.RI files= n
copy
.I n
files from (tape) input
.br
.ns
.TP
.RI seek= n
seek
.I n
records from beginning of output file before copying
.br
.ns
.TP
count=\fIn\fR
copy only
.IR n ""
input records
.br
.ns
.TP
conv=ascii
.ds h \h'\w'conv='u'
convert EBCDIC to ASCII
.br
.ns
.IP \*hebcdic
convert ASCII to EBCDIC
.br
.ns
.IP \*hibm
slightly different map of ASCII to EBCDIC
.br
.ns
.IP \*hlcase
map alphabetics to lower case
.br
.ns
.IP \*hucase
map alphabetics to upper case
.br
.ns
.IP \*hswab
swap every pair of bytes
.br
.ns
.IP \*hnoerror
do not stop processing on an error
.br
.ns
.IP \*hsync
pad every input record to
.I ibs
.br
.ns
.IP "\*h... , ..."
several comma-separated conversions
.PP
.fi
Where sizes are specified,
a number of bytes is expected.
A number may end with
.B "k, b"
or
.B w
to specify multiplication by
1024, 512, or 2 respectively;
a pair of numbers may be separated by
.B x
to indicate a product.
.PP
.I Cbs
is used only if
.I ascii
or
.I ebcdic
conversion is specified.
In the former case
.I cbs
characters are placed into the conversion buffer, converted to
ASCII, and trailing blanks trimmed and new-line added
before sending the line to the output.
In the latter case ASCII characters are read into the
conversion buffer, converted to EBCDIC, and blanks added
to make up an
output record of size
.IR cbs .
.PP
After completion,
.I dd
reports the number of whole and partial input and output
blocks.
.PP
For example, to read an EBCDIC tape blocked ten 80-byte
EBCDIC card images per record into the ASCII file
.IR x :
.IP ""
dd if=/dev/rmt0 of=x ibs=800 cbs=80 conv=ascii,lcase
.PP
Note the use of raw magtape.
.I Dd
is especially suited to I/O on the raw
physical devices because it allows reading
and writing in arbitrary record sizes.
.PP
To skip over a file before copying from magnetic tape do
.IP""
(dd of=/dev/null; dd of=x) </dev/rmt0
.SH "SEE ALSO"
cp(1), tr(1)
.SH DIAGNOSTICS
f+p records in(out): numbers of full and partial records read(written)
.SH BUGS
The ASCII/EBCDIC conversion tables are
taken
from the 256 character standard in
the CACM Nov, 1968.
The `ibm' conversion, while less blessed as a standard,
corresponds better to certain IBM print train conventions.
There is no universal solution.
.PP
Newlines are inserted only on conversion to ASCII;
padding is done only on conversion to EBCDIC.
These should be separate options.

542
v7/cmd/dd.c#b00008 Normal file
View File

@ -0,0 +1,542 @@
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#define BIG 32767
#define LCASE 01
#define UCASE 02
#define SWAB 04
#define NERR 010
#define SYNC 020
int cflag;
int fflag;
int skip;
int seekn;
int count;
int files = 1;
char *string;
char *ifile;
char *ofile;
char *ibuf;
char *obuf;
int ibs = 512;
int obs = 512;
int bs;
int cbs;
int ibc;
int obc;
int cbc;
int nifr;
int nipr;
int nofr;
int nopr;
int ntrunc;
int ibf;
int obf;
char *op;
int nspace;
char etoa[] = {
0000,0001,0002,0003,0234,0011,0206,0177,
0227,0215,0216,0013,0014,0015,0016,0017,
0020,0021,0022,0023,0235,0205,0010,0207,
0030,0031,0222,0217,0034,0035,0036,0037,
0200,0201,0202,0203,0204,0012,0027,0033,
0210,0211,0212,0213,0214,0005,0006,0007,
0220,0221,0026,0223,0224,0225,0226,0004,
0230,0231,0232,0233,0024,0025,0236,0032,
0040,0240,0241,0242,0243,0244,0245,0246,
0247,0250,0133,0056,0074,0050,0053,0041,
0046,0251,0252,0253,0254,0255,0256,0257,
0260,0261,0135,0044,0052,0051,0073,0136,
0055,0057,0262,0263,0264,0265,0266,0267,
0270,0271,0174,0054,0045,0137,0076,0077,
0272,0273,0274,0275,0276,0277,0300,0301,
0302,0140,0072,0043,0100,0047,0075,0042,
0303,0141,0142,0143,0144,0145,0146,0147,
0150,0151,0304,0305,0306,0307,0310,0311,
0312,0152,0153,0154,0155,0156,0157,0160,
0161,0162,0313,0314,0315,0316,0317,0320,
0321,0176,0163,0164,0165,0166,0167,0170,
0171,0172,0322,0323,0324,0325,0326,0327,
0330,0331,0332,0333,0334,0335,0336,0337,
0340,0341,0342,0343,0344,0345,0346,0347,
0173,0101,0102,0103,0104,0105,0106,0107,
0110,0111,0350,0351,0352,0353,0354,0355,
0175,0112,0113,0114,0115,0116,0117,0120,
0121,0122,0356,0357,0360,0361,0362,0363,
0134,0237,0123,0124,0125,0126,0127,0130,
0131,0132,0364,0365,0366,0367,0370,0371,
0060,0061,0062,0063,0064,0065,0066,0067,
0070,0071,0372,0373,0374,0375,0376,0377,
};
char atoe[] = {
0000,0001,0002,0003,0067,0055,0056,0057,
0026,0005,0045,0013,0014,0015,0016,0017,
0020,0021,0022,0023,0074,0075,0062,0046,
0030,0031,0077,0047,0034,0035,0036,0037,
0100,0117,0177,0173,0133,0154,0120,0175,
0115,0135,0134,0116,0153,0140,0113,0141,
0360,0361,0362,0363,0364,0365,0366,0367,
0370,0371,0172,0136,0114,0176,0156,0157,
0174,0301,0302,0303,0304,0305,0306,0307,
0310,0311,0321,0322,0323,0324,0325,0326,
0327,0330,0331,0342,0343,0344,0345,0346,
0347,0350,0351,0112,0340,0132,0137,0155,
0171,0201,0202,0203,0204,0205,0206,0207,
0210,0211,0221,0222,0223,0224,0225,0226,
0227,0230,0231,0242,0243,0244,0245,0246,
0247,0250,0251,0300,0152,0320,0241,0007,
0040,0041,0042,0043,0044,0025,0006,0027,
0050,0051,0052,0053,0054,0011,0012,0033,
0060,0061,0032,0063,0064,0065,0066,0010,
0070,0071,0072,0073,0004,0024,0076,0341,
0101,0102,0103,0104,0105,0106,0107,0110,
0111,0121,0122,0123,0124,0125,0126,0127,
0130,0131,0142,0143,0144,0145,0146,0147,
0150,0151,0160,0161,0162,0163,0164,0165,
0166,0167,0170,0200,0212,0213,0214,0215,
0216,0217,0220,0232,0233,0234,0235,0236,
0237,0240,0252,0253,0254,0255,0256,0257,
0260,0261,0262,0263,0264,0265,0266,0267,
0270,0271,0272,0273,0274,0275,0276,0277,
0312,0313,0314,0315,0316,0317,0332,0333,
0334,0335,0336,0337,0352,0353,0354,0355,
0356,0357,0372,0373,0374,0375,0376,0377,
};
char atoibm[] =
{
0000,0001,0002,0003,0067,0055,0056,0057,
0026,0005,0045,0013,0014,0015,0016,0017,
0020,0021,0022,0023,0074,0075,0062,0046,
0030,0031,0077,0047,0034,0035,0036,0037,
0100,0132,0177,0173,0133,0154,0120,0175,
0115,0135,0134,0116,0153,0140,0113,0141,
0360,0361,0362,0363,0364,0365,0366,0367,
0370,0371,0172,0136,0114,0176,0156,0157,
0174,0301,0302,0303,0304,0305,0306,0307,
0310,0311,0321,0322,0323,0324,0325,0326,
0327,0330,0331,0342,0343,0344,0345,0346,
0347,0350,0351,0255,0340,0275,0137,0155,
0171,0201,0202,0203,0204,0205,0206,0207,
0210,0211,0221,0222,0223,0224,0225,0226,
0227,0230,0231,0242,0243,0244,0245,0246,
0247,0250,0251,0300,0117,0320,0241,0007,
0040,0041,0042,0043,0044,0025,0006,0027,
0050,0051,0052,0053,0054,0011,0012,0033,
0060,0061,0032,0063,0064,0065,0066,0010,
0070,0071,0072,0073,0004,0024,0076,0341,
0101,0102,0103,0104,0105,0106,0107,0110,
0111,0121,0122,0123,0124,0125,0126,0127,
0130,0131,0142,0143,0144,0145,0146,0147,
0150,0151,0160,0161,0162,0163,0164,0165,
0166,0167,0170,0200,0212,0213,0214,0215,
0216,0217,0220,0232,0233,0234,0235,0236,
0237,0240,0252,0253,0254,0255,0256,0257,
0260,0261,0262,0263,0264,0265,0266,0267,
0270,0271,0272,0273,0274,0275,0276,0277,
0312,0313,0314,0315,0316,0317,0332,0333,
0334,0335,0336,0337,0352,0353,0354,0355,
0356,0357,0372,0373,0374,0375,0376,0377,
};
main(argc, argv)
int argc;
char **argv;
{
int (*conv)();
register char *ip;
register c;
int ebcdic(), ibm(), ascii(), null(), cnull(), term();
int a;
conv = null;
for(c=1; c<argc; c++) {
string = argv[c];
if(match("ibs=")) {
ibs = number(BIG);
continue;
}
if(match("obs=")) {
obs = number(BIG);
continue;
}
if(match("cbs=")) {
cbs = number(BIG);
continue;
}
if (match("bs=")) {
bs = number(BIG);
continue;
}
if(match("if=")) {
ifile = string;
continue;
}
if(match("of=")) {
ofile = string;
continue;
}
if(match("skip=")) {
skip = number(BIG);
continue;
}
if(match("seek=")) {
seekn = number(BIG);
continue;
}
if(match("count=")) {
count = number(BIG);
continue;
}
if(match("files=")) {
files = number(BIG);
continue;
}
if(match("conv=")) {
cloop:
if(match(","))
goto cloop;
if(*string == '\0')
continue;
if(match("ebcdic")) {
conv = ebcdic;
goto cloop;
}
if(match("ibm")) {
conv = ibm;
goto cloop;
}
if(match("ascii")) {
conv = ascii;
goto cloop;
}
if(match("lcase")) {
cflag |= LCASE;
goto cloop;
}
if(match("ucase")) {
cflag |= UCASE;
goto cloop;
}
if(match("swab")) {
cflag |= SWAB;
goto cloop;
}
if(match("noerror")) {
cflag |= NERR;
goto cloop;
}
if(match("sync")) {
cflag |= SYNC;
goto cloop;
}
}
fprintf(stderr,"bad arg: %s\n", string);
exit(0);
}
if(conv == null && cflag&(LCASE|UCASE))
conv = cnull;
if (ifile)
ibf = open(ifile, 0);
else
ibf = dup(0);
if(ibf < 0) {
fprintf(stderr,"cannot open: %s\n", ifile);
exit(0);
}
if (ofile)
obf = creat(ofile, 0666);
else
obf = dup(1);
if(obf < 0) {
fprintf(stderr,"cannot create: %s\n", ofile);
exit(0);
}
if (bs) {
ibs = obs = bs;
if (conv == null)
fflag++;
}
if(ibs == 0 || obs == 0) {
fprintf(stderr,"counts: cannot be zero\n");
exit(0);
}
ibuf = (char*)malloc(ibs);
if (fflag)
obuf = ibuf;
else
obuf = (char*)malloc(obs);
/* sbrk(64); */ /* For good measure */
if(ibuf == (char *)-1 || obuf == (char *)-1) {
fprintf(stderr, "not enough memory\n");
exit(0);
}
ibc = 0;
obc = 0;
cbc = 0;
op = obuf;
/* if (signal(SIGINT, SIG_IGN) != SIG_IGN)
signal(SIGINT, term); */
while(skip) {
read(ibf, ibuf, ibs);
skip--;
}
while(seekn) {
lseek(obf, (long)obs, 1);
seekn--;
}
loop:
if(ibc-- == 0) {
ibc = 0;
if(count==0 || nifr+nipr!=count) {
if(cflag&(NERR|SYNC))
for(ip=ibuf+ibs; ip>ibuf;)
*--ip = 0;
ibc = read(ibf, ibuf, ibs);
}
if(ibc == -1) {
perror("read");
if((cflag&NERR) == 0) {
flsh();
term();
}
ibc = 0;
for(c=0; c<ibs; c++)
if(ibuf[c] != 0)
ibc = c;
stats();
}
if(ibc == 0 && --files<=0) {
flsh();
term();
}
if(ibc != ibs) {
nipr++;
if(cflag&SYNC)
ibc = ibs;
} else
nifr++;
ip = ibuf;
c = (ibc>>1) & ~1;
if(cflag&SWAB && c)
do {
a = *ip++;
ip[-1] = *ip;
*ip++ = a;
} while(--c);
ip = ibuf;
if (fflag) {
obc = ibc;
flsh();
ibc = 0;
}
goto loop;
}
c = 0;
c |= *ip++;
c &= 0377;
(*conv)(c);
goto loop;
}
flsh()
{
register c;
if(obc) {
if(obc == obs)
nofr++; else
nopr++;
c = write(obf, obuf, obc);
if(c != obc) {
perror("write");
term();
}
obc = 0;
}
}
match(s)
char *s;
{
register char *cs;
cs = string;
while(*cs++ == *s)
if(*s++ == '\0')
goto true;
if(*s != '\0')
return(0);
true:
cs--;
string = cs;
return(1);
}
number(big)
{
register char *cs;
long n;
cs = string;
n = 0;
while(*cs >= '0' && *cs <= '9')
n = n*10 + *cs++ - '0';
for(;;)
switch(*cs++) {
case 'k':
n *= 1024;
continue;
case 'w':
n *= sizeof(int);
continue;
case 'b':
n *= 512;
continue;
case '*':
case 'x':
string = cs;
n *= number(BIG);
case '\0':
if (n>=big || n<0) {
fprintf(stderr, "dd: argument %D out of range\n", n);
exit(1);
}
return(n);
}
/* never gets here */
}
cnull(cc)
{
register c;
c = cc;
if(cflag&UCASE && c>='a' && c<='z')
c += 'A'-'a';
if(cflag&LCASE && c>='A' && c<='Z')
c += 'a'-'A';
null(c);
}
null(c)
{
*op = c;
op++;
if(++obc >= obs) {
flsh();
op = obuf;
}
}
ascii(cc)
{
register c;
c = etoa[cc] & 0377;
if(cbs == 0) {
cnull(c);
return;
}
if(c == ' ') {
nspace++;
goto out;
}
while(nspace > 0) {
null(' ');
nspace--;
}
cnull(c);
out:
if(++cbc >= cbs) {
null('\n');
cbc = 0;
nspace = 0;
}
}
ebcdic(cc)
{
register c;
c = cc;
if(cflag&UCASE && c>='a' && c<='z')
c += 'A'-'a';
if(cflag&LCASE && c>='A' && c<='Z')
c += 'a'-'A';
c = atoe[c] & 0377;
if(cbs == 0) {
null(c);
return;
}
if(cc == '\n') {
while(cbc < cbs) {
null(atoe[' ']);
cbc++;
}
cbc = 0;
return;
}
if(cbc == cbs)
ntrunc++;
cbc++;
if(cbc <= cbs)
null(c);
}
ibm(cc)
{
register c;
c = cc;
if(cflag&UCASE && c>='a' && c<='z')
c += 'A'-'a';
if(cflag&LCASE && c>='A' && c<='Z')
c += 'a'-'A';
c = atoibm[c] & 0377;
if(cbs == 0) {
null(c);
return;
}
if(cc == '\n') {
while(cbc < cbs) {
null(atoibm[' ']);
cbc++;
}
cbc = 0;
return;
}
if(cbc == cbs)
ntrunc++;
cbc++;
if(cbc <= cbs)
null(c);
}
term()
{
stats();
exit(0);
}
stats()
{
fprintf(stderr,"%u+%u records in\n", nifr, nipr);
fprintf(stderr,"%u+%u records out\n", nofr, nopr);
if(ntrunc)
fprintf(stderr,"%u truncated records\n", ntrunc);
}

541
v7/cmd/dd.c.orig#b00008 Normal file
View File

@ -0,0 +1,541 @@
#include <stdio.h>
#include <signal.h>
#define BIG 32767
#define LCASE 01
#define UCASE 02
#define SWAB 04
#define NERR 010
#define SYNC 020
int cflag;
int fflag;
int skip;
int seekn;
int count;
int files = 1;
char *string;
char *ifile;
char *ofile;
char *ibuf;
char *obuf;
char *sbrk();
int ibs = 512;
int obs = 512;
int bs;
int cbs;
int ibc;
int obc;
int cbc;
int nifr;
int nipr;
int nofr;
int nopr;
int ntrunc;
int ibf;
int obf;
char *op;
int nspace;
char etoa[] = {
0000,0001,0002,0003,0234,0011,0206,0177,
0227,0215,0216,0013,0014,0015,0016,0017,
0020,0021,0022,0023,0235,0205,0010,0207,
0030,0031,0222,0217,0034,0035,0036,0037,
0200,0201,0202,0203,0204,0012,0027,0033,
0210,0211,0212,0213,0214,0005,0006,0007,
0220,0221,0026,0223,0224,0225,0226,0004,
0230,0231,0232,0233,0024,0025,0236,0032,
0040,0240,0241,0242,0243,0244,0245,0246,
0247,0250,0133,0056,0074,0050,0053,0041,
0046,0251,0252,0253,0254,0255,0256,0257,
0260,0261,0135,0044,0052,0051,0073,0136,
0055,0057,0262,0263,0264,0265,0266,0267,
0270,0271,0174,0054,0045,0137,0076,0077,
0272,0273,0274,0275,0276,0277,0300,0301,
0302,0140,0072,0043,0100,0047,0075,0042,
0303,0141,0142,0143,0144,0145,0146,0147,
0150,0151,0304,0305,0306,0307,0310,0311,
0312,0152,0153,0154,0155,0156,0157,0160,
0161,0162,0313,0314,0315,0316,0317,0320,
0321,0176,0163,0164,0165,0166,0167,0170,
0171,0172,0322,0323,0324,0325,0326,0327,
0330,0331,0332,0333,0334,0335,0336,0337,
0340,0341,0342,0343,0344,0345,0346,0347,
0173,0101,0102,0103,0104,0105,0106,0107,
0110,0111,0350,0351,0352,0353,0354,0355,
0175,0112,0113,0114,0115,0116,0117,0120,
0121,0122,0356,0357,0360,0361,0362,0363,
0134,0237,0123,0124,0125,0126,0127,0130,
0131,0132,0364,0365,0366,0367,0370,0371,
0060,0061,0062,0063,0064,0065,0066,0067,
0070,0071,0372,0373,0374,0375,0376,0377,
};
char atoe[] = {
0000,0001,0002,0003,0067,0055,0056,0057,
0026,0005,0045,0013,0014,0015,0016,0017,
0020,0021,0022,0023,0074,0075,0062,0046,
0030,0031,0077,0047,0034,0035,0036,0037,
0100,0117,0177,0173,0133,0154,0120,0175,
0115,0135,0134,0116,0153,0140,0113,0141,
0360,0361,0362,0363,0364,0365,0366,0367,
0370,0371,0172,0136,0114,0176,0156,0157,
0174,0301,0302,0303,0304,0305,0306,0307,
0310,0311,0321,0322,0323,0324,0325,0326,
0327,0330,0331,0342,0343,0344,0345,0346,
0347,0350,0351,0112,0340,0132,0137,0155,
0171,0201,0202,0203,0204,0205,0206,0207,
0210,0211,0221,0222,0223,0224,0225,0226,
0227,0230,0231,0242,0243,0244,0245,0246,
0247,0250,0251,0300,0152,0320,0241,0007,
0040,0041,0042,0043,0044,0025,0006,0027,
0050,0051,0052,0053,0054,0011,0012,0033,
0060,0061,0032,0063,0064,0065,0066,0010,
0070,0071,0072,0073,0004,0024,0076,0341,
0101,0102,0103,0104,0105,0106,0107,0110,
0111,0121,0122,0123,0124,0125,0126,0127,
0130,0131,0142,0143,0144,0145,0146,0147,
0150,0151,0160,0161,0162,0163,0164,0165,
0166,0167,0170,0200,0212,0213,0214,0215,
0216,0217,0220,0232,0233,0234,0235,0236,
0237,0240,0252,0253,0254,0255,0256,0257,
0260,0261,0262,0263,0264,0265,0266,0267,
0270,0271,0272,0273,0274,0275,0276,0277,
0312,0313,0314,0315,0316,0317,0332,0333,
0334,0335,0336,0337,0352,0353,0354,0355,
0356,0357,0372,0373,0374,0375,0376,0377,
};
char atoibm[] =
{
0000,0001,0002,0003,0067,0055,0056,0057,
0026,0005,0045,0013,0014,0015,0016,0017,
0020,0021,0022,0023,0074,0075,0062,0046,
0030,0031,0077,0047,0034,0035,0036,0037,
0100,0132,0177,0173,0133,0154,0120,0175,
0115,0135,0134,0116,0153,0140,0113,0141,
0360,0361,0362,0363,0364,0365,0366,0367,
0370,0371,0172,0136,0114,0176,0156,0157,
0174,0301,0302,0303,0304,0305,0306,0307,
0310,0311,0321,0322,0323,0324,0325,0326,
0327,0330,0331,0342,0343,0344,0345,0346,
0347,0350,0351,0255,0340,0275,0137,0155,
0171,0201,0202,0203,0204,0205,0206,0207,
0210,0211,0221,0222,0223,0224,0225,0226,
0227,0230,0231,0242,0243,0244,0245,0246,
0247,0250,0251,0300,0117,0320,0241,0007,
0040,0041,0042,0043,0044,0025,0006,0027,
0050,0051,0052,0053,0054,0011,0012,0033,
0060,0061,0032,0063,0064,0065,0066,0010,
0070,0071,0072,0073,0004,0024,0076,0341,
0101,0102,0103,0104,0105,0106,0107,0110,
0111,0121,0122,0123,0124,0125,0126,0127,
0130,0131,0142,0143,0144,0145,0146,0147,
0150,0151,0160,0161,0162,0163,0164,0165,
0166,0167,0170,0200,0212,0213,0214,0215,
0216,0217,0220,0232,0233,0234,0235,0236,
0237,0240,0252,0253,0254,0255,0256,0257,
0260,0261,0262,0263,0264,0265,0266,0267,
0270,0271,0272,0273,0274,0275,0276,0277,
0312,0313,0314,0315,0316,0317,0332,0333,
0334,0335,0336,0337,0352,0353,0354,0355,
0356,0357,0372,0373,0374,0375,0376,0377,
};
main(argc, argv)
int argc;
char **argv;
{
int (*conv)();
register char *ip;
register c;
int ebcdic(), ibm(), ascii(), null(), cnull(), term();
int a;
conv = null;
for(c=1; c<argc; c++) {
string = argv[c];
if(match("ibs=")) {
ibs = number(BIG);
continue;
}
if(match("obs=")) {
obs = number(BIG);
continue;
}
if(match("cbs=")) {
cbs = number(BIG);
continue;
}
if (match("bs=")) {
bs = number(BIG);
continue;
}
if(match("if=")) {
ifile = string;
continue;
}
if(match("of=")) {
ofile = string;
continue;
}
if(match("skip=")) {
skip = number(BIG);
continue;
}
if(match("seek=")) {
seekn = number(BIG);
continue;
}
if(match("count=")) {
count = number(BIG);
continue;
}
if(match("files=")) {
files = number(BIG);
continue;
}
if(match("conv=")) {
cloop:
if(match(","))
goto cloop;
if(*string == '\0')
continue;
if(match("ebcdic")) {
conv = ebcdic;
goto cloop;
}
if(match("ibm")) {
conv = ibm;
goto cloop;
}
if(match("ascii")) {
conv = ascii;
goto cloop;
}
if(match("lcase")) {
cflag |= LCASE;
goto cloop;
}
if(match("ucase")) {
cflag |= UCASE;
goto cloop;
}
if(match("swab")) {
cflag |= SWAB;
goto cloop;
}
if(match("noerror")) {
cflag |= NERR;
goto cloop;
}
if(match("sync")) {
cflag |= SYNC;
goto cloop;
}
}
fprintf(stderr,"bad arg: %s\n", string);
exit(0);
}
if(conv == null && cflag&(LCASE|UCASE))
conv = cnull;
if (ifile)
ibf = open(ifile, 0);
else
ibf = dup(0);
if(ibf < 0) {
fprintf(stderr,"cannot open: %s\n", ifile);
exit(0);
}
if (ofile)
obf = creat(ofile, 0666);
else
obf = dup(1);
if(obf < 0) {
fprintf(stderr,"cannot create: %s\n", ofile);
exit(0);
}
if (bs) {
ibs = obs = bs;
if (conv == null)
fflag++;
}
if(ibs == 0 || obs == 0) {
fprintf(stderr,"counts: cannot be zero\n");
exit(0);
}
ibuf = sbrk(ibs);
if (fflag)
obuf = ibuf;
else
obuf = sbrk(obs);
sbrk(64); /* For good measure */
if(ibuf == (char *)-1 || obuf == (char *)-1) {
fprintf(stderr, "not enough memory\n");
exit(0);
}
ibc = 0;
obc = 0;
cbc = 0;
op = obuf;
if (signal(SIGINT, SIG_IGN) != SIG_IGN)
signal(SIGINT, term);
while(skip) {
read(ibf, ibuf, ibs);
skip--;
}
while(seekn) {
lseek(obf, (long)obs, 1);
seekn--;
}
loop:
if(ibc-- == 0) {
ibc = 0;
if(count==0 || nifr+nipr!=count) {
if(cflag&(NERR|SYNC))
for(ip=ibuf+ibs; ip>ibuf;)
*--ip = 0;
ibc = read(ibf, ibuf, ibs);
}
if(ibc == -1) {
perror("read");
if((cflag&NERR) == 0) {
flsh();
term();
}
ibc = 0;
for(c=0; c<ibs; c++)
if(ibuf[c] != 0)
ibc = c;
stats();
}
if(ibc == 0 && --files<=0) {
flsh();
term();
}
if(ibc != ibs) {
nipr++;
if(cflag&SYNC)
ibc = ibs;
} else
nifr++;
ip = ibuf;
c = (ibc>>1) & ~1;
if(cflag&SWAB && c)
do {
a = *ip++;
ip[-1] = *ip;
*ip++ = a;
} while(--c);
ip = ibuf;
if (fflag) {
obc = ibc;
flsh();
ibc = 0;
}
goto loop;
}
c = 0;
c |= *ip++;
c &= 0377;
(*conv)(c);
goto loop;
}
flsh()
{
register c;
if(obc) {
if(obc == obs)
nofr++; else
nopr++;
c = write(obf, obuf, obc);
if(c != obc) {
perror("write");
term();
}
obc = 0;
}
}
match(s)
char *s;
{
register char *cs;
cs = string;
while(*cs++ == *s)
if(*s++ == '\0')
goto true;
if(*s != '\0')
return(0);
true:
cs--;
string = cs;
return(1);
}
number(big)
{
register char *cs;
long n;
cs = string;
n = 0;
while(*cs >= '0' && *cs <= '9')
n = n*10 + *cs++ - '0';
for(;;)
switch(*cs++) {
case 'k':
n *= 1024;
continue;
case 'w':
n *= sizeof(int);
continue;
case 'b':
n *= 512;
continue;
case '*':
case 'x':
string = cs;
n *= number(BIG);
case '\0':
if (n>=big || n<0) {
fprintf(stderr, "dd: argument %D out of range\n", n);
exit(1);
}
return(n);
}
/* never gets here */
}
cnull(cc)
{
register c;
c = cc;
if(cflag&UCASE && c>='a' && c<='z')
c += 'A'-'a';
if(cflag&LCASE && c>='A' && c<='Z')
c += 'a'-'A';
null(c);
}
null(c)
{
*op = c;
op++;
if(++obc >= obs) {
flsh();
op = obuf;
}
}
ascii(cc)
{
register c;
c = etoa[cc] & 0377;
if(cbs == 0) {
cnull(c);
return;
}
if(c == ' ') {
nspace++;
goto out;
}
while(nspace > 0) {
null(' ');
nspace--;
}
cnull(c);
out:
if(++cbc >= cbs) {
null('\n');
cbc = 0;
nspace = 0;
}
}
ebcdic(cc)
{
register c;
c = cc;
if(cflag&UCASE && c>='a' && c<='z')
c += 'A'-'a';
if(cflag&LCASE && c>='A' && c<='Z')
c += 'a'-'A';
c = atoe[c] & 0377;
if(cbs == 0) {
null(c);
return;
}
if(cc == '\n') {
while(cbc < cbs) {
null(atoe[' ']);
cbc++;
}
cbc = 0;
return;
}
if(cbc == cbs)
ntrunc++;
cbc++;
if(cbc <= cbs)
null(c);
}
ibm(cc)
{
register c;
c = cc;
if(cflag&UCASE && c>='a' && c<='z')
c += 'A'-'a';
if(cflag&LCASE && c>='A' && c<='Z')
c += 'a'-'A';
c = atoibm[c] & 0377;
if(cbs == 0) {
null(c);
return;
}
if(cc == '\n') {
while(cbc < cbs) {
null(atoibm[' ']);
cbc++;
}
cbc = 0;
return;
}
if(cbc == cbs)
ntrunc++;
cbc++;
if(cbc <= cbs)
null(c);
}
term()
{
stats();
exit(0);
}
stats()
{
fprintf(stderr,"%u+%u records in\n", nifr, nipr);
fprintf(stderr,"%u+%u records out\n", nofr, nopr);
if(ntrunc)
fprintf(stderr,"%u truncated records\n", ntrunc);
}

18
v7/cmd/file.1#000000 Normal file
View File

@ -0,0 +1,18 @@
.TH FILE 1
.SH NAME
file \- determine file type
.SH SYNOPSIS
.B file
file ...
.SH DESCRIPTION
.I File
performs a series of tests on each argument
in an attempt to classify it.
If an argument appears to be ascii,
.I file
examines the first 512 bytes
and tries to guess its language.
.SH BUGS
It often makes mistakes.
In particular it often suggests that
command files are C programs.

330
v7/cmd/file.c#b00008 Normal file
View File

@ -0,0 +1,330 @@
/*
* determine type of file
*/
#include <sys/param.h>
#include <sys/stat.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(int, char**);
int type(char*);
int ascom(void);
int ccom(void);
int english (char *bp, int n);
int lookup(char *tab[]);
int in;
int i = 0;
char buf[512];
char *fort[] = {
"function","subroutine","common","dimension","block","integer",
"real","data","double",0};
char *asc[] = {
"sys","mov","tst","clr","jmp",0};
char *c[] = {
"int","char","float","double","struct","extern",0};
char *as[] = {
"globl","byte","even","text","data","bss","comm",0};
int ifile;
int main(int argc, char **argv)
{
FILE *fl;
register char *p;
char ap[128];
if (argc>1 && argv[1][0]=='-' && argv[1][1]=='f') {
if ((fl = fopen(argv[2], "r")) == NULL) {
printf("Can't open %s\n", argv[2]);
exit(2);
}
while ((p = fgets(ap, 128, fl)) != NULL) {
int l = strlen(p);
if (l>0)
p[l-1] = '\0';
printf("%s: ", p);
type(p);
if (ifile>=0)
close(ifile);
}
exit(1);
}
while(argc > 1) {
printf("%s: ", argv[1]);
type(argv[1]);
argc--;
argv++;
if (ifile >= 0)
close(ifile);
}
}
int type(char *file)
{
int j,nl;
char ch;
struct stat mbuf;
ifile = -1;
if(stat(file, &mbuf) < 0) {
printf("cannot stat\n");
return;
}
switch (mbuf.st_mode & S_IFMT) {
case S_IFCHR:
printf("character");
goto spcl;
case S_IFDIR:
printf("directory\n");
return;
case S_IFBLK:
printf("block");
spcl:
printf(" special (%d/%d)\n", major(mbuf.st_rdev), minor(mbuf.st_rdev));
return;
}
ifile = open(file, 0);
if(ifile < 0) {
printf("cannot open\n");
return;
}
in = read(ifile, buf, 512);
if(in == 0){
printf("empty\n");
return;
}
switch(*(int *)buf) {
case 0410:
printf("pure ");
goto exec;
case 0411:
printf("separate ");
case 0407:
exec:
printf("executable");
if(((int *)buf)[4] != 0)
printf(" not stripped");
printf("\n");
goto out;
case 0177555:
printf("old archive\n");
goto out;
case 0177545:
printf("archive\n");
goto out;
}
i = 0;
if(ccom() == 0)goto notc;
while(buf[i] == '#'){
j = i;
while(buf[i++] != '\n'){
if(i - j > 255){
printf("data\n");
goto out;
}
if(i >= in)goto notc;
}
if(ccom() == 0)goto notc;
}
check:
if(lookup(c) == 1){
while((ch = buf[i++]) != ';' && ch != '{')if(i >= in)goto notc;
printf("c program text");
goto outa;
}
nl = 0;
while(buf[i] != '('){
if(buf[i] <= 0)
goto notas;
if(buf[i] == ';'){
i++;
goto check;
}
if(buf[i++] == '\n')
if(nl++ > 6)goto notc;
if(i >= in)goto notc;
}
while(buf[i] != ')'){
if(buf[i++] == '\n')
if(nl++ > 6)goto notc;
if(i >= in)goto notc;
}
while(buf[i] != '{'){
if(buf[i++] == '\n')
if(nl++ > 6)goto notc;
if(i >= in)goto notc;
}
printf("c program text");
goto outa;
notc:
i = 0;
while(buf[i] == 'c' || buf[i] == '#'){
while(buf[i++] != '\n')if(i >= in)goto notfort;
}
if(lookup(fort) == 1){
printf("fortran program text");
goto outa;
}
notfort:
i=0;
if(ascom() == 0)goto notas;
j = i-1;
if(buf[i] == '.'){
i++;
if(lookup(as) == 1){
printf("assembler program text");
goto outa;
}
else if(buf[j] == '\n' && isalpha(buf[j+2])){
printf("roff, nroff, or eqn input text");
goto outa;
}
}
while(lookup(asc) == 0){
if(ascom() == 0)goto notas;
while(buf[i] != '\n' && buf[i++] != ':')
if(i >= in)goto notas;
while(buf[i] == '\n' || buf[i] == ' ' || buf[i] == '\t')if(i++ >= in)goto notas;
j = i-1;
if(buf[i] == '.'){
i++;
if(lookup(as) == 1){
printf("assembler program text");
goto outa;
}
else if(buf[j] == '\n' && isalpha(buf[j+2])){
printf("roff, nroff, or eqn input text");
goto outa;
}
}
}
printf("assembler program text");
goto outa;
notas:
for(i=0; i < in; i++)if(buf[i]&0200){
if (buf[0]=='\100' && buf[1]=='\357') {
printf("troff output\n");
goto out;
}
printf("data\n");
goto out;
}
if (mbuf.st_mode&((S_IEXEC)|(S_IEXEC>>3)|(S_IEXEC>>6)))
printf("commands text");
else
if (english(buf, in))
printf("English text");
else
printf("ascii text");
outa:
while(i < in)
if((buf[i++]&0377) > 127){
printf(" with garbage\n");
goto out;
}
/* if next few lines in then read whole file looking for nulls ...
while((in = read(ifile,buf,512)) > 0)
for(i = 0; i < in; i++)
if((buf[i]&0377) > 127){
printf(" with garbage\n");
goto out;
}
/*.... */
printf("\n");
out:;
}
int lookup(char *tab[])
{
char r;
int k,j,l;
while(buf[i] == ' ' || buf[i] == '\t' || buf[i] == '\n')i++;
for(j=0; tab[j] != 0; j++){
l=0;
for(k=i; ((r=tab[j][l++]) == buf[k] && r != '\0');k++);
if(r == '\0')
if(buf[k] == ' ' || buf[k] == '\n' || buf[k] == '\t'
|| buf[k] == '{' || buf[k] == '/'){
i=k;
return(1);
}
}
return(0);
}
int ccom(void){
char cc;
while((cc = buf[i]) == ' ' || cc == '\t' || cc == '\n')if(i++ >= in)return(0);
if(buf[i] == '/' && buf[i+1] == '*'){
i += 2;
while(buf[i] != '*' || buf[i+1] != '/'){
if(buf[i] == '\\')i += 2;
else i++;
if(i >= in)return(0);
}
if((i += 2) >= in)return(0);
}
if(buf[i] == '\n')if(ccom() == 0)return(0);
return(1);
}
int ascom(void){
while(buf[i] == '/'){
i++;
while(buf[i++] != '\n')if(i >= in)return(0);
while(buf[i] == '\n')if(i++ >= in)return(0);
}
return(1);
}
int english (char *bp, int n)
{
# define NASC 128
int ct[NASC], j, vow, freq, rare;
int badpun = 0, punct = 0;
if (n<50) return(0); /* no point in statistics on squibs */
for(j=0; j<NASC; j++)
ct[j]=0;
for(j=0; j<n; j++)
{
if (bp[j]<NASC)
ct[bp[j]|040]++;
switch (bp[j])
{
case '.':
case ',':
case ')':
case '%':
case ';':
case ':':
case '?':
punct++;
if ( j < n-1 &&
bp[j+1] != ' ' &&
bp[j+1] != '\n')
badpun++;
}
}
if (badpun*5 > punct)
return(0);
vow = ct['a'] + ct['e'] + ct['i'] + ct['o'] + ct['u'];
freq = ct['e'] + ct['t'] + ct['a'] + ct['i'] + ct['o'] + ct['n'];
rare = ct['v'] + ct['j'] + ct['k'] + ct['q'] + ct['x'] + ct['z'];
if (2*ct[';'] > ct['e']) return(0);
if ( (ct['>']+ct['<']+ct['/'])>ct['e']) return(0); /* shell file test */
return (vow*5 >= n-ct[' '] && freq >= 10*rare);
}

321
v7/cmd/file.c.orig#b00008 Normal file
View File

@ -0,0 +1,321 @@
/*
* determine type of file
*/
#include <sys/param.h>
#include <sys/stat.h>
#include <stdio.h>
#include <ctype.h>
int in;
int i = 0;
char buf[512];
char *fort[] = {
"function","subroutine","common","dimension","block","integer",
"real","data","double",0};
char *asc[] = {
"sys","mov","tst","clr","jmp",0};
char *c[] = {
"int","char","float","double","struct","extern",0};
char *as[] = {
"globl","byte","even","text","data","bss","comm",0};
int ifile;
main(argc, argv)
char **argv;
{
FILE *fl;
register char *p;
char ap[128];
if (argc>1 && argv[1][0]=='-' && argv[1][1]=='f') {
if ((fl = fopen(argv[2], "r")) == NULL) {
printf("Can't open %s\n", argv[2]);
exit(2);
}
while ((p = fgets(ap, 128, fl)) != NULL) {
int l = strlen(p);
if (l>0)
p[l-1] = '\0';
printf("%s: ", p);
type(p);
if (ifile>=0)
close(ifile);
}
exit(1);
}
while(argc > 1) {
printf("%s: ", argv[1]);
type(argv[1]);
argc--;
argv++;
if (ifile >= 0)
close(ifile);
}
}
type(file)
char *file;
{
int j,nl;
char ch;
struct stat mbuf;
ifile = -1;
if(stat(file, &mbuf) < 0) {
printf("cannot stat\n");
return;
}
switch (mbuf.st_mode & S_IFMT) {
case S_IFCHR:
printf("character");
goto spcl;
case S_IFDIR:
printf("directory\n");
return;
case S_IFBLK:
printf("block");
spcl:
printf(" special (%d/%d)\n", major(mbuf.st_rdev), minor(mbuf.st_rdev));
return;
}
ifile = open(file, 0);
if(ifile < 0) {
printf("cannot open\n");
return;
}
in = read(ifile, buf, 512);
if(in == 0){
printf("empty\n");
return;
}
switch(*(int *)buf) {
case 0410:
printf("pure ");
goto exec;
case 0411:
printf("separate ");
case 0407:
exec:
printf("executable");
if(((int *)buf)[4] != 0)
printf(" not stripped");
printf("\n");
goto out;
case 0177555:
printf("old archive\n");
goto out;
case 0177545:
printf("archive\n");
goto out;
}
i = 0;
if(ccom() == 0)goto notc;
while(buf[i] == '#'){
j = i;
while(buf[i++] != '\n'){
if(i - j > 255){
printf("data\n");
goto out;
}
if(i >= in)goto notc;
}
if(ccom() == 0)goto notc;
}
check:
if(lookup(c) == 1){
while((ch = buf[i++]) != ';' && ch != '{')if(i >= in)goto notc;
printf("c program text");
goto outa;
}
nl = 0;
while(buf[i] != '('){
if(buf[i] <= 0)
goto notas;
if(buf[i] == ';'){
i++;
goto check;
}
if(buf[i++] == '\n')
if(nl++ > 6)goto notc;
if(i >= in)goto notc;
}
while(buf[i] != ')'){
if(buf[i++] == '\n')
if(nl++ > 6)goto notc;
if(i >= in)goto notc;
}
while(buf[i] != '{'){
if(buf[i++] == '\n')
if(nl++ > 6)goto notc;
if(i >= in)goto notc;
}
printf("c program text");
goto outa;
notc:
i = 0;
while(buf[i] == 'c' || buf[i] == '#'){
while(buf[i++] != '\n')if(i >= in)goto notfort;
}
if(lookup(fort) == 1){
printf("fortran program text");
goto outa;
}
notfort:
i=0;
if(ascom() == 0)goto notas;
j = i-1;
if(buf[i] == '.'){
i++;
if(lookup(as) == 1){
printf("assembler program text");
goto outa;
}
else if(buf[j] == '\n' && isalpha(buf[j+2])){
printf("roff, nroff, or eqn input text");
goto outa;
}
}
while(lookup(asc) == 0){
if(ascom() == 0)goto notas;
while(buf[i] != '\n' && buf[i++] != ':')
if(i >= in)goto notas;
while(buf[i] == '\n' || buf[i] == ' ' || buf[i] == '\t')if(i++ >= in)goto notas;
j = i-1;
if(buf[i] == '.'){
i++;
if(lookup(as) == 1){
printf("assembler program text");
goto outa;
}
else if(buf[j] == '\n' && isalpha(buf[j+2])){
printf("roff, nroff, or eqn input text");
goto outa;
}
}
}
printf("assembler program text");
goto outa;
notas:
for(i=0; i < in; i++)if(buf[i]&0200){
if (buf[0]=='\100' && buf[1]=='\357') {
printf("troff output\n");
goto out;
}
printf("data\n");
goto out;
}
if (mbuf.st_mode&((S_IEXEC)|(S_IEXEC>>3)|(S_IEXEC>>6)))
printf("commands text");
else
if (english(buf, in))
printf("English text");
else
printf("ascii text");
outa:
while(i < in)
if((buf[i++]&0377) > 127){
printf(" with garbage\n");
goto out;
}
/* if next few lines in then read whole file looking for nulls ...
while((in = read(ifile,buf,512)) > 0)
for(i = 0; i < in; i++)
if((buf[i]&0377) > 127){
printf(" with garbage\n");
goto out;
}
/*.... */
printf("\n");
out:;
}
lookup(tab)
char *tab[];
{
char r;
int k,j,l;
while(buf[i] == ' ' || buf[i] == '\t' || buf[i] == '\n')i++;
for(j=0; tab[j] != 0; j++){
l=0;
for(k=i; ((r=tab[j][l++]) == buf[k] && r != '\0');k++);
if(r == '\0')
if(buf[k] == ' ' || buf[k] == '\n' || buf[k] == '\t'
|| buf[k] == '{' || buf[k] == '/'){
i=k;
return(1);
}
}
return(0);
}
ccom(){
char cc;
while((cc = buf[i]) == ' ' || cc == '\t' || cc == '\n')if(i++ >= in)return(0);
if(buf[i] == '/' && buf[i+1] == '*'){
i += 2;
while(buf[i] != '*' || buf[i+1] != '/'){
if(buf[i] == '\\')i += 2;
else i++;
if(i >= in)return(0);
}
if((i += 2) >= in)return(0);
}
if(buf[i] == '\n')if(ccom() == 0)return(0);
return(1);
}
ascom(){
while(buf[i] == '/'){
i++;
while(buf[i++] != '\n')if(i >= in)return(0);
while(buf[i] == '\n')if(i++ >= in)return(0);
}
return(1);
}
english (bp, n)
char *bp;
{
# define NASC 128
int ct[NASC], j, vow, freq, rare;
int badpun = 0, punct = 0;
if (n<50) return(0); /* no point in statistics on squibs */
for(j=0; j<NASC; j++)
ct[j]=0;
for(j=0; j<n; j++)
{
if (bp[j]<NASC)
ct[bp[j]|040]++;
switch (bp[j])
{
case '.':
case ',':
case ')':
case '%':
case ';':
case ':':
case '?':
punct++;
if ( j < n-1 &&
bp[j+1] != ' ' &&
bp[j+1] != '\n')
badpun++;
}
}
if (badpun*5 > punct)
return(0);
vow = ct['a'] + ct['e'] + ct['i'] + ct['o'] + ct['u'];
freq = ct['e'] + ct['t'] + ct['a'] + ct['i'] + ct['o'] + ct['n'];
rare = ct['v'] + ct['j'] + ct['k'] + ct['q'] + ct['x'] + ct['z'];
if (2*ct[';'] > ct['e']) return(0);
if ( (ct['>']+ct['<']+ct['/'])>ct['e']) return(0); /* shell file test */
return (vow*5 >= n-ct[' '] && freq >= 10*rare);
}

169
v7/cmd/find.1#000000 Normal file
View File

@ -0,0 +1,169 @@
.TH FIND 1
.SH NAME
find \- find files
.SH SYNOPSIS
.B find
pathname-list expression
.SH DESCRIPTION
.I Find
recursively descends
the directory hierarchy for
each pathname in the
.I pathname-list
(i.e., one or more pathnames)
seeking files that match a boolean
.I expression
written in the primaries given below.
In the descriptions, the argument
.I n
is used as a decimal integer
where
.I +n
means more than
.I n,
.I \-n
means less than
.I n
and
.I n
means exactly
.IR n .
.TP 10n
.BR \-name " filename"
True if the
.I filename
argument matches the current file name.
Normal
Shell
argument syntax may be used if escaped (watch out for
`[', `?' and `*').
.TP
.BR \-perm " onum"
True if the file permission flags
exactly
match the
octal number
.I onum
(see
.IR chmod (1)).
If
.I onum
is prefixed by a minus sign,
more flag bits (017777, see
.IR stat (2))
become significant and
the flags are compared:
.IR (flags&onum)==onum .
.TP
.BR \-type " c"
True if the type of the file
is
.I c,
where
.I c
is
.B "b, c, d"
or
.B f
for
block special file, character special file,
directory or plain file.
.TP
.BR \-links " n"
True if the file has
.I n
links.
.TP
.BR \-user " uname"
True if the file belongs to the user
.I uname
(login name or numeric user ID).
.TP
.BR \-group " gname"
True if the file belongs to group
.I gname
(group name or numeric group ID).
.TP
.BR \-size " n"
True if the file is
.I n
blocks long (512 bytes per block).
.TP
.BR \-inum " n"
True if the file has inode number
.I n.
.TP
.BR \-atime " n"
True if the file has been accessed in
.I n
days.
.TP
.BR \-mtime " n"
True if the file has been modified in
.I n
days.
.TP
.BR \-exec " command"
True if the executed command returns
a zero value as exit status.
The end of the command must be punctuated by an escaped
semicolon.
A command argument `{}' is replaced by the
current pathname.
.TP
.BR \-ok " command"
Like
.B \-exec
except that the generated command is written on
the standard output, then the standard input is read
and the command executed only upon response
.BR y .
.TP
.B \-print
Always true;
causes the current pathname to be printed.
.TP
.BR \-newer " file"
True if
the current file has been modified more recently than the argument
.I file.
.PP
The primaries may be combined using the following operators
(in order of decreasing precedence):
.TP 4
1)
A parenthesized group of primaries and operators
(parentheses are special to the Shell and must be escaped).
.TP 4
2)
The negation of a primary
(`!' is the unary
.I not
operator).
.TP 4
3)
Concatenation of primaries
(the
.I and
operation
is implied by the juxtaposition of two primaries).
.TP 4
4)
Alternation of primaries
.RB "(`" \-o "' is the"
.I or
operator).
.SH EXAMPLE
To remove all files named
`a.out' or `*.o' that have not been accessed for a week:
.IP "" .2i
find / \\( \-name a.out \-o \-name '*.o' \\)
\-atime +7 \-exec rm {} \\;
.SH FILES
/etc/passwd
.br
/etc/group
.SH "SEE ALSO"
sh(1), test(1), filsys(5)
.SH BUGS
The syntax is painful.

780
v7/cmd/find.c#b00008 Normal file
View File

@ -0,0 +1,780 @@
/* find COMPILE: cc -o find -s -O -i find.c -lS */
#pragma debug 8+64 /* No ORCA/C stack fixup */
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <sys/param.h>
#define FNAMELEN 255
#define A_DAY 86400L /* a day full of seconds */
#define EQ(x, y) (strcmp(x, y)==0)
time_t time(time_t*);
struct anode {
int (*F)(void *);
void *L, *R;
} Node[100];
int Randlast;
char Pathname[MAXPATHLEN];
int Nn; /* number of nodes */
char *Fname;
long Now;
int Argc, Ai, Pi;
char **Argv;
/* cpio stuff */
int Cpio;
short *Buf, *Dbuf, *Wp;
int Bufsize = 5120;
int Wct = 2560;
long Newer;
struct stat Statb;
char Home[MAXPATHLEN];
long Blocks;
int main(int argc, char *argv[]);
struct anode *_exp(void);
struct anode *e1(void);
struct anode *e2(void);
struct anode *e3(void);
struct anode *mk(void *f, void *l, void *r);
char *nxtarg(void);
int and(register struct anode *p);
int or(register struct anode *p);
int not(register struct anode *p);
int _glob(register struct anode *p);
int print(void);
int mtime(register struct anode *p);
int atime(register struct anode *p);
int _ctime(register struct anode *p);
int user(register struct anode *p);
int ino(register struct anode *p);
int group(register struct anode *p);
int links(register struct anode *p);
int size(register struct anode *p);
int perm(register struct anode *p);
int type(register struct anode *p);
int exeq(register struct anode *p);
int ok(register struct anode *p);
long mklong(short v[]);
void cpio(void);
int newer(void);
int scomp(register int a, register int b, register char s);
int doex(int com);
int getunum(char *f, char *s);
int descend(char *name, char *fname, struct anode *exlist);
int gmatch(register char *s, register char *p);
int amatch(register char *s, register char *p);
int umatch(register char *s, register char *p);
void bwrite(register short *rp, register int c);
int chgreel(int x, int fl);
void pr(char *s);
int main(int argc, char *argv[])
{
struct anode *exlist;
int paths;
register char *cp, *sp = 0;
FILE *pwd;
time(&Now);
getcwd(Home, MAXPATHLEN);
Argc = argc; Argv = argv;
if(argc<3) {
usage: pr("Usage: find path-list predicate-list\n");
exit(1);
}
for(Ai = paths = 1; Ai < (argc-1); ++Ai, ++paths)
if(*Argv[Ai] == '-' || EQ(Argv[Ai], "(") || EQ(Argv[Ai], "!"))
break;
if(paths == 1) /* no path-list */
goto usage;
if(!(exlist = _exp())) { /* parse and compile the arguments */
pr("find: parsing error\n");
exit(1);
}
if(Ai<argc) {
pr("find: missing conjunction\n");
exit(1);
}
for(Pi = 1; Pi < paths; ++Pi) {
sp = 0;
chdir(Home);
strcpy(Pathname, Argv[Pi]);
if((cp = rindex(Pathname, '/'))) {
sp = cp + 1;
*cp = '\0';
if(chdir(*Pathname? Pathname: "/") == -1) {
pr("find: bad starting directory\n");
exit(2);
}
*cp = '/';
}
Fname = sp? sp: Pathname;
descend(Pathname, Fname, exlist); /* to find files that match */
}
if(Cpio) {
strcpy(Pathname, "TRAILER!!!");
Statb.st_size = 0;
cpio();
}
exit(0);
}
/* compile time functions: priority is _exp()<e1()<e2()<e3() */
struct anode *_exp(void) { /* parse ALTERNATION (-o) */
register struct anode * p1;
p1 = e1() /* get left operand */ ;
if(EQ(nxtarg(), "-o")) {
Randlast--;
return(mk(or, p1, _exp()));
}
else if(Ai <= Argc) --Ai;
return(p1);
}
struct anode *e1(void) { /* parse CONCATENATION (formerly -a) */
register struct anode * p1;
register char *a;
p1 = e2();
a = nxtarg();
if(EQ(a, "-a")) {
And:
Randlast--;
return(mk(and, p1, e1()));
} else if(EQ(a, "(") || EQ(a, "!") || (*a=='-' && !EQ(a, "-o"))) {
--Ai;
goto And;
} else if(Ai <= Argc) --Ai;
return(p1);
}
struct anode *e2(void) { /* parse NOT (!) */
if(Randlast) {
pr("find: operand follows operand\n");
exit(1);
}
Randlast++;
if(EQ(nxtarg(), "!"))
return(mk(not, e3(), 0));
else if(Ai <= Argc) --Ai;
return(e3());
}
struct anode *e3(void) { /* parse parens and predicates */
struct anode *p1;
int i, s;
register char *a, *b;
a = nxtarg();
if(EQ(a, "(")) {
Randlast--;
p1 = _exp();
a = nxtarg();
if(!EQ(a, ")")) goto err;
return(p1);
}
else if(EQ(a, "-print")) {
return(mk(print, 0, 0));
}
b = nxtarg();
s = *b;
if(s=='+') b++;
if(EQ(a, "-name"))
return(mk(_glob, b, 0));
else if(EQ(a, "-mtime"))
return(mk(mtime, (void*)atoi(b), (void*)s));
else if(EQ(a, "-atime"))
return(mk(atime, (void*)atoi(b), (void*)s));
else if(EQ(a, "-ctime"))
return(mk(_ctime, (void*)atoi(b), (void*)s));
else if(EQ(a, "-user")) {
if((i=getunum("/etc/passwd", b)) == -1) {
if(gmatch(b, "[0-9][0-9][0-9]*")
|| gmatch(b, "[0-9][0-9]")
|| gmatch(b, "[0-9]"))
return mk(user, (void*)atoi(b), (void*)s);
pr("find: cannot find -user name\n");
exit(1);
}
return(mk(user, (void*)i, (void*)s));
}
else if(EQ(a, "-inum"))
return(mk(ino, (void*)atoi(b), (void*)s));
else if(EQ(a, "-group")) {
if((i=getunum("/etc/group", b)) == -1) {
if(gmatch(b, "[0-9][0-9][0-9]*")
|| gmatch(b, "[0-9][0-9]")
|| gmatch(b, "[0-9]"))
return mk(group, (void*)atoi(b), (void*)s);
pr("find: cannot find -group name\n");
exit(1);
}
return(mk(group, (void*)i, (void*)s));
} else if(EQ(a, "-size"))
return(mk(size, (void*)atoi(b), (void*)s));
else if(EQ(a, "-links"))
return(mk(links, (void*)atoi(b), (void*)s));
else if(EQ(a, "-perm")) {
for(i=0; *b ; ++b) {
if(*b=='-') continue;
i <<= 3;
i = i + (*b - '0');
}
return(mk(perm, (void*)i, (void*)s));
}
else if(EQ(a, "-type")) {
i = s=='d' ? S_IFDIR :
s=='b' ? S_IFBLK :
s=='c' ? S_IFCHR :
s=='f' ? 0100000 :
0;
return(mk(type, (void*)i, 0));
}
else if (EQ(a, "-exec")) {
i = Ai - 1;
while(!EQ(nxtarg(), ";"));
return(mk(exeq, (void*)i, 0));
}
else if (EQ(a, "-ok")) {
i = Ai - 1;
while(!EQ(nxtarg(), ";"));
return(mk(ok, (void*)i, 0));
}
else if(EQ(a, "-cpio")) {
if((Cpio = creat(b, 0666)) < 0) {
pr("find: cannot create "), pr(b), pr("\n");
exit(1);
}
Buf = (short *)malloc(512);
Wp = Dbuf = (short *)malloc(5120);
return(mk(cpio, 0, 0));
}
else if(EQ(a, "-newer")) {
if(stat(b, &Statb) < 0) {
pr("find: cannot access "), pr(b), pr("\n");
exit(1);
}
Newer = Statb.st_mtime;
return mk(newer, 0, 0);
}
err: pr("find: bad option "), pr(a), pr("\n");
exit(1);
}
struct anode *mk(void *f, void *l, void *r)
{
Node[Nn].F = f;
Node[Nn].L = l;
Node[Nn].R = r;
return(&(Node[Nn++]));
}
char *nxtarg(void) { /* get next arg from command line */
static int strikes = 0;
if(strikes==3) {
pr("find: incomplete statement\n");
exit(1);
}
if(Ai>=Argc) {
strikes++;
Ai = Argc + 1;
return("");
}
return(Argv[Ai++]);
}
/* execution time functions */
int and(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(((*L->F)(p->L)) && ((*R->F)(R))?1:0);
}
int or(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(((*L->F)(L)) || ((*R->F)(R))?1:0);
}
int not(register struct anode *p)
{
struct anode *L = p->L;
return( !((*L->F)(L)));
}
int _glob(register struct anode *p)
{
struct anode *L = p->L;
return(gmatch(Fname, (char*)L));
}
int print(void)
{
puts(Pathname);
return(1);
}
int mtime(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)((Now - Statb.st_mtime) / A_DAY), (int)L, (char)R));
}
int atime(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)((Now - Statb.st_atime) / A_DAY), (int)L, (char)R));
}
int _ctime(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)((Now - Statb.st_ctime) / A_DAY), (int)L, (char)R));
}
int user(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp(Statb.st_uid, (int)L, (char)R));
}
int ino(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)Statb.st_ino, (int)L, (char)R));
}
int group(register struct anode *p)
{
struct anode *L = p->L;
return((int)L == Statb.st_gid);
}
int links(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp(Statb.st_nlink, (int)L, (char)R));
}
int size(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)((Statb.st_size+511)>>9), (int)L, (char)R));
}
int perm(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
register int i;
i = ((char)R=='-') ? (int)L : 07777; /* '-' means only arg bits */
return((Statb.st_mode & i & 07777) == (int)L);
}
int type(register struct anode *p)
{
struct anode *L = p->L;
return((Statb.st_mode&S_IFMT)==(int)L);
}
int exeq(register struct anode *p)
{
struct anode *L = p->L;
fflush(stdout); /* to flush possible `-print' */
return(doex((int)L));
}
int ok(register struct anode *p)
{
struct anode *L = p->L;
int c; int yes;
yes = 0;
fflush(stdout); /* to flush possible `-print' */
pr("< "), pr(Argv[(int)L]), pr(" ... "), pr(Pathname), pr(" >? ");
fflush(stderr);
if((c=getchar())=='y') yes = 1;
while(c!='\n')
if(c==EOF)
exit(2);
else
c = getchar();
if(yes) return(doex((int)L));
return(0);
}
#define MKSHORT(v, lv) {U.l=1L;if(U.c[0]) U.l=lv, v[0]=U.s[1], v[1]=U.s[0]; else U.l=lv, v[0]=U.s[0], v[1]=U.s[1];}
union { long l; short s[2]; char c[4]; } U;
long mklong(short v[])
{
U.l = 1;
if(U.c[0] /* VAX */)
U.s[0] = v[1], U.s[1] = v[0];
else
U.s[0] = v[0], U.s[1] = v[1];
return U.l;
}
void cpio(void)
{
#define MAGIC 070707
struct header {
short h_magic,
h_dev,
h_ino,
h_mode,
h_uid,
h_gid,
h_nlink,
h_rdev;
short h_mtime[2];
short h_namesize;
short h_filesize[2];
char h_name[256];
} hdr;
register int ifile, ct;
static long fsz;
register int i;
hdr.h_magic = MAGIC;
strcpy(hdr.h_name, !strncmp(Pathname, "./", 2)? Pathname+2: Pathname);
hdr.h_namesize = strlen(hdr.h_name) + 1;
hdr.h_uid = Statb.st_uid;
hdr.h_gid = Statb.st_gid;
hdr.h_dev = Statb.st_dev;
hdr.h_ino = Statb.st_ino;
hdr.h_mode = Statb.st_mode;
MKSHORT(hdr.h_mtime, Statb.st_mtime);
hdr.h_nlink = Statb.st_nlink;
fsz = hdr.h_mode & S_IFREG? Statb.st_size: 0L;
MKSHORT(hdr.h_filesize, fsz);
hdr.h_rdev = Statb.st_rdev;
if(EQ(hdr.h_name, "TRAILER!!!")) {
bwrite((short *)&hdr, (sizeof hdr-256)+hdr.h_namesize);
for(i = 0; i < 10; ++i)
bwrite(Buf, 512);
return;
}
if(!mklong(hdr.h_filesize)) {
bwrite((short *)&hdr, (sizeof hdr-256)+hdr.h_namesize);
return;
}
if((ifile = open(Fname, 0)) < 0) {
cerror:
pr("find: cannot copy "), pr(hdr.h_name), pr("\n");
return;
}
bwrite((short *)&hdr, (sizeof hdr-256)+hdr.h_namesize);
for(fsz = mklong(hdr.h_filesize); fsz > 0; fsz -= 512) {
ct = fsz>512? 512: fsz;
if(read(ifile, (char *)Buf, ct) < 0)
goto cerror;
bwrite(Buf, ct);
}
close(ifile);
return;
}
int newer(void)
{
return Statb.st_mtime > Newer;
}
/* support functions */
int scomp(register int a, register int b, register char s) /* funny signed compare */
{
if(s == '+')
return(a > b);
if(s == '-')
return(a < (b * -1));
return(a == b);
}
/* Child entry point for GNO fork2() */
void child(char **nargv) {
chdir(Home);
execvp(nargv[0], nargv);
}
int doex(int com)
{
static char *nargv[50];
register int np;
register char *na;
union wait ccode;
np = 0;
while ((na=Argv[com++])) {
if(strcmp(na, ";")==0) break;
if(strcmp(na, "{}")==0) nargv[np++] = Pathname;
else nargv[np++] = na;
}
nargv[np] = 0;
if (np==0) return(9);
if(fork2(child, 1024, 0, "find", 2, nargv)) wait(&ccode);
return(*((int*)&ccode) ? 0:1);
}
int getunum(char *f, char *s) { /* find user/group name and return number */
register int i;
register char *sp;
register int c;
char str[20];
FILE *pin;
i = -1;
pin = fopen(f, "r");
c = '\n'; /* prime with a CR */
do {
if(c=='\n') {
sp = str;
while((c = *sp++ = getc(pin)) != ':')
if(c == EOF) goto RET;
*--sp = '\0';
if(EQ(str, s)) {
while((c=getc(pin)) != ':')
if(c == EOF) goto RET;
sp = str;
while((*sp = getc(pin)) != ':') sp++;
*sp = '\0';
i = atoi(str);
goto RET;
}
}
} while((c = getc(pin)) != EOF);
RET:
fclose(pin);
return(i);
}
/*
* name - Full pathname of current file or directory ("/foo/bar/baz")
* fname - Name of leaf node file or directory ("baz")
* exlist - Expression list
* Returns 0 if we are done with subtree, 1 if we should continue
*/
int descend(char *name, char *fname, struct anode *exlist) {
DIR *dp;
struct dirent *entry;
int rv = 0, i;
char *c1, *c2, *endofname;
if (lstat(fname, &Statb) < 0) {
printf("find: bad status-- %s\n", name);
return 0;
}
(*exlist->F)(exlist);
/* If it's a symlink we are done */
if ((Statb.st_mode & S_IFMT) == S_IFLNK) {
return 1;
}
/* If it's not a directory we are done */
if ((Statb.st_mode & S_IFMT) != S_IFDIR) return 1;
/* Find first '/' in name */
for (c1 = name; *c1; ++c1);
if (*(c1-1) == '/') --c1;
endofname = c1;
/* If we can't enter & open directory we are done */
if (chdir(fname) == -1) return 0;
dp = opendir(".");
if (!dp) {
printf("find: cannot open %s\n", name);
rv = 0;
goto done;
}
errno = 0;
for (;;) {
entry = readdir(dp);
if (!entry) {
//if (errno != 0) {
// printf("find: cannot read %s (%d)\n", name, errno);
//}
rv = 0;
goto done;
}
/* Skip . and .. */
if (strcmp(entry->d_name, ".") == 0) continue;
if (strcmp(entry->d_name, "..") == 0) continue;
c1 = endofname;
*c1++ = '/';
c2 = entry->d_name;
for (i=0; i<FNAMELEN; ++i)
if (*c2) *c1++ = *c2++;
else break;
*c1 = '\0';
if (c1 == endofname) {
rv = 0;
goto done;
}
Fname = endofname + 1;
if (!descend(name, Fname, exlist)) {
*endofname = '\0';
chdir(Home);
if (chdir(Pathname) == -1) {
puts("find: bad directory tree\n");
exit(1);
}
}
}
rv = 1;
done:
if (dp) closedir(dp);
if (chdir("..") == -1) {
*endofname = '\0';
printf("find: bad directory %s\n", name);
rv = 1;
}
return rv;
}
int gmatch(register char *s, register char *p) /* string match as in glob */
{
if (*s=='.' && *p!='.') return(0);
return amatch(s, p);
}
int amatch(register char *s, register char *p) /* string match as in glob */
{
register int cc;
int scc, k;
int c, lc;
scc = *s;
lc = 077777;
switch (c = *p) {
case '[':
k = 0;
while ((cc = *++p)) {
switch (cc) {
case ']':
if (k)
return(amatch(++s, ++p));
else
return(0);
case '-':
k |= (lc <= scc) & (scc <= (cc=p[1]));
}
if (scc==(lc=cc)) k++;
}
return(0);
case '?':
caseq:
if(scc) return(amatch(++s, ++p));
return(0);
case '*':
return(umatch(s, ++p));
case 0:
return(!scc);
}
if (c==scc) goto caseq;
return(0);
}
int umatch(register char *s, register char *p)
{
if(*p==0) return(1);
while(*s)
if (amatch(s++, p)) return(1);
return(0);
}
void bwrite(register short *rp, register int c)
{
register short *wp = Wp;
c = (c+1) >> 1;
while(c--) {
if(!Wct) {
again:
if(write(Cpio, (char *)Dbuf, Bufsize)<0) {
Cpio = chgreel(1, Cpio);
goto again;
}
Wct = Bufsize >> 1;
wp = Dbuf;
++Blocks;
}
*wp++ = *rp++;
--Wct;
}
Wp = wp;
}
int chgreel(int x, int fl)
{
register int f;
char str[22];
FILE *devtty;
struct stat statb;
pr("find: can't "), pr(x? "write output": "read input"), pr("\n");
fstat(fl, &statb);
if((statb.st_mode&S_IFMT) != S_IFCHR)
exit(1);
again:
pr("If you want to go on, type device/file name when ready\n");
devtty = fopen("/dev/tty", "r");
fgets(str, 20, devtty);
str[strlen(str) - 1] = '\0';
if(!*str)
exit(1);
close(fl);
if((f = open(str, x? 1: 0)) < 0) {
pr("That didn't work");
fclose(devtty);
goto again;
}
return f;
}
void pr(char *s)
{
fputs(s, stderr);
}

780
v7/cmd/find.c.BACKUP#b00008 Normal file
View File

@ -0,0 +1,780 @@
/* find COMPILE: cc -o find -s -O -i find.c -lS */
#pragma debug 8+64 /* No ORCA/C stack fixup */
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <sys/param.h>
#define FNAMELEN 255
#define A_DAY 86400L /* a day full of seconds */
#define EQ(x, y) (strcmp(x, y)==0)
time_t time(time_t*);
struct anode {
int (*F)(void *);
void *L, *R;
} Node[100];
int Randlast;
char Pathname[MAXPATHLEN];
int Nn; /* number of nodes */
char *Fname;
long Now;
int Argc, Ai, Pi;
char **Argv;
/* cpio stuff */
int Cpio;
short *Buf, *Dbuf, *Wp;
int Bufsize = 5120;
int Wct = 2560;
long Newer;
struct stat Statb;
char Home[MAXPATHLEN];
long Blocks;
int main(int argc, char *argv[]);
struct anode *_exp(void);
struct anode *e1(void);
struct anode *e2(void);
struct anode *e3(void);
struct anode *mk(void *f, void *l, void *r);
char *nxtarg(void);
int and(register struct anode *p);
int or(register struct anode *p);
int not(register struct anode *p);
int _glob(register struct anode *p);
int print(void);
int mtime(register struct anode *p);
int atime(register struct anode *p);
int _ctime(register struct anode *p);
int user(register struct anode *p);
int ino(register struct anode *p);
int group(register struct anode *p);
int links(register struct anode *p);
int size(register struct anode *p);
int perm(register struct anode *p);
int type(register struct anode *p);
int exeq(register struct anode *p);
int ok(register struct anode *p);
long mklong(short v[]);
void cpio(void);
int newer(void);
int scomp(register int a, register int b, register char s);
int doex(int com);
int getunum(char *f, char *s);
int descend(char *name, char *fname, struct anode *exlist);
int gmatch(register char *s, register char *p);
int amatch(register char *s, register char *p);
int umatch(register char *s, register char *p);
void bwrite(register short *rp, register int c);
int chgreel(int x, int fl);
void pr(char *s);
int main(int argc, char *argv[])
{
struct anode *exlist;
int paths;
register char *cp, *sp = 0;
FILE *pwd;
time(&Now);
getcwd(Home, MAXPATHLEN);
Argc = argc; Argv = argv;
if(argc<3) {
usage: pr("Usage: find path-list predicate-list\n");
exit(1);
}
for(Ai = paths = 1; Ai < (argc-1); ++Ai, ++paths)
if(*Argv[Ai] == '-' || EQ(Argv[Ai], "(") || EQ(Argv[Ai], "!"))
break;
if(paths == 1) /* no path-list */
goto usage;
if(!(exlist = _exp())) { /* parse and compile the arguments */
pr("find: parsing error\n");
exit(1);
}
if(Ai<argc) {
pr("find: missing conjunction\n");
exit(1);
}
for(Pi = 1; Pi < paths; ++Pi) {
sp = 0;
chdir(Home);
strcpy(Pathname, Argv[Pi]);
if((cp = rindex(Pathname, '/'))) {
sp = cp + 1;
*cp = '\0';
if(chdir(*Pathname? Pathname: "/") == -1) {
pr("find: bad starting directory\n");
exit(2);
}
*cp = '/';
}
Fname = sp? sp: Pathname;
descend(Pathname, Fname, exlist); /* to find files that match */
}
if(Cpio) {
strcpy(Pathname, "TRAILER!!!");
Statb.st_size = 0;
cpio();
}
exit(0);
}
/* compile time functions: priority is _exp()<e1()<e2()<e3() */
struct anode *_exp(void) { /* parse ALTERNATION (-o) */
register struct anode * p1;
p1 = e1() /* get left operand */ ;
if(EQ(nxtarg(), "-o")) {
Randlast--;
return(mk(or, p1, _exp()));
}
else if(Ai <= Argc) --Ai;
return(p1);
}
struct anode *e1(void) { /* parse CONCATENATION (formerly -a) */
register struct anode * p1;
register char *a;
p1 = e2();
a = nxtarg();
if(EQ(a, "-a")) {
And:
Randlast--;
return(mk(and, p1, e1()));
} else if(EQ(a, "(") || EQ(a, "!") || (*a=='-' && !EQ(a, "-o"))) {
--Ai;
goto And;
} else if(Ai <= Argc) --Ai;
return(p1);
}
struct anode *e2(void) { /* parse NOT (!) */
if(Randlast) {
pr("find: operand follows operand\n");
exit(1);
}
Randlast++;
if(EQ(nxtarg(), "!"))
return(mk(not, e3(), 0));
else if(Ai <= Argc) --Ai;
return(e3());
}
struct anode *e3(void) { /* parse parens and predicates */
struct anode *p1;
int i, s;
register char *a, *b;
a = nxtarg();
if(EQ(a, "(")) {
Randlast--;
p1 = _exp();
a = nxtarg();
if(!EQ(a, ")")) goto err;
return(p1);
}
else if(EQ(a, "-print")) {
return(mk(print, 0, 0));
}
b = nxtarg();
s = *b;
if(s=='+') b++;
if(EQ(a, "-name"))
return(mk(_glob, b, 0));
else if(EQ(a, "-mtime"))
return(mk(mtime, (void*)atoi(b), (void*)s));
else if(EQ(a, "-atime"))
return(mk(atime, (void*)atoi(b), (void*)s));
else if(EQ(a, "-ctime"))
return(mk(_ctime, (void*)atoi(b), (void*)s));
else if(EQ(a, "-user")) {
if((i=getunum("/etc/passwd", b)) == -1) {
if(gmatch(b, "[0-9][0-9][0-9]*")
|| gmatch(b, "[0-9][0-9]")
|| gmatch(b, "[0-9]"))
return mk(user, (void*)atoi(b), (void*)s);
pr("find: cannot find -user name\n");
exit(1);
}
return(mk(user, (void*)i, (void*)s));
}
else if(EQ(a, "-inum"))
return(mk(ino, (void*)atoi(b), (void*)s));
else if(EQ(a, "-group")) {
if((i=getunum("/etc/group", b)) == -1) {
if(gmatch(b, "[0-9][0-9][0-9]*")
|| gmatch(b, "[0-9][0-9]")
|| gmatch(b, "[0-9]"))
return mk(group, (void*)atoi(b), (void*)s);
pr("find: cannot find -group name\n");
exit(1);
}
return(mk(group, (void*)i, (void*)s));
} else if(EQ(a, "-size"))
return(mk(size, (void*)atoi(b), (void*)s));
else if(EQ(a, "-links"))
return(mk(links, (void*)atoi(b), (void*)s));
else if(EQ(a, "-perm")) {
for(i=0; *b ; ++b) {
if(*b=='-') continue;
i <<= 3;
i = i + (*b - '0');
}
return(mk(perm, (void*)i, (void*)s));
}
else if(EQ(a, "-type")) {
i = s=='d' ? S_IFDIR :
s=='b' ? S_IFBLK :
s=='c' ? S_IFCHR :
s=='f' ? 0100000 :
0;
return(mk(type, (void*)i, 0));
}
else if (EQ(a, "-exec")) {
i = Ai - 1;
while(!EQ(nxtarg(), ";"));
return(mk(exeq, (void*)i, 0));
}
else if (EQ(a, "-ok")) {
i = Ai - 1;
while(!EQ(nxtarg(), ";"));
return(mk(ok, (void*)i, 0));
}
else if(EQ(a, "-cpio")) {
if((Cpio = creat(b, 0666)) < 0) {
pr("find: cannot create "), pr(b), pr("\n");
exit(1);
}
Buf = (short *)malloc(512);
Wp = Dbuf = (short *)malloc(5120);
return(mk(cpio, 0, 0));
}
else if(EQ(a, "-newer")) {
if(stat(b, &Statb) < 0) {
pr("find: cannot access "), pr(b), pr("\n");
exit(1);
}
Newer = Statb.st_mtime;
return mk(newer, 0, 0);
}
err: pr("find: bad option "), pr(a), pr("\n");
exit(1);
}
struct anode *mk(void *f, void *l, void *r)
{
Node[Nn].F = f;
Node[Nn].L = l;
Node[Nn].R = r;
return(&(Node[Nn++]));
}
char *nxtarg(void) { /* get next arg from command line */
static int strikes = 0;
if(strikes==3) {
pr("find: incomplete statement\n");
exit(1);
}
if(Ai>=Argc) {
strikes++;
Ai = Argc + 1;
return("");
}
return(Argv[Ai++]);
}
/* execution time functions */
int and(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(((*L->F)(p->L)) && ((*R->F)(R))?1:0);
}
int or(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(((*L->F)(L)) || ((*R->F)(R))?1:0);
}
int not(register struct anode *p)
{
struct anode *L = p->L;
return( !((*L->F)(L)));
}
int _glob(register struct anode *p)
{
struct anode *L = p->L;
return(gmatch(Fname, (char*)L));
}
int print(void)
{
puts(Pathname);
return(1);
}
int mtime(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)((Now - Statb.st_mtime) / A_DAY), (int)L, (char)R));
}
int atime(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)((Now - Statb.st_atime) / A_DAY), (int)L, (char)R));
}
int _ctime(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)((Now - Statb.st_ctime) / A_DAY), (int)L, (char)R));
}
int user(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp(Statb.st_uid, (int)L, (char)R));
}
int ino(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)Statb.st_ino, (int)L, (char)R));
}
int group(register struct anode *p)
{
struct anode *L = p->L;
return((int)L == Statb.st_gid);
}
int links(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp(Statb.st_nlink, (int)L, (char)R));
}
int size(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
return(scomp((int)((Statb.st_size+511)>>9), (int)L, (char)R));
}
int perm(register struct anode *p)
{
struct anode *L = p->L;
struct anode *R = p->R;
register int i;
i = ((char)R=='-') ? (int)L : 07777; /* '-' means only arg bits */
return((Statb.st_mode & i & 07777) == (int)L);
}
int type(register struct anode *p)
{
struct anode *L = p->L;
return((Statb.st_mode&S_IFMT)==(int)L);
}
int exeq(register struct anode *p)
{
struct anode *L = p->L;
fflush(stdout); /* to flush possible `-print' */
return(doex((int)L));
}
int ok(register struct anode *p)
{
struct anode *L = p->L;
int c; int yes;
yes = 0;
fflush(stdout); /* to flush possible `-print' */
pr("< "), pr(Argv[(int)L]), pr(" ... "), pr(Pathname), pr(" >? ");
fflush(stderr);
if((c=getchar())=='y') yes = 1;
while(c!='\n')
if(c==EOF)
exit(2);
else
c = getchar();
if(yes) return(doex((int)L));
return(0);
}
#define MKSHORT(v, lv) {U.l=1L;if(U.c[0]) U.l=lv, v[0]=U.s[1], v[1]=U.s[0]; else U.l=lv, v[0]=U.s[0], v[1]=U.s[1];}
union { long l; short s[2]; char c[4]; } U;
long mklong(short v[])
{
U.l = 1;
if(U.c[0] /* VAX */)
U.s[0] = v[1], U.s[1] = v[0];
else
U.s[0] = v[0], U.s[1] = v[1];
return U.l;
}
void cpio(void)
{
#define MAGIC 070707
struct header {
short h_magic,
h_dev,
h_ino,
h_mode,
h_uid,
h_gid,
h_nlink,
h_rdev;
short h_mtime[2];
short h_namesize;
short h_filesize[2];
char h_name[256];
} hdr;
register int ifile, ct;
static long fsz;
register int i;
hdr.h_magic = MAGIC;
strcpy(hdr.h_name, !strncmp(Pathname, "./", 2)? Pathname+2: Pathname);
hdr.h_namesize = strlen(hdr.h_name) + 1;
hdr.h_uid = Statb.st_uid;
hdr.h_gid = Statb.st_gid;
hdr.h_dev = Statb.st_dev;
hdr.h_ino = Statb.st_ino;
hdr.h_mode = Statb.st_mode;
MKSHORT(hdr.h_mtime, Statb.st_mtime);
hdr.h_nlink = Statb.st_nlink;
fsz = hdr.h_mode & S_IFREG? Statb.st_size: 0L;
MKSHORT(hdr.h_filesize, fsz);
hdr.h_rdev = Statb.st_rdev;
if(EQ(hdr.h_name, "TRAILER!!!")) {
bwrite((short *)&hdr, (sizeof hdr-256)+hdr.h_namesize);
for(i = 0; i < 10; ++i)
bwrite(Buf, 512);
return;
}
if(!mklong(hdr.h_filesize)) {
bwrite((short *)&hdr, (sizeof hdr-256)+hdr.h_namesize);
return;
}
if((ifile = open(Fname, 0)) < 0) {
cerror:
pr("find: cannot copy "), pr(hdr.h_name), pr("\n");
return;
}
bwrite((short *)&hdr, (sizeof hdr-256)+hdr.h_namesize);
for(fsz = mklong(hdr.h_filesize); fsz > 0; fsz -= 512) {
ct = fsz>512? 512: fsz;
if(read(ifile, (char *)Buf, ct) < 0)
goto cerror;
bwrite(Buf, ct);
}
close(ifile);
return;
}
int newer(void)
{
return Statb.st_mtime > Newer;
}
/* support functions */
int scomp(register int a, register int b, register char s) /* funny signed compare */
{
if(s == '+')
return(a > b);
if(s == '-')
return(a < (b * -1));
return(a == b);
}
/* Child entry point for GNO fork2() */
void child(char **nargv) {
chdir(Home);
execvp(nargv[0], nargv);
}
int doex(int com)
{
static char *nargv[50];
register int np;
register char *na;
union wait ccode;
np = 0;
while ((na=Argv[com++])) {
if(strcmp(na, ";")==0) break;
if(strcmp(na, "{}")==0) nargv[np++] = Pathname;
else nargv[np++] = na;
}
nargv[np] = 0;
if (np==0) return(9);
if(fork2(child, 1024, 0, "find", 2, nargv)) wait(&ccode);
return(*((int*)&ccode) ? 0:1);
}
int getunum(char *f, char *s) { /* find user/group name and return number */
register int i;
register char *sp;
register int c;
char str[20];
FILE *pin;
i = -1;
pin = fopen(f, "r");
c = '\n'; /* prime with a CR */
do {
if(c=='\n') {
sp = str;
while((c = *sp++ = getc(pin)) != ':')
if(c == EOF) goto RET;
*--sp = '\0';
if(EQ(str, s)) {
while((c=getc(pin)) != ':')
if(c == EOF) goto RET;
sp = str;
while((*sp = getc(pin)) != ':') sp++;
*sp = '\0';
i = atoi(str);
goto RET;
}
}
} while((c = getc(pin)) != EOF);
RET:
fclose(pin);
return(i);
}
/*
* name - Full pathname of current file or directory ("/foo/bar/baz")
* fname - Name of leaf node file or directory ("baz")
* exlist - Expression list
* Returns 0 if we are done with subtree, 1 if we should continue
*/
int descend(char *name, char *fname, struct anode *exlist) {
DIR *dp;
struct dirent *entry;
int rv = 0, i;
char *c1, *c2, *endofname;
if (lstat(fname, &Statb) < 0) {
printf("find: bad status-- %s\n", name);
return 0;
}
(*exlist->F)(exlist);
/* If it's a symlink we are done */
if ((Statb.st_mode & S_IFMT) == S_IFLNK) {
return 1;
}
/* If it's not a directory we are done */
if ((Statb.st_mode & S_IFMT) != S_IFDIR) return 1;
/* Find first '/' in name */
for (c1 = name; *c1; ++c1);
if (*(c1-1) == '/') --c1;
endofname = c1;
/* If we can't enter & open directory we are done */
if (chdir(fname) == -1) return 0;
dp = opendir(".");
if (!dp) {
printf("find: cannot open %s\n", name);
rv = 0;
goto done;
}
errno = 0;
for (;;) {
entry = readdir(dp);
if (!entry) {
//if (errno != 0) {
// printf("find: cannot read %s (%d)\n", name, errno);
//}
rv = 0;
goto done;
}
/* Skip . and .. */
if (strcmp(entry->d_name, ".") == 0) continue;
if (strcmp(entry->d_name, "..") == 0) continue;
c1 = endofname;
*c1++ = '/';
c2 = entry->d_name;
for (i=0; i<FNAMELEN; ++i)
if (*c2) *c1++ = *c2++;
else break;
*c1 = '\0';
if (c1 == endofname) {
rv = 0;
goto done;
}
Fname = endofname + 1;
if (!descend(name, Fname, exlist)) {
*endofname = '\0';
chdir(Home);
if (chdir(Pathname) == -1) {
puts("find: bad directory tree\n");
exit(1);
}
}
}
rv = 1;
done:
if (dp) closedir(dp);
if (chdir("..") == -1) {
*endofname = '\0';
printf("find: bad directory %s\n", name);
rv = 1;
}
return rv;
}
int gmatch(register char *s, register char *p) /* string match as in glob */
{
if (*s=='.' && *p!='.') return(0);
return amatch(s, p);
}
int amatch(register char *s, register char *p) /* string match as in glob */
{
register int cc;
int scc, k;
int c, lc;
scc = *s;
lc = 077777;
switch (c = *p) {
case '[':
k = 0;
while ((cc = *++p)) {
switch (cc) {
case ']':
if (k)
return(amatch(++s, ++p));
else
return(0);
case '-':
k |= (lc <= scc) & (scc <= (cc=p[1]));
}
if (scc==(lc=cc)) k++;
}
return(0);
case '?':
caseq:
if(scc) return(amatch(++s, ++p));
return(0);
case '*':
return(umatch(s, ++p));
case 0:
return(!scc);
}
if (c==scc) goto caseq;
return(0);
}
int umatch(register char *s, register char *p)
{
if(*p==0) return(1);
while(*s)
if (amatch(s++, p)) return(1);
return(0);
}
void bwrite(register short *rp, register int c)
{
register short *wp = Wp;
c = (c+1) >> 1;
while(c--) {
if(!Wct) {
again:
if(write(Cpio, (char *)Dbuf, Bufsize)<0) {
Cpio = chgreel(1, Cpio);
goto again;
}
Wct = Bufsize >> 1;
wp = Dbuf;
++Blocks;
}
*wp++ = *rp++;
--Wct;
}
Wp = wp;
}
int chgreel(int x, int fl)
{
register int f;
char str[22];
FILE *devtty;
struct stat statb;
pr("find: can't "), pr(x? "write output": "read input"), pr("\n");
fstat(fl, &statb);
if((statb.st_mode&S_IFMT) != S_IFCHR)
exit(1);
again:
pr("If you want to go on, type device/file name when ready\n");
devtty = fopen("/dev/tty", "r");
fgets(str, 20, devtty);
str[strlen(str) - 1] = '\0';
if(!*str)
exit(1);
close(fl);
if((f = open(str, x? 1: 0)) < 0) {
pr("That didn't work");
fclose(devtty);
goto again;
}
return f;
}
void pr(char *s)
{
fputs(s, stderr);
}

724
v7/cmd/find.c.orig#b00000 Normal file
View File

@ -0,0 +1,724 @@
/* find COMPILE: cc -o find -s -O -i find.c -lS */
#include <stdio.h>
#include <sys/types.h>
#include <sys/dir.h>
#include <sys/stat.h>
#define A_DAY 86400L /* a day full of seconds */
#define EQ(x, y) (strcmp(x, y)==0)
int Randlast;
char Pathname[200];
struct anode {
int (*F)();
struct anode *L, *R;
} Node[100];
int Nn; /* number of nodes */
char *Fname;
long Now;
int Argc,
Ai,
Pi;
char **Argv;
/* cpio stuff */
int Cpio;
short *Buf, *Dbuf, *Wp;
int Bufsize = 5120;
int Wct = 2560;
long Newer;
struct stat Statb;
struct anode *exp(),
*e1(),
*e2(),
*e3(),
*mk();
char *nxtarg();
char Home[128];
long Blocks;
char *rindex();
char *sbrk();
main(argc, argv) char *argv[];
{
struct anode *exlist;
int paths;
register char *cp, *sp = 0;
FILE *pwd, *popen();
time(&Now);
pwd = popen("pwd", "r");
fgets(Home, 128, pwd);
pclose(pwd);
Home[strlen(Home) - 1] = '\0';
Argc = argc; Argv = argv;
if(argc<3) {
usage: pr("Usage: find path-list predicate-list\n");
exit(1);
}
for(Ai = paths = 1; Ai < (argc-1); ++Ai, ++paths)
if(*Argv[Ai] == '-' || EQ(Argv[Ai], "(") || EQ(Argv[Ai], "!"))
break;
if(paths == 1) /* no path-list */
goto usage;
if(!(exlist = exp())) { /* parse and compile the arguments */
pr("find: parsing error\n");
exit(1);
}
if(Ai<argc) {
pr("find: missing conjunction\n");
exit(1);
}
for(Pi = 1; Pi < paths; ++Pi) {
sp = 0;
chdir(Home);
strcpy(Pathname, Argv[Pi]);
if(cp = rindex(Pathname, '/')) {
sp = cp + 1;
*cp = '\0';
if(chdir(*Pathname? Pathname: "/") == -1) {
pr("find: bad starting directory\n");
exit(2);
}
*cp = '/';
}
Fname = sp? sp: Pathname;
descend(Pathname, Fname, exlist); /* to find files that match */
}
if(Cpio) {
strcpy(Pathname, "TRAILER!!!");
Statb.st_size = 0;
cpio();
}
exit(0);
}
/* compile time functions: priority is exp()<e1()<e2()<e3() */
struct anode *exp() { /* parse ALTERNATION (-o) */
int or();
register struct anode * p1;
p1 = e1() /* get left operand */ ;
if(EQ(nxtarg(), "-o")) {
Randlast--;
return(mk(or, p1, exp()));
}
else if(Ai <= Argc) --Ai;
return(p1);
}
struct anode *e1() { /* parse CONCATENATION (formerly -a) */
int and();
register struct anode * p1;
register char *a;
p1 = e2();
a = nxtarg();
if(EQ(a, "-a")) {
And:
Randlast--;
return(mk(and, p1, e1()));
} else if(EQ(a, "(") || EQ(a, "!") || (*a=='-' && !EQ(a, "-o"))) {
--Ai;
goto And;
} else if(Ai <= Argc) --Ai;
return(p1);
}
struct anode *e2() { /* parse NOT (!) */
int not();
if(Randlast) {
pr("find: operand follows operand\n");
exit(1);
}
Randlast++;
if(EQ(nxtarg(), "!"))
return(mk(not, e3(), (struct anode *)0));
else if(Ai <= Argc) --Ai;
return(e3());
}
struct anode *e3() { /* parse parens and predicates */
int exeq(), ok(), glob(), mtime(), atime(), ctime(), user(),
group(), size(), perm(), links(), print(),
type(), ino(), cpio(), newer();
struct anode *p1;
int i;
register char *a, *b, s;
a = nxtarg();
if(EQ(a, "(")) {
Randlast--;
p1 = exp();
a = nxtarg();
if(!EQ(a, ")")) goto err;
return(p1);
}
else if(EQ(a, "-print")) {
return(mk(print, (struct anode *)0, (struct anode *)0));
}
b = nxtarg();
s = *b;
if(s=='+') b++;
puts(b);
if(EQ(a, "-name"))
return(mk(glob, (struct anode *)b, (struct anode *)0));
else if(EQ(a, "-mtime"))
return(mk(mtime, (struct anode *)atoi(b), (struct anode *)s));
else if(EQ(a, "-atime"))
return(mk(atime, (struct anode *)atoi(b), (struct anode *)s));
else if(EQ(a, "-ctime"))
return(mk(ctime, (struct anode *)atoi(b), (struct anode *)s));
else if(EQ(a, "-user")) {
if((i=getunum("/etc/passwd", b)) == -1) {
if(gmatch(b, "[0-9][0-9][0-9]*")
|| gmatch(b, "[0-9][0-9]")
|| gmatch(b, "[0-9]"))
return mk(user, (struct anode *)atoi(b), (struct anode *)s);
pr("find: cannot find -user name\n");
exit(1);
}
return(mk(user, (struct anode *)i, (struct anode *)s));
}
else if(EQ(a, "-inum"))
return(mk(ino, (struct anode *)atoi(b), (struct anode *)s));
else if(EQ(a, "-group")) {
if((i=getunum("/etc/group", b)) == -1) {
if(gmatch(b, "[0-9][0-9][0-9]*")
|| gmatch(b, "[0-9][0-9]")
|| gmatch(b, "[0-9]"))
return mk(group, (struct anode *)atoi(b), (struct anode *)s);
pr("find: cannot find -group name\n");
exit(1);
}
return(mk(group, (struct anode *)i, (struct anode *)s));
} else if(EQ(a, "-size"))
return(mk(size, (struct anode *)atoi(b), (struct anode *)s));
else if(EQ(a, "-links"))
return(mk(links, (struct anode *)atoi(b), (struct anode *)s));
else if(EQ(a, "-perm")) {
for(i=0; *b ; ++b) {
if(*b=='-') continue;
i <<= 3;
i = i + (*b - '0');
}
return(mk(perm, (struct anode *)i, (struct anode *)s));
}
else if(EQ(a, "-type")) {
i = s=='d' ? S_IFDIR :
s=='b' ? S_IFBLK :
s=='c' ? S_IFCHR :
s=='f' ? 0100000 :
0;
return(mk(type, (struct anode *)i, (struct anode *)0));
}
else if (EQ(a, "-exec")) {
i = Ai - 1;
while(!EQ(nxtarg(), ";"));
return(mk(exeq, (struct anode *)i, (struct anode *)0));
}
else if (EQ(a, "-ok")) {
i = Ai - 1;
while(!EQ(nxtarg(), ";"));
return(mk(ok, (struct anode *)i, (struct anode *)0));
}
else if(EQ(a, "-cpio")) {
if((Cpio = creat(b, 0666)) < 0) {
pr("find: cannot create "), pr(s), pr("\n");
exit(1);
}
Buf = (short *)sbrk(512);
Wp = Dbuf = (short *)sbrk(5120);
return(mk(cpio, (struct anode *)0, (struct anode *)0));
}
else if(EQ(a, "-newer")) {
if(stat(b, &Statb) < 0) {
pr("find: cannot access "), pr(b), pr("\n");
exit(1);
}
Newer = Statb.st_mtime;
return mk(newer, (struct anode *)0, (struct anode *)0);
}
err: pr("find: bad option "), pr(a), pr("\n");
exit(1);
}
struct anode *mk(f, l, r)
int (*f)();
struct anode *l, *r;
{
Node[Nn].F = f;
Node[Nn].L = l;
Node[Nn].R = r;
return(&(Node[Nn++]));
}
char *nxtarg() { /* get next arg from command line */
static strikes = 0;
if(strikes==3) {
pr("find: incomplete statement\n");
exit(1);
}
if(Ai>=Argc) {
strikes++;
Ai = Argc + 1;
return("");
}
return(Argv[Ai++]);
}
/* execution time functions */
and(p)
register struct anode *p;
{
return(((*p->L->F)(p->L)) && ((*p->R->F)(p->R))?1:0);
}
or(p)
register struct anode *p;
{
return(((*p->L->F)(p->L)) || ((*p->R->F)(p->R))?1:0);
}
not(p)
register struct anode *p;
{
return( !((*p->L->F)(p->L)));
}
glob(p)
register struct { int f; char *pat; } *p;
{
return(gmatch(Fname, p->pat));
}
print()
{
puts(Pathname);
return(1);
}
mtime(p)
register struct { int f, t, s; } *p;
{
return(scomp((int)((Now - Statb.st_mtime) / A_DAY), p->t, p->s));
}
atime(p)
register struct { int f, t, s; } *p;
{
return(scomp((int)((Now - Statb.st_atime) / A_DAY), p->t, p->s));
}
ctime(p)
register struct { int f, t, s; } *p;
{
return(scomp((int)((Now - Statb.st_ctime) / A_DAY), p->t, p->s));
}
user(p)
register struct { int f, u, s; } *p;
{
return(scomp(Statb.st_uid, p->u, p->s));
}
ino(p)
register struct { int f, u, s; } *p;
{
return(scomp((int)Statb.st_ino, p->u, p->s));
}
group(p)
register struct { int f, u; } *p;
{
return(p->u == Statb.st_gid);
}
links(p)
register struct { int f, link, s; } *p;
{
return(scomp(Statb.st_nlink, p->link, p->s));
}
size(p)
register struct { int f, sz, s; } *p;
{
return(scomp((int)((Statb.st_size+511)>>9), p->sz, p->s));
}
perm(p)
register struct { int f, per, s; } *p;
{
register i;
i = (p->s=='-') ? p->per : 07777; /* '-' means only arg bits */
return((Statb.st_mode & i & 07777) == p->per);
}
type(p)
register struct { int f, per, s; } *p;
{
return((Statb.st_mode&S_IFMT)==p->per);
}
exeq(p)
register struct { int f, com; } *p;
{
fflush(stdout); /* to flush possible `-print' */
return(doex(p->com));
}
ok(p)
struct { int f, com; } *p;
{
int c; int yes;
yes = 0;
fflush(stdout); /* to flush possible `-print' */
pr("< "), pr(Argv[p->com]), pr(" ... "), pr(Pathname), pr(" >? ");
fflush(stderr);
if((c=getchar())=='y') yes = 1;
while(c!='\n')
if(c==EOF)
exit(2);
else
c = getchar();
if(yes) return(doex(p->com));
return(0);
}
#define MKSHORT(v, lv) {U.l=1L;if(U.c[0]) U.l=lv, v[0]=U.s[1], v[1]=U.s[0]; else U.l=lv, v[0]=U.s[0], v[1]=U.s[1];}
union { long l; short s[2]; char c[4]; } U;
long mklong(v)
short v[];
{
U.l = 1;
if(U.c[0] /* VAX */)
U.s[0] = v[1], U.s[1] = v[0];
else
U.s[0] = v[0], U.s[1] = v[1];
return U.l;
}
cpio()
{
#define MAGIC 070707
struct header {
short h_magic,
h_dev,
h_ino,
h_mode,
h_uid,
h_gid,
h_nlink,
h_rdev;
short h_mtime[2];
short h_namesize;
short h_filesize[2];
char h_name[256];
} hdr;
register ifile, ct;
static long fsz;
register i;
hdr.h_magic = MAGIC;
strcpy(hdr.h_name, !strncmp(Pathname, "./", 2)? Pathname+2: Pathname);
hdr.h_namesize = strlen(hdr.h_name) + 1;
hdr.h_uid = Statb.st_uid;
hdr.h_gid = Statb.st_gid;
hdr.h_dev = Statb.st_dev;
hdr.h_ino = Statb.st_ino;
hdr.h_mode = Statb.st_mode;
MKSHORT(hdr.h_mtime, Statb.st_mtime);
hdr.h_nlink = Statb.st_nlink;
fsz = hdr.h_mode & S_IFREG? Statb.st_size: 0L;
MKSHORT(hdr.h_filesize, fsz);
hdr.h_rdev = Statb.st_rdev;
if(EQ(hdr.h_name, "TRAILER!!!")) {
bwrite((short *)&hdr, (sizeof hdr-256)+hdr.h_namesize);
for(i = 0; i < 10; ++i)
bwrite(Buf, 512);
return;
}
if(!mklong(hdr.h_filesize)) {
bwrite((short *)&hdr, (sizeof hdr-256)+hdr.h_namesize);
return;
}
if((ifile = open(Fname, 0)) < 0) {
cerror:
pr("find: cannot copy "), pr(hdr.h_name), pr("\n");
return;
}
bwrite((short *)&hdr, (sizeof hdr-256)+hdr.h_namesize);
for(fsz = mklong(hdr.h_filesize); fsz > 0; fsz -= 512) {
ct = fsz>512? 512: fsz;
if(read(ifile, (char *)Buf, ct) < 0)
goto cerror;
bwrite(Buf, ct);
}
close(ifile);
return;
}
newer()
{
return Statb.st_mtime > Newer;
}
/* support functions */
scomp(a, b, s) /* funny signed compare */
register a, b;
register char s;
{
if(s == '+')
return(a > b);
if(s == '-')
return(a < (b * -1));
return(a == b);
}
doex(com)
{
register np;
register char *na;
static char *nargv[50];
static ccode;
ccode = np = 0;
while (na=Argv[com++]) {
if(strcmp(na, ";")==0) break;
if(strcmp(na, "{}")==0) nargv[np++] = Pathname;
else nargv[np++] = na;
}
nargv[np] = 0;
if (np==0) return(9);
if(fork()) /*parent*/ wait(&ccode);
else { /*child*/
chdir(Home);
execvp(nargv[0], nargv, np);
exit(1);
}
return(ccode ? 0:1);
}
getunum(f, s) char *f, *s; { /* find user/group name and return number */
register i;
register char *sp;
register c;
char str[20];
FILE *pin;
i = -1;
pin = fopen(f, "r");
c = '\n'; /* prime with a CR */
do {
if(c=='\n') {
sp = str;
while((c = *sp++ = getc(pin)) != ':')
if(c == EOF) goto RET;
*--sp = '\0';
if(EQ(str, s)) {
while((c=getc(pin)) != ':')
if(c == EOF) goto RET;
sp = str;
while((*sp = getc(pin)) != ':') sp++;
*sp = '\0';
i = atoi(str);
goto RET;
}
}
} while((c = getc(pin)) != EOF);
RET:
fclose(pin);
return(i);
}
descend(name, fname, exlist)
struct anode *exlist;
char *name, *fname;
{
int dir = 0, /* open directory */
offset,
dsize,
entries,
dirsize;
struct direct dentry[32];
register struct direct *dp;
register char *c1, *c2;
int i;
int rv = 0;
char *endofname;
if(stat(fname, &Statb)<0) {
pr("find: bad status-- "), pr(name), pr("\n");
return(0);
}
(*exlist->F)(exlist);
if((Statb.st_mode&S_IFMT)!=S_IFDIR)
return(1);
for(c1 = name; *c1; ++c1);
if(*(c1-1) == '/')
--c1;
endofname = c1;
dirsize = Statb.st_size;
if(chdir(fname) == -1)
return(0);
for(offset=0 ; offset < dirsize ; offset += 512) { /* each block */
dsize = 512<(dirsize-offset)? 512: (dirsize-offset);
if(!dir) {
if((dir=open(".", 0))<0) {
pr("find: cannot open "), pr(name), pr("\n");
rv = 0;
goto ret;
}
if(offset) lseek(dir, (long)offset, 0);
if(read(dir, (char *)dentry, dsize)<0) {
pr("find: cannot read "), pr(name), pr("\n");
rv = 0;
goto ret;
}
if(dir > 10) {
close(dir);
dir = 0;
}
} else
if(read(dir, (char *)dentry, dsize)<0) {
pr("find: cannot read "), pr(name), pr("\n");
rv = 0;
goto ret;
}
for(dp=dentry, entries=dsize>>4; entries; --entries, ++dp) { /* each directory entry */
if(dp->d_ino==0
|| (dp->d_name[0]=='.' && dp->d_name[1]=='\0')
|| (dp->d_name[0]=='.' && dp->d_name[1]=='.' && dp->d_name[2]=='\0'))
continue;
c1 = endofname;
*c1++ = '/';
c2 = dp->d_name;
for(i=0; i<14; ++i)
if(*c2)
*c1++ = *c2++;
else
break;
*c1 = '\0';
if(c1 == endofname) { /* ?? */
rv = 0;
goto ret;
}
Fname = endofname+1;
if(!descend(name, Fname, exlist)) {
*endofname = '\0';
chdir(Home);
if(chdir(Pathname) == -1) {
pr("find: bad directory tree\n");
exit(1);
}
}
}
}
rv = 1;
ret:
if(dir)
close(dir);
if(chdir("..") == -1) {
*endofname = '\0';
pr("find: bad directory "), pr(name), pr("\n");
rv = 1;
}
return(rv);
}
gmatch(s, p) /* string match as in glob */
register char *s, *p;
{
if (*s=='.' && *p!='.') return(0);
return amatch(s, p);
}
amatch(s, p)
register char *s, *p;
{
register cc;
int scc, k;
int c, lc;
scc = *s;
lc = 077777;
switch (c = *p) {
case '[':
k = 0;
while (cc = *++p) {
switch (cc) {
case ']':
if (k)
return(amatch(++s, ++p));
else
return(0);
case '-':
k |= lc <= scc & scc <= (cc=p[1]);
}
if (scc==(lc=cc)) k++;
}
return(0);
case '?':
caseq:
if(scc) return(amatch(++s, ++p));
return(0);
case '*':
return(umatch(s, ++p));
case 0:
return(!scc);
}
if (c==scc) goto caseq;
return(0);
}
umatch(s, p)
register char *s, *p;
{
if(*p==0) return(1);
while(*s)
if (amatch(s++, p)) return(1);
return(0);
}
bwrite(rp, c)
register short *rp;
register c;
{
register short *wp = Wp;
c = (c+1) >> 1;
while(c--) {
if(!Wct) {
again:
if(write(Cpio, (char *)Dbuf, Bufsize)<0) {
Cpio = chgreel(1, Cpio);
goto again;
}
Wct = Bufsize >> 1;
wp = Dbuf;
++Blocks;
}
*wp++ = *rp++;
--Wct;
}
Wp = wp;
}
chgreel(x, fl)
{
register f;
char str[22];
FILE *devtty;
struct stat statb;
pr("find: can't "), pr(x? "write output": "read input"), pr("\n");
fstat(fl, &statb);
if((statb.st_mode&S_IFMT) != S_IFCHR)
exit(1);
again:
pr("If you want to go on, type device/file name when ready\n");
devtty = fopen("/dev/tty", "r");
fgets(str, 20, devtty);
str[strlen(str) - 1] = '\0';
if(!*str)
exit(1);
close(fl);
if((f = open(str, x? 1: 0)) < 0) {
pr("That didn't work");
fclose(devtty);
goto again;
}
return f;
}
pr(s)
char *s;
{
fputs(s, stderr);
}

70
v7/cmd/od.1#000000 Normal file
View File

@ -0,0 +1,70 @@
.TH OD 1
.SH NAME
od \- octal dump
.SH SYNOPSIS
.B od
[
.B \-bcdox
] [ file ] [ [
.B +
]offset[
.BR ". " "]["
\fBb\fR ] ]
.SH DESCRIPTION
.I Od
dumps
.I file
in
one or more formats
as
selected by the first argument.
If the first argument is missing,
.B \-o
is default.
The meanings of the format argument characters
are:
.TP 3
.B b
Interpret bytes in octal.
.TP 3
.B c
Interpret bytes in ASCII.
Certain non-graphic characters appear as C escapes:
null=\e0,
backspace=\eb,
formfeed=\ef,
newline=\en,
return=\er,
tab=\et;
others appear as 3-digit octal numbers.
.TP 3
.B d
Interpret words in decimal.
.TP 3
.B o
Interpret words in octal.
.TP 3
.B x
Interpret words in hex.
.PP
The
.I file
argument specifies which file is to be dumped.
If no file argument is specified,
the standard input is used.
.PP
The offset argument specifies the offset
in the file where dumping is to commence.
This argument is normally interpreted
as octal bytes.
If `\fB.\fR' is appended, the offset is interpreted in
decimal.
If `\fBb\fR' is appended, the offset is interpreted in
blocks of 512 bytes.
If the file argument is omitted,
the offset argument must be preceded
.RB ` + '.
.PP
Dumping continues until end-of-file.
.SH "SEE ALSO"
adb(1)

250
v7/cmd/od.c#b00008 Normal file
View File

@ -0,0 +1,250 @@
/*
* od -- octal (also hex, decimal, and character) dump
*/
#include <stdio.h>
unsigned short word[8];
unsigned short lastword[8];
int conv;
int base = 010;
int max;
long addr;
main(argc, argv)
char **argv;
{
register char *p;
register n, f, same;
argv++;
f = 0;
if(argc > 1) {
p = *argv;
if(*p == '-') {
while(*p != '\0') {
switch(*p++) {
case 'o':
conv |= 001;
f = 6;
break;
case 'd':
conv |= 002;
f = 5;
break;
case 'x':
case 'h':
conv |= 010;
f = 4;
break;
case 'c':
conv |= 020;
f = 7;
break;
case 'b':
conv |= 040;
f = 7;
break;
}
if(f > max)
max = f;
}
argc--;
argv++;
}
}
if(!conv) {
max = 6;
conv = 1;
}
if(argc > 1)
if(**argv != '+') {
if (freopen(*argv, "r", stdin) == NULL) {
printf("cannot open %s\n", *argv);
exit(1);
}
argv++;
argc--;
}
if(argc > 1)
offset(*argv);
same = -1;
for ( ; (n = fread((char *)word, 1, sizeof(word), stdin)) > 0; addr += n) {
if (same>=0) {
for (f=0; f<8; f++)
if (lastword[f] != word[f])
goto notsame;
if (same==0) {
printf("*\n");
same = 1;
}
continue;
}
notsame:
line(addr, word, (n+sizeof(word[0])-1)/sizeof(word[0]));
same = 0;
for (f=0; f<8; f++)
lastword[f] = word[f];
for (f=0; f<8; f++)
word[f] = 0;
}
putn(addr, base, 7);
putchar('\n');
}
line(a, w, n)
long a;
unsigned short *w;
{
register i, f, c;
f = 1;
for(c=1; c; c<<=1) {
if((c&conv) == 0)
continue;
if(f) {
putn(a, base, 7);
putchar(' ');
f = 0;
} else
putchar('\t');
for (i=0; i<n; i++) {
putx(w[i], c);
putchar(i==n-1? '\n': ' ');
}
}
}
putx(n, c)
unsigned n;
{
switch(c) {
case 001:
pre(6);
putn((long)n, 8, 6);
break;
case 002:
pre(5);
putn((long)n, 10, 5);
break;
case 010:
pre(4);
putn((long)n, 16, 4);
break;
case 020:
pre(7);
{
unsigned short sn = n;
cput(*(char *)&sn);
putchar(' ');
cput(*((char *)&sn + 1));
break;
}
case 040:
pre(7);
{
unsigned short sn = n;
putn((long)(*(char *)&sn)&0377, 8, 3);
putchar(' ');
putn((long)(*((char *)&sn + 1))&0377, 8, 3);
break;
}
}
}
cput(c)
{
c &= 0377;
if(c>037 && c<0177) {
printf(" ");
putchar(c);
return;
}
switch(c) {
case '\0':
printf(" \\0");
break;
case '\b':
printf(" \\b");
break;
case '\f':
printf(" \\f");
break;
case '\n':
printf(" \\n");
break;
case '\r':
printf(" \\r");
break;
case '\t':
printf(" \\t");
break;
default:
putn((long)c, 8, 3);
}
}
putn(n, b, c)
long n;
{
register d;
if(!c)
return;
putn(n/b, b, c-1);
d = n%b;
if (d > 9)
putchar(d-10+'a');
else
putchar(d+'0');
}
pre(n)
{
int i;
for(i=n; i<max; i++)
putchar(' ');
}
offset(s)
register char *s;
{
register char *p;
long a;
register int d;
if (*s=='+')
s++;
if (*s=='x') {
s++;
base = 16;
} else if (*s=='0' && s[1]=='x') {
s += 2;
base = 16;
} else if (*s == '0')
base = 8;
p = s;
while(*p) {
if (*p++=='.')
base = 10;
}
for (a=0; *s; s++) {
d = *s;
if(d>='0' && d<='9')
a = a*base + d - '0';
else if (d>='a' && d<='f' && base==16)
a = a*base + d + 10 - 'a';
else
break;
}
if (*s == '.')
s++;
if(*s=='b' || *s=='B')
a *= 512;
fseek(stdin, a, 0);
addr = a;
}

11
v7/cmd/rev.1#000000 Normal file
View File

@ -0,0 +1,11 @@
.TH REV 1
.SH NAME
rev \- reverse lines of a file
.SH SYNOPSIS
.B rev
[ file ] ...
.SH DESCRIPTION
.I Rev
copies the named files to the standard output,
reversing the order of characters in every line.
If no file is specified, the standard input is copied.

44
v7/cmd/rev.c#b00008 Normal file
View File

@ -0,0 +1,44 @@
#include <stdio.h>
/* reverse lines of a file */
#define N 256
char line[N];
FILE *input;
main(argc,argv)
char **argv;
{
register i,c;
input = stdin;
do {
if(argc>1) {
if((input=fopen(argv[1],"r"))==NULL) {
fprintf(stderr,"rev: cannot open %s\n",
argv[1]);
exit(1);
}
}
for(;;){
for(i=0;i<N;i++) {
line[i] = c = getc(input);
switch(c) {
case EOF:
goto eof;
default:
continue;
case '\n':
break;
}
break;
}
while(--i>=0)
putc(line[i],stdout);
putc('\n',stdout);
}
eof:
fclose(input);
argc--;
argv++;
} while(argc>1);
}

72
v7/cmd/units.1#000000 Normal file
View File

@ -0,0 +1,72 @@
.if n .ds / /
.if t .ds / \z/\h'\w'*'u'
.TH UNITS 1
.SH NAME
units \- conversion program
.SH SYNOPSIS
.B units
.SH DESCRIPTION
.I Units
converts quantities expressed
in various standard scales to
their equivalents in other scales.
It works interactively in this fashion:
.PP
.I " You have:"
inch
.br
.I " You want:"
cm
.br
.I " * 2.54000e+00
.br
.I " \*/ 3.93701e\-01
.PP
A quantity is specified as a multiplicative combination of
units optionally preceded by a numeric multiplier.
Powers are indicated by suffixed positive integers,
division by the usual sign:
.PP
.I " You have:"
15 pounds force/in2
.br
.I " You want:"
atm
.br
.I " * 1.02069e+00"
.br
.I " \*/ 9.79730e\-01"
.PP
.I Units
only does multiplicative scale changes.
Thus it can convert Kelvin to Rankine, but not Centigrade to
Fahrenheit.
Most familiar units,
abbreviations, and metric prefixes are recognized,
together with a generous leavening of exotica
and a few constants of nature including:
.PP
.nf
pi ratio of circumference to diameter
c speed of light
e charge on an electron
g acceleration of gravity
force same as g
mole Avogadro's number
water pressure head per unit height of water
au astronomical unit
.PP
.fi
`Pound' is a unit of
mass.
Compound names are run together, e.g. `lightyear'.
British units that differ from their US counterparts
are prefixed thus: `brgallon'.
Currency is denoted `belgiumfranc', `britainpound', ...
.PP
For a complete list of units, `cat /usr/lib/units'.
.SH FILES
/usr/lib/units
.SH BUGS
Don't base your
financial plans on the currency conversions.

464
v7/cmd/units.c#b00008 Normal file
View File

@ -0,0 +1,464 @@
#include <stdio.h>
#define NDIM 10
#define NTAB 601
char *dfile = "/usr/local/lib/units";
char *unames[NDIM];
double getflt();
int fperr();
struct table *hash();
struct unit
{
double factor;
char dim[NDIM];
};
struct table
{
double factor;
char dim[NDIM];
char *name;
} table[NTAB];
char names[NTAB*10];
struct prefix
{
double factor;
char *pname;
} prefix[] =
{
1e-18, "atto",
1e-15, "femto",
1e-12, "pico",
1e-9, "nano",
1e-6, "micro",
1e-3, "milli",
1e-2, "centi",
1e-1, "deci",
1e1, "deka",
1e2, "hecta",
1e2, "hecto",
1e3, "kilo",
1e6, "mega",
1e6, "meg",
1e9, "giga",
1e12, "tera",
0.0, 0
};
FILE *inp;
int fperrc;
int peekc;
int dumpflg;
main(argc, argv)
char *argv[];
{
register i;
register char *file;
struct unit u1, u2;
double f;
if(argc>1 && *argv[1]=='-') {
argc--;
argv++;
dumpflg++;
}
file = dfile;
if(argc > 1)
file = argv[1];
if ((inp = fopen(file, "r")) == NULL) {
printf("no table\n");
exit(1);
}
signal(8, fperr);
init();
loop:
fperrc = 0;
printf("you have: ");
if(convr(&u1))
goto loop;
if(fperrc)
goto fp;
loop1:
printf("you want: ");
if(convr(&u2))
goto loop1;
for(i=0; i<NDIM; i++)
if(u1.dim[i] != u2.dim[i])
goto conform;
f = u1.factor/u2.factor;
if(fperrc)
goto fp;
printf("\t* %e\n", f);
printf("\t/ %e\n", 1./f);
goto loop;
conform:
if(fperrc)
goto fp;
printf("conformability\n");
units(&u1);
units(&u2);
goto loop;
fp:
printf("underflow or overflow\n");
goto loop;
}
units(up)
struct unit *up;
{
register struct unit *p;
register f, i;
p = up;
printf("\t%e ", p->factor);
f = 0;
for(i=0; i<NDIM; i++)
f |= pu(p->dim[i], i, f);
if(f&1) {
putchar('/');
f = 0;
for(i=0; i<NDIM; i++)
f |= pu(-p->dim[i], i, f);
}
putchar('\n');
}
pu(u, i, f)
{
if(u > 0) {
if(f&2)
putchar('-');
if(unames[i])
printf("%s", unames[i]); else
printf("*%c*", i+'a');
if(u > 1)
putchar(u+'0');
return(2);
}
if(u < 0)
return(1);
return(0);
}
convr(up)
struct unit *up;
{
register struct unit *p;
register c;
register char *cp;
char name[20];
int den, err;
p = up;
for(c=0; c<NDIM; c++)
p->dim[c] = 0;
p->factor = getflt();
if(p->factor == 0.)
p->factor = 1.0;
err = 0;
den = 0;
cp = name;
loop:
switch(c=get()) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '/':
case ' ':
case '\t':
case '\n':
if(cp != name) {
*cp++ = 0;
cp = name;
err |= lookup(cp, p, den, c);
}
if(c == '/')
den++;
if(c == '\n')
return(err);
goto loop;
}
*cp++ = c;
goto loop;
}
lookup(name, up, den, c)
char *name;
struct unit *up;
{
register struct unit *p;
register struct table *q;
register i;
char *cp1, *cp2;
double e;
p = up;
e = 1.0;
loop:
q = hash(name);
if(q->name) {
l1:
if(den) {
p->factor /= q->factor*e;
for(i=0; i<NDIM; i++)
p->dim[i] -= q->dim[i];
} else {
p->factor *= q->factor*e;
for(i=0; i<NDIM; i++)
p->dim[i] += q->dim[i];
}
if(c >= '2' && c <= '9') {
c--;
goto l1;
}
return(0);
}
for(i=0; cp1 = prefix[i].pname; i++) {
cp2 = name;
while(*cp1 == *cp2++)
if(*cp1++ == 0) {
cp1--;
break;
}
if(*cp1 == 0) {
e *= prefix[i].factor;
name = cp2-1;
goto loop;
}
}
for(cp1 = name; *cp1; cp1++);
if(cp1 > name+1 && *--cp1 == 's') {
*cp1 = 0;
goto loop;
}
printf("cannot recognize %s\n", name);
return(1);
}
equal(s1, s2)
char *s1, *s2;
{
register char *c1, *c2;
c1 = s1;
c2 = s2;
while(*c1++ == *c2)
if(*c2++ == 0)
return(1);
return(0);
}
init()
{
register char *cp;
register struct table *tp, *lp;
int c, i, f, t;
char *np;
cp = names;
for(i=0; i<NDIM; i++) {
np = cp;
*cp++ = '*';
*cp++ = i+'a';
*cp++ = '*';
*cp++ = 0;
lp = hash(np);
lp->name = np;
lp->factor = 1.0;
lp->dim[i] = 1;
}
lp = hash("");
lp->name = cp-1;
lp->factor = 1.0;
l0:
c = get();
if(c == 0) {
printf("%l units; %l bytes\n\n", i, cp-names);
if(dumpflg)
for(tp = &table[0]; tp < &table[NTAB]; tp++) {
if(tp->name == 0)
continue;
printf("%s", tp->name);
units(tp);
}
fclose(inp);
inp = stdin;
return;
}
if(c == '/') {
while(c != '\n' && c != 0)
c = get();
goto l0;
}
if(c == '\n')
goto l0;
np = cp;
while(c != ' ' && c != '\t') {
*cp++ = c;
c = get();
if (c==0)
goto l0;
if(c == '\n') {
*cp++ = 0;
tp = hash(np);
if(tp->name)
goto redef;
tp->name = np;
tp->factor = lp->factor;
for(c=0; c<NDIM; c++)
tp->dim[c] = lp->dim[c];
i++;
goto l0;
}
}
*cp++ = 0;
lp = hash(np);
if(lp->name)
goto redef;
convr(lp);
lp->name = np;
f = 0;
i++;
if(lp->factor != 1.0)
goto l0;
for(c=0; c<NDIM; c++) {
t = lp->dim[c];
if(t>1 || (f>0 && t!=0))
goto l0;
if(f==0 && t==1) {
if(unames[c])
goto l0;
f = c+1;
}
}
if(f>0)
unames[f-1] = np;
goto l0;
redef:
printf("redefinition %s\n", np);
goto l0;
}
double
getflt()
{
register c, i, dp;
double d, e;
int f;
d = 0.;
dp = 0;
do
c = get();
while(c == ' ' || c == '\t');
l1:
if(c >= '0' && c <= '9') {
d = d*10. + c-'0';
if(dp)
dp++;
c = get();
goto l1;
}
if(c == '.') {
dp++;
c = get();
goto l1;
}
if(dp)
dp--;
if(c == '+' || c == '-') {
f = 0;
if(c == '-')
f++;
i = 0;
c = get();
while(c >= '0' && c <= '9') {
i = i*10 + c-'0';
c = get();
}
if(f)
i = -i;
dp -= i;
}
e = 1.;
i = dp;
if(i < 0)
i = -i;
while(i--)
e *= 10.;
if(dp < 0)
d *= e; else
d /= e;
if(c == '|')
return(d/getflt());
peekc = c;
return(d);
}
get()
{
register c;
if(c=peekc) {
peekc = 0;
return(c);
}
c = getc(inp);
if (c == EOF) {
if (inp == stdin) {
printf("\n");
exit(0);
}
return(0);
}
return(c);
}
struct table *
hash(name)
char *name;
{
register struct table *tp;
register char *np;
register unsigned h;
h = 0;
np = name;
while(*np)
h = h*57 + *np++ - '0';
h %= NTAB;
tp = &table[h];
l0:
if(tp->name == 0)
return(tp);
if(equal(name, tp->name))
return(tp);
tp++;
if(tp >= &table[NTAB])
tp = table;
goto l0;
}
fperr()
{
signal(8, fperr);
fperrc++;
}

464
v7/cmd/units.c.orig#b00008 Normal file
View File

@ -0,0 +1,464 @@
#include <stdio.h>
#define NDIM 10
#define NTAB 601
char *dfile = "/usr/lib/units";
char *unames[NDIM];
double getflt();
int fperr();
struct table *hash();
struct unit
{
double factor;
char dim[NDIM];
};
struct table
{
double factor;
char dim[NDIM];
char *name;
} table[NTAB];
char names[NTAB*10];
struct prefix
{
double factor;
char *pname;
} prefix[] =
{
1e-18, "atto",
1e-15, "femto",
1e-12, "pico",
1e-9, "nano",
1e-6, "micro",
1e-3, "milli",
1e-2, "centi",
1e-1, "deci",
1e1, "deka",
1e2, "hecta",
1e2, "hecto",
1e3, "kilo",
1e6, "mega",
1e6, "meg",
1e9, "giga",
1e12, "tera",
0.0, 0
};
FILE *inp;
int fperrc;
int peekc;
int dumpflg;
main(argc, argv)
char *argv[];
{
register i;
register char *file;
struct unit u1, u2;
double f;
if(argc>1 && *argv[1]=='-') {
argc--;
argv++;
dumpflg++;
}
file = dfile;
if(argc > 1)
file = argv[1];
if ((inp = fopen(file, "r")) == NULL) {
printf("no table\n");
exit(1);
}
signal(8, fperr);
init();
loop:
fperrc = 0;
printf("you have: ");
if(convr(&u1))
goto loop;
if(fperrc)
goto fp;
loop1:
printf("you want: ");
if(convr(&u2))
goto loop1;
for(i=0; i<NDIM; i++)
if(u1.dim[i] != u2.dim[i])
goto conform;
f = u1.factor/u2.factor;
if(fperrc)
goto fp;
printf("\t* %e\n", f);
printf("\t/ %e\n", 1./f);
goto loop;
conform:
if(fperrc)
goto fp;
printf("conformability\n");
units(&u1);
units(&u2);
goto loop;
fp:
printf("underflow or overflow\n");
goto loop;
}
units(up)
struct unit *up;
{
register struct unit *p;
register f, i;
p = up;
printf("\t%e ", p->factor);
f = 0;
for(i=0; i<NDIM; i++)
f |= pu(p->dim[i], i, f);
if(f&1) {
putchar('/');
f = 0;
for(i=0; i<NDIM; i++)
f |= pu(-p->dim[i], i, f);
}
putchar('\n');
}
pu(u, i, f)
{
if(u > 0) {
if(f&2)
putchar('-');
if(unames[i])
printf("%s", unames[i]); else
printf("*%c*", i+'a');
if(u > 1)
putchar(u+'0');
return(2);
}
if(u < 0)
return(1);
return(0);
}
convr(up)
struct unit *up;
{
register struct unit *p;
register c;
register char *cp;
char name[20];
int den, err;
p = up;
for(c=0; c<NDIM; c++)
p->dim[c] = 0;
p->factor = getflt();
if(p->factor == 0.)
p->factor = 1.0;
err = 0;
den = 0;
cp = name;
loop:
switch(c=get()) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '/':
case ' ':
case '\t':
case '\n':
if(cp != name) {
*cp++ = 0;
cp = name;
err |= lookup(cp, p, den, c);
}
if(c == '/')
den++;
if(c == '\n')
return(err);
goto loop;
}
*cp++ = c;
goto loop;
}
lookup(name, up, den, c)
char *name;
struct unit *up;
{
register struct unit *p;
register struct table *q;
register i;
char *cp1, *cp2;
double e;
p = up;
e = 1.0;
loop:
q = hash(name);
if(q->name) {
l1:
if(den) {
p->factor /= q->factor*e;
for(i=0; i<NDIM; i++)
p->dim[i] -= q->dim[i];
} else {
p->factor *= q->factor*e;
for(i=0; i<NDIM; i++)
p->dim[i] += q->dim[i];
}
if(c >= '2' && c <= '9') {
c--;
goto l1;
}
return(0);
}
for(i=0; cp1 = prefix[i].pname; i++) {
cp2 = name;
while(*cp1 == *cp2++)
if(*cp1++ == 0) {
cp1--;
break;
}
if(*cp1 == 0) {
e *= prefix[i].factor;
name = cp2-1;
goto loop;
}
}
for(cp1 = name; *cp1; cp1++);
if(cp1 > name+1 && *--cp1 == 's') {
*cp1 = 0;
goto loop;
}
printf("cannot recognize %s\n", name);
return(1);
}
equal(s1, s2)
char *s1, *s2;
{
register char *c1, *c2;
c1 = s1;
c2 = s2;
while(*c1++ == *c2)
if(*c2++ == 0)
return(1);
return(0);
}
init()
{
register char *cp;
register struct table *tp, *lp;
int c, i, f, t;
char *np;
cp = names;
for(i=0; i<NDIM; i++) {
np = cp;
*cp++ = '*';
*cp++ = i+'a';
*cp++ = '*';
*cp++ = 0;
lp = hash(np);
lp->name = np;
lp->factor = 1.0;
lp->dim[i] = 1;
}
lp = hash("");
lp->name = cp-1;
lp->factor = 1.0;
l0:
c = get();
if(c == 0) {
printf("%l units; %l bytes\n\n", i, cp-names);
if(dumpflg)
for(tp = &table[0]; tp < &table[NTAB]; tp++) {
if(tp->name == 0)
continue;
printf("%s", tp->name);
units(tp);
}
fclose(inp);
inp = stdin;
return;
}
if(c == '/') {
while(c != '\n' && c != 0)
c = get();
goto l0;
}
if(c == '\n')
goto l0;
np = cp;
while(c != ' ' && c != '\t') {
*cp++ = c;
c = get();
if (c==0)
goto l0;
if(c == '\n') {
*cp++ = 0;
tp = hash(np);
if(tp->name)
goto redef;
tp->name = np;
tp->factor = lp->factor;
for(c=0; c<NDIM; c++)
tp->dim[c] = lp->dim[c];
i++;
goto l0;
}
}
*cp++ = 0;
lp = hash(np);
if(lp->name)
goto redef;
convr(lp);
lp->name = np;
f = 0;
i++;
if(lp->factor != 1.0)
goto l0;
for(c=0; c<NDIM; c++) {
t = lp->dim[c];
if(t>1 || (f>0 && t!=0))
goto l0;
if(f==0 && t==1) {
if(unames[c])
goto l0;
f = c+1;
}
}
if(f>0)
unames[f-1] = np;
goto l0;
redef:
printf("redefinition %s\n", np);
goto l0;
}
double
getflt()
{
register c, i, dp;
double d, e;
int f;
d = 0.;
dp = 0;
do
c = get();
while(c == ' ' || c == '\t');
l1:
if(c >= '0' && c <= '9') {
d = d*10. + c-'0';
if(dp)
dp++;
c = get();
goto l1;
}
if(c == '.') {
dp++;
c = get();
goto l1;
}
if(dp)
dp--;
if(c == '+' || c == '-') {
f = 0;
if(c == '-')
f++;
i = 0;
c = get();
while(c >= '0' && c <= '9') {
i = i*10 + c-'0';
c = get();
}
if(f)
i = -i;
dp -= i;
}
e = 1.;
i = dp;
if(i < 0)
i = -i;
while(i--)
e *= 10.;
if(dp < 0)
d *= e; else
d /= e;
if(c == '|')
return(d/getflt());
peekc = c;
return(d);
}
get()
{
register c;
if(c=peekc) {
peekc = 0;
return(c);
}
c = getc(inp);
if (c == EOF) {
if (inp == stdin) {
printf("\n");
exit(0);
}
return(0);
}
return(c);
}
struct table *
hash(name)
char *name;
{
register struct table *tp;
register char *np;
register unsigned h;
h = 0;
np = name;
while(*np)
h = h*57 + *np++ - '0';
h %= NTAB;
tp = &table[h];
l0:
if(tp->name == 0)
return(tp);
if(equal(name, tp->name))
return(tp);
tp++;
if(tp >= &table[NTAB])
tp = table;
goto l0;
}
fperr()
{
signal(8, fperr);
fperrc++;
}

View File

@ -0,0 +1,484 @@
/ dimensions
m *a*
kg *b*
sec *c*
coul *d*
candela *e*
dollar *f*
radian *g*
bit *h*
erlang *i*
degC *j*
/ constants
fuzz 1
pi 3.14159265358979323846
c 2.997925+8 m/sec fuzz
g 9.80665 m/sec2
au 1.49597871+11 m fuzz
mole 6.022169+23 fuzz
e 1.6021917-19 coul fuzz
energy c2
force g
mercury 1.33322+5 kg/m2-sec2
hg mercury
/ dimensionless
degree 1|180 pi-radian
circle 2 pi-radian
turn 2 pi-radian
grade .9 degree
arcdeg 1 degree
arcmin 1|60 arcdeg
ccs 1|36 erlang
arcsec 1|60 arcmin
steradian radian2
sphere 4 pi-steradian
sr steradian
/ Time
second sec
s sec
minute 60 sec
min minute
hour 60 min
hr hour
day 24 hr
da day
week 7 day
year 365.24219879 day fuzz
yr year
month 1|12 year
ms millisec
us microsec
/ Mass
gram millikg
gm gram
mg milligram
metricton kilokg
/ Avoirdupois
lb .45359237 kg
lbf lb g
pound lb
ounce 1|16 lb
oz ounce
dram 1|16 oz
dr dram
grain 1|7000 lb
gr grain
shortton 2000 lb
ton shortton
longton 2240 lb
/ Apothecary
scruple 20 grain
apdram 60 grain
apounce 480 grain
appound 5760 grain
/ Length
meter m
cm centimeter
mm millimeter
km kilometer
nm nanometer
micron micrometer
angstrom decinanometer
inch 2.54 cm
in inch
foot 12 in
feet foot
ft foot
yard 3 ft
yd yard
rod 5.5 yd
rd rod
mile 5280 ft
mi mile
british 1200|3937 m/ft
nmile 1852m
acre 4840 yd2
cc cm3
liter kilocc
ml milliliter
/ US Liquid
gallon 231 in3
imperial 1.20095
gal gallon
quart 1|4 gal
qt quart
pint 1|2 qt
pt pint
floz 1|16 pt
fldr 1|8 floz
/ US Dry
dry 268.8025 in3/gallon fuzz
peck 8 dry-quart
pk peck
bushel 4 peck
bu bushel
/ British
brgallon 277.420 in3 fuzz
brquart 1|4 brgallon
brpint 1|2 brquart
brfloz 1|20 brpint
brpeck 554.84 in3 fuzz
brbushel 4 brpeck
/ Energy Work
newton kg-m/sec2
nt newton
joule nt-m
cal 4.1868 joule
/ Electrical
coulomb coul
ampere coul/sec
amp ampere
watt joule/sec
volt watt/amp
ohm volt/amp
mho /ohm
farad coul/volt
henry sec2/farad
weber volt-sec
/ Light
cd candela
lumen cd sr
lux cd sr/m2
/ Money
/ epoch Nov 10, 1978 wall st j
$ dollar
argentinapeso .0011 $
australiadollar 1.1560 $
austriaschilling .0726 $
belgiumfranc .0333 $
brazilcruzeiro .0512 $
britainpound 1.9705 $
brpound britainpound
canadadollar .8525 $
colombiapeso .0279 $
denmarkkrone .1927 $
equadorsucre .0404 $
finlandmarkka .2524 $
francefranc .2336 $
greecedrachma .0284 $
hongkongdollar .2096 $
indiarupee .1275 $
indonesiarupiah .00245 $
iranrial .0144 $
iraqdinar 3.44 $
israelpound .0540 $
italylira .001198 $
japanyen .005332 $
lebanonpound .3340 $
malaysiadollar .4595 $
mexicopeso .04394 $
netherlandsguilder .4924 $
newzealanddollar 1.0660 $
norwaykrone .1996 $
pakistanrupee .1020 $
perusol .0067 $
phillippinespeso .1365 $
portugalescudo .0218 $
saudiarabiariyal .3029 $
singaporedollar .4615 $
southafricarand 1.1522 $
southkoreawon .0021 $
spainpeseta .01415 $
swedenkrona .2305 $
switzerlandfranc .6171 $
thailandbhat .050 $
uruguaypeso .1546 $
usdollar $
venezuelabolivar .2331 $
germanymark .5306 $
mark germanymark
bolivar venezuelabolivar
peseta spainpeseta
rand southafricarand
escudo portugalescudo
sol perusol
guilder netherlandsguilder
peso mexicopeso
yen japanyen
lira italylira
dinar iraqdinar
rial iranrial
rupee indiarupee
drachma greecedrachma
franc francefranc
markka finlandmarkka
sucre equadorsucre
poundsterling britainpound
cruzeiro brazilcruzeiro
/ PDP-11
baud bit/sec
byte 8 bit
word 2 byte
block 512 byte
K 1024 word
tc 578 block
rktrack 12 block
rkcylinder 2 rktrack
rk 203 rkcylinder
rptrack 10 block
rpcylinder 20 rptracks
rp 406 rpcylinder
rftrack 8 block
rfshoe 8 rftrack
rfdisk 16 rfshoe
rf 2 rfdisk
/ Trivia
% 1|100
admiraltyknot 6080 ft/hr
apostilb cd/pi-m2
are 1+2 m2
arpentcan 27.52 mi
arpentlin 191.835 ft
astronomicalunit au
atmosphere 1.01325+5 nt/m2
atm atmosphere
atomicmassunit 1.66044-27 kg fuzz
amu atomicmassunit
bag 94 lb
bakersdozen 13
bar 1+5 nt/m2
barie 1-1 nt/m2
barleycorn 1|3 in
barn 1-28 m2
barrel 42 gal
barye 1-1 nt/m2
bev 1+9 e-volt
biot 10 amp
blondel cd/pi-m2
boardfoot 144 in3
bolt 40 yd
bottommeasure 1|40 in
britishthermalunit 1.05506+3 joule fuzz
btu britishthermalunit
refrigeration 12000 btu/ton-hour
buck dollar
cable 720 ft
caliber 1-2 in
calorie cal
carat 205 mg
cent centidollar
cental 100 lb
centesimalminute 1-2 grade
centesimalsecond 1-4 grade
century 100 year
cfs ft3/sec
chain 66 ft
circularinch 1|4 pi-in2
circularmil 1-6|4 pi-in2
clusec 1-8 mm-hg m3/s
coomb 4 bu
cord 128 ft3
cordfoot cord
crith 9.06-2 gm
cubit 18 in
cup 1|2 pt
curie 3.7+10 /sec
dalton amu
decade 10 yr
dipotre /m
displacementton 35 ft3
doppelzentner 100 kg
dozen 12
drop .03 cm3
dyne cm-gm/sec2
electronvolt e-volt
ell 45 in
engineerschain 100 ft
engineerslink 100|100 ft
equivalentfootcandle lumen/pi-ft2
equivalentlux lumen/pi-m2
equivalentphot cd/pi-cm2
erg cm2-gm/sec2
ev e-volt
faraday 9.652+4 coul
fathom 6 ft
fermi 1-15 m
fifth 4|5 qt
fin 5 dollar
finger 7|8 in
firkin 9 gal
footcandle lumen/ft2
footlambert cd/pi-ft2
fortnight 14 da
franklin 3.33564-10 coul
frigorie kilocal
furlong 220 yd
galileo 1-2 m/sec2
gamma 1-9 weber/m2
gauss 1-4 weber/m2
geodeticfoot british-ft
geographicalmile 1852 m
gilbert 7.95775-1 amp
gill 1|4 pt
gross 144
gunterschain 22 yd
hand 4 in
hectare 1+4 m2
hefnercandle .92 cd
hertz /sec
hogshead 2 barrel
hd hogshead
homestead 1|4 mi2
horsepower 550 ft-lb-g/sec
hp horsepower
hyl gm force sec2/m
hz /sec
imaginarycubicfoot 1.4 ft3
jeroboam 4|5 gal
karat 1|24
kcal kilocal
kcalorie kilocal
kev 1+3 e-volt
key kg
khz 1+3 /sec
kilderkin 18 gal
knot nmile/hr
lambert cd/pi-cm2
langley cal/cm2
last 80 bu
league 3 mi
lightyear c-yr
line 1|12 in
link 66|100 ft
longhundredweight 112 lb
longquarter 28 lb
lusec 1-6 mm-hg m3/s
mach 331.46 m/sec
magnum 2 qt
marineleague 3 nmile
maxwell 1-8 weber
metriccarat 200 mg
mev 1+6 e-volt
mgd megagal/day
mh millihenry
mhz 1+6 /sec
mil 1-2 in
millenium 1000 year
minersinch 1.5 ft3/min
minim 1|60 fldr
mo month
mpg mile/gal
mph mile/hr
nail 1|16 yd
nauticalmile nmile
nit cd/m2
noggin 1|8 qt
nox 1-3 lux
ns nanosec
oersted 2.5+2 pi-amp/m
oe oersted
pace 36 in
palm 3 in
parasang 3.5 mi
parsec au-radian/arcsec
pascal nt/m2
pc parsec
pennyweight 1|20 oz
percent %
perch rd
pf picofarad
phot lumen/cm2
pica 1|6 in
pieze 1+3 nt/m2
pipe 4 barrel
point 1|72 in
poise gm/cm-sec
pole rd
poundal ft-lb/sec2
pdl poundal
proof 1|200
psi lb-g/in2
quarter 9 in
quartersection 1|4 mi2
quintal 100 kg
quire 25
rad 100 erg/gm
ream 500
registerton 100 ft3
rehoboam 156 floz
rhe 10 m2/nt-sec
rontgen 2.58-4 curie/kg
rood 1.21+3 yd
rope 20 ft
rutherford 1+6 /sec
rydberg 1.36054+1 ev
sabin 1 ft2
sack 3 bu
seam 8 bu
section mi2
shippington 40 ft3
shorthundredweight 100 lb
shortquarter 25 lb
siemens /ohm
sigma microsec
skein 120 yd
skot 1-3 apostilb
slug lb-g-sec2/ft
span 9 in
spat 4 pi sr
spindle 14400 yd
square 100 ft2
stere m3
sthene 1+3 nt
stilb cd/cm2
stoke 1-4 m2/sec
stone 14 lb
strike 2 bu
surveyfoot british-ft
surveyorschain 66 ft
surveyorslink 66|100 ft
tablespoon 4 fldr
teaspoon 4|3 fldr
tesla weber/m2
therm 1+5 btu
thermie 1+6 cal
timberfoot ft3
tnt 4.6+6 m2/sec2
tonne 1+6 gm
torr mm hg
township 36 mi2
tun 8 barrel
water .22491|2.54 kg/m2-sec2
wey 40 bu
weymass 252 lb
Xunit 1.00202-13m
k 1.38047-16 erg/degC

29
v7/games/Makefile#b00000 Normal file
View File

@ -0,0 +1,29 @@
all: arithmetic fish fortune hangman quiz wump
arithmetic: arithmetic.c
occ -I /usr/include -o arithmetic arithmetic.c
fish: fish.c
occ -I /usr/include -o fish fish.c
fortune: fortune.c
occ -I /usr/include -o fortune fortune.c
hangman: hangman.c
occ -I /usr/include -o hangman hangman.c
quiz: quiz.c
occ -I /usr/include -o quiz quiz.c
wump: wump.c
occ -I /usr/include -o wump wump.c
clean:
cp -p rm -f *.o *.a *.root arithmetic fish fortune hangman quiz wump
install: all
cp lib/fortunes /usr/local/games/lib
cp quiz.k/* /usr/local/games/quiz.k
cp words /usr/local/dict
cp arithmetic fish fortune hangman quiz wump /usr/local/games

24001
v7/games/WORDS#000000 Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,194 @@
#include <signal.h>
#define MAX 100
char types[10];
int right[MAX];
int left[MAX];
int rights;
int wrongs;
long stvec;
long etvec;
long dtvec;
void delete(int, int);
main(argc,argv)
char *argv[];
{
int range, k, dif, l;
char line[100];
int ans,pans,i,j,t;
signal(SIGINT, delete);
range = 11;
dif = 0;
while(argc > 1) {
switch(*argv[1]) {
case '+':
case '-':
case 'x':
case '/':
while(types[dif] = argv[1][dif])
dif++;
break;
default:
range = getnum(argv[1]) + 1;
}
argv++;
argc--;
}
if(range > MAX) {
printf("Range is too large.\n");
exit(0);
}
if(dif == 0) {
types[0] = '+';
types[1] = '-';
dif = 2;
}
for(i = 0; i < range; i++) {
left[i] = right[i] = i;
}
time(&stvec);
k = stvec;
srand(k);
k = 0;
l = 0;
goto start;
loop:
if(++k%20 == 0)
score();
start:
i = skrand(range);
j = skrand(range);
if(dif > 1)
l = random(dif);
switch(types[l]) {
case '+':
default:
ans = left[i] + right[j];
printf("%d + %d = ", left[i], right[j]);
break;
case '-':
t = left[i] + right[j];
ans = left[i];
printf("%d - %d = ", t, right[j]);
break;
case 'x':
ans = left[i] * right[j];
printf("%d x %d = ", left[i], right[j]);
break;
case '/':
while(right[j] == 0)
j = random(range);
t = left[i] * right[j] + random(right[j]);
ans = left[i];
printf("%d / %d = ", t, right[j]);
break;
}
loop1:
getline(line);
dtvec += etvec - stvec;
if(line[0]=='\n') goto loop1;
pans = getnum(line);
if(pans == ans) {
printf("Right!\n");
rights++;
goto loop;
}
else {
printf("What?\n");
wrongs++;
if(range >= MAX) goto loop1;
left[range] = left[i];
right[range++] = right[j];
goto loop1;
}
}
getline(s)
char *s;
{
register char *rs;
rs = s;
while((*rs = getchar()) == ' ');
while(*rs != '\n')
if(*rs == 0)
exit(0);
else if(rs >= &s[99]) {
while((*rs = getchar()) != '\n')
if(*rs == '\0') exit(0);
}
else
*++rs = getchar();
while(*--rs == ' ')
*rs = '\n';
}
getnum(s)
char *s;
{
int a;
char c;
a = 0;
while((c = *s++) >= '0' && c <= '9') {
a = a*10 + c - '0';
}
return(a);
}
random(range)
{
return(rand()%range);
}
skrand(range){
int temp;
temp = random(range) + random(range);
if(temp > range - 1) temp = 2*range - 1 - temp;
return(temp);
}
score()
{
time(&etvec);
printf("\n\nRights %d; Wrongs %d; Score %d%%\n", rights, wrongs,
(rights * 100)/(rights + wrongs));
if(rights == 0) return;
printf("Total time %ld seconds; %.1f seconds per problem\n\n\n",
etvec - stvec,
(etvec - stvec) / (rights + 0.));
sleep(3);
time(&dtvec);
stvec += dtvec - etvec;
}
void delete(int x, int y)
{
if(rights + wrongs == 0.) {
printf("\n");
exit(0);
}
score();
exit(0);
}

BIN
v7/games/backgammon#b50100 Normal file

Binary file not shown.

View File

@ -0,0 +1,585 @@
#include <stdio.h>
#include <stdlib.h>
#
#define NIL (-1)
#define MAXGMOV 10
#define MAXIMOVES 1000
char level; /*'b'=beginner, 'i'=intermediate, 'e'=expert*/
int die1;
int die2;
int i;
int j;
int l;
int m;
int count;
int red[] = {0,2,0,0,0,0,0,0,0,0,0,0,5,
0,0,0,0,3,0,5,0,0,0,0,0,
0,0,0,0,0,0};
int white[] = {0,2,0,0,0,0,0,0,0,0,0,0,5,
0,0,0,0,3,0,5,0,0,0,0,0,
0,0,0,0,0,0};
int probability[] = {0,11,12,13,14,15,16,
06,05,04,03,02,01};
int imoves;
int goodmoves[MAXGMOV] ;
int probmoves[MAXGMOV] ;
struct {int pos[4],mov[4];} moves[MAXIMOVES] ;
int main(int argc, char *argv[])
{
int t,k,n,go[5];
char s[100];
go[5]=NIL;
srand();
printf( "Do you want instructions? Type 'y' for yes,\n");
printf( "anything else means no.?? ");
getstr(s);
if(*s=='y')instructions();
printf( "Choose the level of your oppponent.\n");
printf( "Type 'b' for beginner, or 'i' for intermediate.\n");
printf( "Anything else gets you an expert.?? ");
level='e';
getstr(s);
if(*s=='b')level='b';
else if(*s=='i')level='i';
printf( "You will play red. Do you wan't to move first?\n");
printf( "Type 'y' for yes, anything else means no.?? ");
getstr(s);
if(*s=='y')goto nowhmove;
whitesmv:
roll();
printf( "white rolls %d,%d\n",die1,die2);
printf( "white's move is:");
if(nextmove(white,red)==NIL)goto nowhmove;
if(piececount(white,0,24)==0){
printf( "White wins\n");
printf( "Aren't you ashamed. You've been beaten by a computer.\n");
exit();
}
nowhmove:
prtbrd();
roll();
retry:
printf( "your roll is %d, %d\n",die1,die2);
printf( "your move, please?? ");
getstr(s);
if(*s==0){
printf( "red's move skipped\n");
goto whitesmv;
}
n=sscanf(s,"%d%d%d%d%d",&go[0],&go[1],&go[2],&go[3],&go[4]);
if((die1!=die2&&n>2)||n>4){
printf( "you've made too many moves\n");
goto retry;
}
go[n]=NIL;
if(*s=='-'){
go[0]= -go[0];
t=die1;
die1=die2;
die2=t;
}
for(k=0;k<n;k++){
if(0<=go[k] && go[k]<=24)continue;
else{
printf( "move %d is illegal\n",go[k]);
goto retry;
}
}
if(play(red,white,go))goto retry;
if(piececount(red,0,24)==0){
printf( "Red wins.\n");
printf( "Congratulations! You have just defeated a dumb machine.\n");
exit();
}
goto whitesmv;
}
getstr(s)
char *s;
{
while((*s=getchar())!='\n')s++;
*s=0;
}
play(player,playee,pos)
int *player,*playee,pos[];
{
int k,n,die,ipos;
for(k=0;k<player[0];k++){ /*blots on player[0] must be moved first*/
if(pos[k]==NIL)break;
if(pos[k]!=0){
printf( "piece on position 0 must be moved first\n");
return(-1);
}
}
for(k=0;(ipos=pos[k])!=NIL;k++){
die=k?die2:die1;
n=25-ipos-die;
if(player[ipos]==0)goto badmove;
if(n>0&&playee[n]>=2)goto badmove;
if(n<=0){
if(piececount(player,0,18)!=0)goto badmove;
if((ipos+die)!=25&&
piececount(player,19,24-die)!=0)goto badmove;
}
player[ipos]--;
player[ipos+die]++;
}
for(k=0;pos[k]!=NIL;k++){
die=k?die2:die1;
n=25-pos[k]-die;
if(n>0 && playee[n]==1){
playee[n]=0;
playee[0]++;
}
}
return(0);
badmove:
printf( "Move %d is not legal.\n",ipos);
while(k--){
die=k?die2:die1;
player[pos[k]]++;
player[pos[k]+die]--;
}
return(-1);
}
nextmove(player,playee)
int *player,*playee;
{
int k;
imoves=0;
movegen(player,playee);
if(die1!=die2){
k=die1;
die1=die2;
die2=k;
movegen(player,playee);
}
if(imoves==0){
printf( "roll was %d,%d; no white move possible\n",die1,die2);
return(NIL);
}
k=strategy(player,playee); /*select kth possible move*/
prtmov(k);
update(player,playee,k);
return(0);
}
prtmov(k)
int k;
{
int n;
if(k==NIL)printf( "no move possible\n");
else for(n=0;n<4;n++){
if(moves[k].pos[n]==NIL)break;
printf( " %d, %d",25-moves[k].pos[n],moves[k].mov[n]);
}
printf( "\n");
}
update(player,playee,k)
int *player,*playee,k;
{
int n,t;
for(n=0;n<4;n++){
if(moves[k].pos[n]==NIL)break;
player[moves[k].pos[n]]--;
player[moves[k].pos[n]+moves[k].mov[n]]++;
t=25-moves[k].pos[n]-moves[k].mov[n];
if(t>0 && playee[t]==1){
playee[0]++;
playee[t]--;
}
}
}
piececount(player,startrow,endrow)
int *player,startrow,endrow;
{
int sum;
sum=0;
while(startrow<=endrow)
sum=+player[startrow++];
return(sum);
}
/*
prtmovs()
{
int i1,i2;
printf( "possible moves are\n");
for(i1=0;i1<imoves;i1++){
printf( "\n%d",i1);
for(i2=0;i2<4;i2++){
if(moves[i1].pos[i2]==NIL)break;
printf( "%d, %d",moves[i1].pos[i2],moves[i1].mov[i2]);
}
}
printf( "\n");
}
*/
roll()
{
extern int die1,die2;
die1=(rand()>>8)%6+1;
die2=(rand()>>8)%6+1;
}
movegen(mover,movee)
int *mover,*movee;
{
extern int i,j,l,m,count;
extern int die1,die2;
int k;
for(i=0;i<=24;i++){
count=0;
if(mover[i]==0)continue;
if((k=25-i-die1)>0&&movee[k]>=2)
if(mover[0]>0)break;
else continue;
if(k<=0){
if(piececount(mover,0,18)!=0)break;
if((i+die1)!=25&&
piececount(mover,19,24-die1)!=0)break;
}
mover[i]--;
mover[i+die1]++;
count=1;
for(j=0;j<=24;j++){
if(mover[j]==0)continue;
if((k=25-j-die2)>0&&movee[k]>=2)
if(mover[0]>0)break;
else continue;
if(k<=0){
if(piececount(mover,0,18)!=0)break;
if((j+die2)!=25&&
piececount(mover,19,24-die2)!=0)break;
}
mover[j]--;
mover[j+die2]++;
count=2;
if(die1!=die2){
moverecord(mover);
if(mover[0]>0)break;
else continue;
}
for(l=0;l<=24;l++){
if(mover[l]==0)continue;
if((k=25-l-die1)>0&&movee[k]>=2)
if(mover[0]>0)break;
else continue;
if(k<=0){
if(piececount(mover,0,18)!=0)break;
if((l+die2)!=25&&
piececount(mover,19,24-die1)!=0)break;
}
mover[l]--;
mover[l+die1]++;
count=3;
for(m=0;m<=24;m++){
if(mover[m]==0)continue;
if((k=25-m-die1)>=0&&movee[k]>=2)
if(mover[0]>0)break;
else continue;
if(k<=0){
if(piececount(mover,0,18)!=0)break;
if((m+die2)!=25&&
piececount(mover,19,24-die1)!=0)break;
}
count=4;
moverecord(mover);
if(mover[0]>0)break;
}
if(count==3)moverecord(mover);
else{
mover[l]++;
mover[l+die1]--;
}
if(mover[0]>0)break;
}
if(count==2)moverecord(mover);
else{
mover[j]++;
mover[j+die1]--;
}
if(mover[0]>0)break;
}
if(count==1)moverecord(mover);
else{
mover[i]++;
mover[i+die1]--;
}
if(mover[0]>0)break;
}
}
moverecord(mover)
int *mover;
{
extern int i,j,l,m,imoves,count;
int t;
if(imoves>=MAXIMOVES)goto undo;;
for(t=0;t<=3;t++)
moves[imoves].pos[t]= NIL;
switch(count){
case 4:
moves[imoves].pos[3]=m;
moves[imoves].mov[3]=die1;
case 3:
moves[imoves].pos[2]=l;
moves[imoves].mov[2]=die1;
case 2:
moves[imoves].pos[1]=j;
moves[imoves].mov[1]=die2;
case 1:
moves[imoves].pos[0]=i;
moves[imoves].mov[0]=die1;
imoves++;
}
undo:
switch(count){
case 4:
break;
case 3:
mover[l]++;
mover[l+die1]--;
break;
case 2:
mover[j]++;
mover[j+die2]--;
break;
case 1:
mover[i]++;
mover[i+die1]--;
}
}
strategy(player,playee)
int *player,*playee;
{
extern char level;
int k,n,nn,bestval,moveval,prob;
n=0;
if(imoves==0)return(NIL);
goodmoves[0]=NIL;
bestval= -32000;
for(k=0;k<imoves;k++){
if((moveval=eval(player,playee,k,&prob))<bestval)continue;
if(moveval>bestval){
bestval=moveval;
n=0;
}
if(n<MAXGMOV){
goodmoves[n]=k;
probmoves[n++]=prob;
}
}
if(level=='e' && n>1){
nn=n;
n=0;
prob=32000;
for(k=0;k<nn;k++){
if((moveval=probmoves[k])>prob)continue;
if(moveval<prob){
prob=moveval;
n=0;
}
goodmoves[n]=goodmoves[k];
probmoves[n++]=probmoves[k];
}
}
return(goodmoves[(rand()>>4)%n]);
}
eval(player,playee,k,prob)
int *player,*playee,k,*prob;
{
extern char level;
int newtry[31],newother[31],*r,*q,*p,n,sum,first;
int ii,lastwhite,lastred;
*prob=sum=0;
r=player+25;
p=newtry;
q=newother;
while(player<r){
*p++= *player++;
*q++= *playee++;
}
q=newtry+31;
for(p=newtry+25;p<q;) *p++ = 0; /*zero out spaces for hit pieces*/
for(n=0;n<4;n++){
if(moves[k].pos[n]==NIL)break;
newtry[moves[k].pos[n]]--;
newtry[ii=moves[k].pos[n]+moves[k].mov[n]]++;
if(ii<25 && newother[25-ii]==1){
newother[25-ii]=0;
newother[0]++;
if(ii<=15 && level=='e')sum++; /*hit if near other's home*/
}
}
for(lastred=0;newother[lastred]==0;lastred++);
for(lastwhite=0;newtry[lastwhite]==0;lastwhite++);
lastwhite=25-lastwhite;
if(lastwhite<=6 && lastwhite<lastred)sum=1000;
if(lastwhite<lastred && level=='e'
&& lastwhite>6){ /*expert's running game.
First priority to get all
pieces into white's home*/
for(sum=1000;lastwhite>6;lastwhite--)
sum=sum-lastwhite*newtry[25-lastwhite];
}
for(first=0;first<25;first++)
if(newother[first]!=0)break; /*find other's first piece*/
q=newtry+25;
for(p=newtry+1;p<q;)if(*p++ > 1)sum++; /*blocked points are good*/
if(first>5){ /*only stress removing pieces if homeboard
cannot be hit
*/
q=newtry+31;
p=newtry+25;
for(n=6;p<q;n--)
sum=+ *p++ * n; /*remove pieces, but just barely*/
}
if(level!='b'){
r=newtry+25-first; /*singles past this point can't be hit*/
for(p=newtry+7;p<r;)
if(*p++ == 1)sum--; /*singles are bad after 1st 6 points
if they can be hit*/
q=newtry+3;
for(p=newtry;p<q;)sum=- *p++; /*bad to be on 1st three points*/
}
for(n=1;n<=4;n++)
*prob=+ n*getprob(newtry,newother,6*n-5,6*n);
return(sum);
}
instructions()
{
printf( "To play backgammon, type the numbers of the points\n");
printf( "from which pieces are to be moved. Thus, if the\n");
printf( "roll is '3,5', typing '2 6' will move a piece\n");
printf( "from point 2 three spaces to point 5,\n");
printf( "and a piece from point 6 forward to\n");
printf( "point 11. If the moves must be made in the\n");
printf( "opposite order, the first character typed must\n");
printf( "be a minus ('-'). Thus, typing\n");
printf( "'-2 6' moves the piece on point 2\n");
printf( "by 5, and the piece on point 6 by 3.\n");
printf( "If you want to move a single piece several times,\n");
printf( "the sequence of points from which it is to be\n");
printf( "moved must be typed. Thus '14 17' will move\n");
printf( "a piece from point 14 to point 17 and thence to\n");
printf( "to point 22.\n");
printf( "If a double is rolled, you should type four numbers.\n");
printf( "Red pieces that have been removed from the board by\n");
printf( "being hit by white are on point 0 and\n");
printf( "must be brought in before any other move can be made.\n");
printf( "White pieces that are hit are removed to point 25.\n");
printf( "You will not be allowed to make an illegal move, or\n");
printf( "to make too many moves. However, if you make too\n");
printf( "few moves, the program does not care. In particular\n");
printf( "you may skip your turn by typing a 'new-line'\n");
printf( "all by itself.\n\n");
}
getprob(player,playee,start,finish)
int *player,*playee,start,finish;
{ /*returns the probability (times 102) that any
pieces belonging to 'player' and lying between
his points 'start' and 'finish' will be hit
by a piece belonging to playee
*/
int k,n,sum;
sum=0;
for(;start<=finish;start++){
if(player[start]==1){
for(k=1;k<=12;k++){
if((n=25-start-k)<0)break;
if(playee[n]!=0)sum=+probability[k];
}
}
}
return(sum);
}
prtbrd()
{
int k;
printf( "White's Home\n");
for(k=1;k<=6;k++)
printf( "%4d",k);
printf( " ");
for(k=7;k<=12;k++)printf( "%4d",k);
putchar('\r' );
for(k=1;k<=54;k++)putchar('_' );
putchar('\n' );
numline(red,white,1,6);
printf( " ");
numline(red,white,7,12);
putchar('\n' );
colorline(red,'R',white,'W',1,6);
printf( " ");
colorline(red,'R',white,'W',7,12);
putchar('\n' );
if(white[0]!=0)printf( "%28dW\n",white[0]);
else putchar('\n' );
if(red[0]!=0)printf( "%28dR\n",red[0]);
else putchar('\n' );
colorline(white,'W',red,'R',1,6);
printf( " ");
colorline(white,'W',red,'R',7,12);
putchar('\n' );
numline(white,red,1,6);
printf( " ");
numline(white,red,7,12);
putchar('\r' );
for(k=1;k<=54;k++)putchar('_' );
putchar('\n' );
for(k=24;k>=19;k--)printf( "%4d",k);
printf( " ");
for(k=18;k>=13;k--)printf( "%4d",k);
printf( "\nRed's Home\n\n\n\n\n");
}
numline(upcol,downcol,start,fin)
int *upcol,*downcol,start,fin;
{
int k,n;
for(k=start;k<=fin;k++){
if((n=upcol[k])!=0 || (n=downcol[25-k])!=0)printf( "%4d",n);
else printf( " ");
}
}
colorline(upcol,c1,downcol,c2,start,fin)
int *upcol,*downcol,start,fin;
char c1,c2;
{
int k;
char c;
for(k=start;k<=fin;k++){
c=' ';
if(upcol[k]!=0)c=c1;
if(downcol[25-k]!=0)c=c2;
printf( " %c",c);
}
}
int rrno = 0;
srand(){
rrno = _look( 0x40000 );
_store( 0x40000, rrno+1 );
}
rand(){
rrno *= 0106273;
rrno += 020202;
return( rrno & 077777 );
}
_look(p) int *p; {
return( *p );
}
_store( p, numb ) int *p; {
*p = numb;
}

View File

@ -0,0 +1,584 @@
# include <stdio.h>
#
#define NIL (-1)
#define MAXGMOV 10
#define MAXIMOVES 1000
char level; /*'b'=beginner, 'i'=intermediate, 'e'=expert*/
int die1;
int die2;
int i;
int j;
int l;
int m;
int count;
int red[] {0,2,0,0,0,0,0,0,0,0,0,0,5,
0,0,0,0,3,0,5,0,0,0,0,0,
0,0,0,0,0,0};
int white[] {0,2,0,0,0,0,0,0,0,0,0,0,5,
0,0,0,0,3,0,5,0,0,0,0,0,
0,0,0,0,0,0};
int probability[]{0,11,12,13,14,15,16,
06,05,04,03,02,01};
int imoves;
int goodmoves[MAXGMOV] ;
int probmoves[MAXGMOV] ;
struct {int pos[4],mov[4];} moves[MAXIMOVES] ;
main()
{
int t,k,n,go[5];
char s[100];
go[5]=NIL;
srand();
printf( "Do you want instructions? Type 'y' for yes,\n");
printf( "anything else means no.?? ");
getstr(s);
if(*s=='y')instructions();
printf( "Choose the level of your oppponent.\n");
printf( "Type 'b' for beginner, or 'i' for intermediate.\n");
printf( "Anything else gets you an expert.?? ");
level='e';
getstr(s);
if(*s=='b')level='b';
else if(*s=='i')level='i';
printf( "You will play red. Do you wan't to move first?\n");
printf( "Type 'y' for yes, anything else means no.?? ");
getstr(s);
if(*s=='y')goto nowhmove;
whitesmv:
roll();
printf( "white rolls %d,%d\n",die1,die2);
printf( "white's move is:");
if(nextmove(white,red)==NIL)goto nowhmove;
if(piececount(white,0,24)==0){
printf( "White wins\n");
printf( "Aren't you ashamed. You've been beaten by a computer.\n");
exit();
}
nowhmove:
prtbrd();
roll();
retry:
printf( "your roll is %d, %d\n",die1,die2);
printf( "your move, please?? ");
getstr(s);
if(*s==0){
printf( "red's move skipped\n");
goto whitesmv;
}
n=sscanf(s,"%d%d%d%d%d",&go[0],&go[1],&go[2],&go[3],&go[4]);
if((die1!=die2&&n>2)||n>4){
printf( "you've made too many moves\n");
goto retry;
}
go[n]=NIL;
if(*s=='-'){
go[0]= -go[0];
t=die1;
die1=die2;
die2=t;
}
for(k=0;k<n;k++){
if(0<=go[k] && go[k]<=24)continue;
else{
printf( "move %d is illegal\n",go[k]);
goto retry;
}
}
if(play(red,white,go))goto retry;
if(piececount(red,0,24)==0){
printf( "Red wins.\n");
printf( "Congratulations! You have just defeated a dumb machine.\n");
exit();
}
goto whitesmv;
}
getstr(s)
char *s;
{
while((*s=getchar())!='\n')s++;
*s=0;
}
play(player,playee,pos)
int *player,*playee,pos[];
{
int k,n,die,ipos;
for(k=0;k<player[0];k++){ /*blots on player[0] must be moved first*/
if(pos[k]==NIL)break;
if(pos[k]!=0){
printf( "piece on position 0 must be moved first\n");
return(-1);
}
}
for(k=0;(ipos=pos[k])!=NIL;k++){
die=k?die2:die1;
n=25-ipos-die;
if(player[ipos]==0)goto badmove;
if(n>0&&playee[n]>=2)goto badmove;
if(n<=0){
if(piececount(player,0,18)!=0)goto badmove;
if((ipos+die)!=25&&
piececount(player,19,24-die)!=0)goto badmove;
}
player[ipos]--;
player[ipos+die]++;
}
for(k=0;pos[k]!=NIL;k++){
die=k?die2:die1;
n=25-pos[k]-die;
if(n>0 && playee[n]==1){
playee[n]=0;
playee[0]++;
}
}
return(0);
badmove:
printf( "Move %d is not legal.\n",ipos);
while(k--){
die=k?die2:die1;
player[pos[k]]++;
player[pos[k]+die]--;
}
return(-1);
}
nextmove(player,playee)
int *player,*playee;
{
int k;
imoves=0;
movegen(player,playee);
if(die1!=die2){
k=die1;
die1=die2;
die2=k;
movegen(player,playee);
}
if(imoves==0){
printf( "roll was %d,%d; no white move possible\n",die1,die2);
return(NIL);
}
k=strategy(player,playee); /*select kth possible move*/
prtmov(k);
update(player,playee,k);
return(0);
}
prtmov(k)
int k;
{
int n;
if(k==NIL)printf( "no move possible\n");
else for(n=0;n<4;n++){
if(moves[k].pos[n]==NIL)break;
printf( " %d, %d",25-moves[k].pos[n],moves[k].mov[n]);
}
printf( "\n");
}
update(player,playee,k)
int *player,*playee,k;
{
int n,t;
for(n=0;n<4;n++){
if(moves[k].pos[n]==NIL)break;
player[moves[k].pos[n]]--;
player[moves[k].pos[n]+moves[k].mov[n]]++;
t=25-moves[k].pos[n]-moves[k].mov[n];
if(t>0 && playee[t]==1){
playee[0]++;
playee[t]--;
}
}
}
piececount(player,startrow,endrow)
int *player,startrow,endrow;
{
int sum;
sum=0;
while(startrow<=endrow)
sum=+player[startrow++];
return(sum);
}
/*
prtmovs()
{
int i1,i2;
printf( "possible moves are\n");
for(i1=0;i1<imoves;i1++){
printf( "\n%d",i1);
for(i2=0;i2<4;i2++){
if(moves[i1].pos[i2]==NIL)break;
printf( "%d, %d",moves[i1].pos[i2],moves[i1].mov[i2]);
}
}
printf( "\n");
}
*/
roll()
{
extern int die1,die2;
die1=(rand()>>8)%6+1;
die2=(rand()>>8)%6+1;
}
movegen(mover,movee)
int *mover,*movee;
{
extern int i,j,l,m,count;
extern int die1,die2;
int k;
for(i=0;i<=24;i++){
count=0;
if(mover[i]==0)continue;
if((k=25-i-die1)>0&&movee[k]>=2)
if(mover[0]>0)break;
else continue;
if(k<=0){
if(piececount(mover,0,18)!=0)break;
if((i+die1)!=25&&
piececount(mover,19,24-die1)!=0)break;
}
mover[i]--;
mover[i+die1]++;
count=1;
for(j=0;j<=24;j++){
if(mover[j]==0)continue;
if((k=25-j-die2)>0&&movee[k]>=2)
if(mover[0]>0)break;
else continue;
if(k<=0){
if(piececount(mover,0,18)!=0)break;
if((j+die2)!=25&&
piececount(mover,19,24-die2)!=0)break;
}
mover[j]--;
mover[j+die2]++;
count=2;
if(die1!=die2){
moverecord(mover);
if(mover[0]>0)break;
else continue;
}
for(l=0;l<=24;l++){
if(mover[l]==0)continue;
if((k=25-l-die1)>0&&movee[k]>=2)
if(mover[0]>0)break;
else continue;
if(k<=0){
if(piececount(mover,0,18)!=0)break;
if((l+die2)!=25&&
piececount(mover,19,24-die1)!=0)break;
}
mover[l]--;
mover[l+die1]++;
count=3;
for(m=0;m<=24;m++){
if(mover[m]==0)continue;
if((k=25-m-die1)>=0&&movee[k]>=2)
if(mover[0]>0)break;
else continue;
if(k<=0){
if(piececount(mover,0,18)!=0)break;
if((m+die2)!=25&&
piececount(mover,19,24-die1)!=0)break;
}
count=4;
moverecord(mover);
if(mover[0]>0)break;
}
if(count==3)moverecord(mover);
else{
mover[l]++;
mover[l+die1]--;
}
if(mover[0]>0)break;
}
if(count==2)moverecord(mover);
else{
mover[j]++;
mover[j+die1]--;
}
if(mover[0]>0)break;
}
if(count==1)moverecord(mover);
else{
mover[i]++;
mover[i+die1]--;
}
if(mover[0]>0)break;
}
}
moverecord(mover)
int *mover;
{
extern int i,j,l,m,imoves,count;
int t;
if(imoves>=MAXIMOVES)goto undo;;
for(t=0;t<=3;t++)
moves[imoves].pos[t]= NIL;
switch(count){
case 4:
moves[imoves].pos[3]=m;
moves[imoves].mov[3]=die1;
case 3:
moves[imoves].pos[2]=l;
moves[imoves].mov[2]=die1;
case 2:
moves[imoves].pos[1]=j;
moves[imoves].mov[1]=die2;
case 1:
moves[imoves].pos[0]=i;
moves[imoves].mov[0]=die1;
imoves++;
}
undo:
switch(count){
case 4:
break;
case 3:
mover[l]++;
mover[l+die1]--;
break;
case 2:
mover[j]++;
mover[j+die2]--;
break;
case 1:
mover[i]++;
mover[i+die1]--;
}
}
strategy(player,playee)
int *player,*playee;
{
extern char level;
int k,n,nn,bestval,moveval,prob;
n=0;
if(imoves==0)return(NIL);
goodmoves[0]=NIL;
bestval= -32000;
for(k=0;k<imoves;k++){
if((moveval=eval(player,playee,k,&prob))<bestval)continue;
if(moveval>bestval){
bestval=moveval;
n=0;
}
if(n<MAXGMOV){
goodmoves[n]=k;
probmoves[n++]=prob;
}
}
if(level=='e' && n>1){
nn=n;
n=0;
prob=32000;
for(k=0;k<nn;k++){
if((moveval=probmoves[k])>prob)continue;
if(moveval<prob){
prob=moveval;
n=0;
}
goodmoves[n]=goodmoves[k];
probmoves[n++]=probmoves[k];
}
}
return(goodmoves[(rand()>>4)%n]);
}
eval(player,playee,k,prob)
int *player,*playee,k,*prob;
{
extern char level;
int newtry[31],newother[31],*r,*q,*p,n,sum,first;
int ii,lastwhite,lastred;
*prob=sum=0;
r=player+25;
p=newtry;
q=newother;
while(player<r){
*p++= *player++;
*q++= *playee++;
}
q=newtry+31;
for(p=newtry+25;p<q;) *p++ = 0; /*zero out spaces for hit pieces*/
for(n=0;n<4;n++){
if(moves[k].pos[n]==NIL)break;
newtry[moves[k].pos[n]]--;
newtry[ii=moves[k].pos[n]+moves[k].mov[n]]++;
if(ii<25 && newother[25-ii]==1){
newother[25-ii]=0;
newother[0]++;
if(ii<=15 && level=='e')sum++; /*hit if near other's home*/
}
}
for(lastred=0;newother[lastred]==0;lastred++);
for(lastwhite=0;newtry[lastwhite]==0;lastwhite++);
lastwhite=25-lastwhite;
if(lastwhite<=6 && lastwhite<lastred)sum=1000;
if(lastwhite<lastred && level=='e'
&& lastwhite>6){ /*expert's running game.
First priority to get all
pieces into white's home*/
for(sum=1000;lastwhite>6;lastwhite--)
sum=sum-lastwhite*newtry[25-lastwhite];
}
for(first=0;first<25;first++)
if(newother[first]!=0)break; /*find other's first piece*/
q=newtry+25;
for(p=newtry+1;p<q;)if(*p++ > 1)sum++; /*blocked points are good*/
if(first>5){ /*only stress removing pieces if homeboard
cannot be hit
*/
q=newtry+31;
p=newtry+25;
for(n=6;p<q;n--)
sum=+ *p++ * n; /*remove pieces, but just barely*/
}
if(level!='b'){
r=newtry+25-first; /*singles past this point can't be hit*/
for(p=newtry+7;p<r;)
if(*p++ == 1)sum--; /*singles are bad after 1st 6 points
if they can be hit*/
q=newtry+3;
for(p=newtry;p<q;)sum=- *p++; /*bad to be on 1st three points*/
}
for(n=1;n<=4;n++)
*prob=+ n*getprob(newtry,newother,6*n-5,6*n);
return(sum);
}
instructions()
{
printf( "To play backgammon, type the numbers of the points\n");
printf( "from which pieces are to be moved. Thus, if the\n");
printf( "roll is '3,5', typing '2 6' will move a piece\n");
printf( "from point 2 three spaces to point 5,\n");
printf( "and a piece from point 6 forward to\n");
printf( "point 11. If the moves must be made in the\n");
printf( "opposite order, the first character typed must\n");
printf( "be a minus ('-'). Thus, typing\n");
printf( "'-2 6' moves the piece on point 2\n");
printf( "by 5, and the piece on point 6 by 3.\n");
printf( "If you want to move a single piece several times,\n");
printf( "the sequence of points from which it is to be\n");
printf( "moved must be typed. Thus '14 17' will move\n");
printf( "a piece from point 14 to point 17 and thence to\n");
printf( "to point 22.\n");
printf( "If a double is rolled, you should type four numbers.\n");
printf( "Red pieces that have been removed from the board by\n");
printf( "being hit by white are on point 0 and\n");
printf( "must be brought in before any other move can be made.\n");
printf( "White pieces that are hit are removed to point 25.\n");
printf( "You will not be allowed to make an illegal move, or\n");
printf( "to make too many moves. However, if you make too\n");
printf( "few moves, the program does not care. In particular\n");
printf( "you may skip your turn by typing a 'new-line'\n");
printf( "all by itself.\n\n");
}
getprob(player,playee,start,finish)
int *player,*playee,start,finish;
{ /*returns the probability (times 102) that any
pieces belonging to 'player' and lying between
his points 'start' and 'finish' will be hit
by a piece belonging to playee
*/
int k,n,sum;
sum=0;
for(;start<=finish;start++){
if(player[start]==1){
for(k=1;k<=12;k++){
if((n=25-start-k)<0)break;
if(playee[n]!=0)sum=+probability[k];
}
}
}
return(sum);
}
prtbrd()
{
int k;
printf( "White's Home\n");
for(k=1;k<=6;k++)
printf( "%4d",k);
printf( " ");
for(k=7;k<=12;k++)printf( "%4d",k);
putchar('\r' );
for(k=1;k<=54;k++)putchar('_' );
putchar('\n' );
numline(red,white,1,6);
printf( " ");
numline(red,white,7,12);
putchar('\n' );
colorline(red,'R',white,'W',1,6);
printf( " ");
colorline(red,'R',white,'W',7,12);
putchar('\n' );
if(white[0]!=0)printf( "%28dW\n",white[0]);
else putchar('\n' );
if(red[0]!=0)printf( "%28dR\n",red[0]);
else putchar('\n' );
colorline(white,'W',red,'R',1,6);
printf( " ");
colorline(white,'W',red,'R',7,12);
putchar('\n' );
numline(white,red,1,6);
printf( " ");
numline(white,red,7,12);
putchar('\r' );
for(k=1;k<=54;k++)putchar('_' );
putchar('\n' );
for(k=24;k>=19;k--)printf( "%4d",k);
printf( " ");
for(k=18;k>=13;k--)printf( "%4d",k);
printf( "\nRed's Home\n\n\n\n\n");
}
numline(upcol,downcol,start,fin)
int *upcol,*downcol,start,fin;
{
int k,n;
for(k=start;k<=fin;k++){
if((n=upcol[k])!=0 || (n=downcol[25-k])!=0)printf( "%4d",n);
else printf( " ");
}
}
colorline(upcol,c1,downcol,c2,start,fin)
int *upcol,*downcol,start,fin;
char c1,c2;
{
int k;
char c;
for(k=start;k<=fin;k++){
c=' ';
if(upcol[k]!=0)c=c1;
if(downcol[25-k]!=0)c=c2;
printf( " %c",c);
}
}
int rrno 0;
srand(){
rrno = _look( 0x40000 );
_store( 0x40000, rrno+1 );
}
rand(){
rrno =* 0106273;
rrno =+ 020202;
return( rrno & 077777 );
}
_look(p) int *p; {
return( *p );
}
_store( p, numb ) int *p; {
*p = numb;
}

527
v7/games/fish.c#b00008 Normal file
View File

@ -0,0 +1,527 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* Through, `my' refers to the program, `your' to the player */
# define CTYPE 13
# define CTSIZ (CTYPE+1)
# define DECK 52
# define NOMORE 0
# define DOUBTIT (-1);
typedef char HAND[CTSIZ];
/* data structures */
short debug;
HAND myhand;
HAND yourhand;
char deck[DECK];
short nextcd;
int proflag;
int shuffle(void);
int choose(char a[], int n);
int error(char *s);
int rand(void);
int draw(void);
int empty(HAND h);
int mark(HAND hand, int cd);
int deal(HAND hand, int n);
int stats(void);
int phand(HAND h);
int instruct(void);
int game(void);
int start(HAND h);
int hedrew(int d);
int heguessed(int d);
int myguess(void);
int move(HAND hs, HAND ht, int g, int v);
int guess(void);
int madebook(int x);
int score(void);
/* utility and output programs */
void test(void) {
HAND h;
int i;
i=mark(h,i);
}
int shuffle(void) {
/* shuffle the deck, and reset nextcd */
/* uses the random number generator `rand' in the C library */
/* assumes that `srand' has already been called */
register i;
for( i=0; i<DECK; ++i ) deck[i] = (i%13)+1; /* seed the deck */
for( i=DECK; i>0; --i ){ /* select the next card at random */
deck[i-1] = choose( deck, i );
}
nextcd = 0;
}
int choose(char a[], int n ) {
/* pick and return one at random from the n choices in a */
/* The last one is moved to replace the one chosen */
register j, t;
if( n <= 0 ) error( "null choice" );
j = rand() % n;
t = a[j];
a[j] = a[n-1];
return(t);
}
int draw(void) {
if( nextcd >= DECK ) return( NOMORE );
return( deck[nextcd++] );
}
int error(char *s) {
fprintf( stderr, "error: " );
fprintf( stderr, s );
exit( 1 );
}
int empty(HAND h) {
register i;
for( i=1; i<=CTYPE; ++i ){
if( h[i] != 0 && h[i] != 4 ) return( 0 );
}
return( i );
}
int mark(HAND hand, int cd) {
if( cd != NOMORE ){
++hand[cd];
if( hand[cd] > 4 ){
error( "mark overflow" );
}
}
return( cd );
}
int deal(HAND hand, int n) {
while( n-- ){
if( mark( hand, draw() ) == NOMORE ) error( "deck exhausted" );
}
}
char *cname[] = {
"NOMORE!!!",
"A",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K"
};
int stats(void) {
register i, ct, b;
if( proflag ) printf( "Pro level\n" );
b = ct = 0;
for( i=1; i<=CTYPE; ++i ){
if( myhand[i] == 4 ) ++b;
else ct += myhand[i];
}
if( b ){
printf( "My books: " );
for( i=1; i<=CTYPE; ++i ){
if( myhand[i] == 4 ) printf( "%s ", cname[i] );
}
printf( "\n" );
}
printf( "%d cards in my hand, %d in the pool\n", ct, DECK-nextcd );
printf( "You ask me for: " );
}
int phand(HAND h) {
register i, j;
j = 0;
for( i = 1; i<= CTYPE; ++i ){
if( h[i] == 4 ) {
++j;
continue;
}
if( h[i] ){
register k;
k = h[i];
while( k-- ) printf( "%s ", cname[i] );
}
}
if( j ){
printf( "+ Books of " );
for( i=1; i<=CTYPE; ++i ){
if( h[i] == 4 ) printf( "%s ", cname[i] );
}
}
printf( "\n" );
}
int main(int argc, char *argv[]) {
/* initialize shuffling, ask for instructions, play game, die */
register c;
if( argc > 1 && argv[1][0] == '-' ){
while( argv[1][0] == '-' ) { ++argv[1]; ++debug; }
argv++;
argc--;
}
srand( getpid() );
printf( "instructions?\n" );
if( (c=getchar()) != '\n' ){
if( c != 'n' ) instruct();
while( getchar() != '\n' );
}
game();
}
/* print instructions */
char *inst[] = {
"`Go Fish' is a childrens' card game.",
"The Object is to accumulate `books' of 4 cards",
"with the same face value.",
"The players alternate turns; each turn begins with one",
"player selecting a card from his hand, and asking the",
"other player for all cards of that face value.",
"If the other player has one or more cards of that face value",
"in his hand, he gives them to the first player, and the",
"first player makes another request.",
"Eventually, the first player asks for a card which",
"is not in the second player's hand: he replies `GO FISH!'",
"The first player then draws a card from the `pool' of",
"undealt cards. If this is the card he had last requested, he",
"draws again.",
"When a book is made, either through drawing or requesting,",
"the cards are laid down and no further action takes",
"place with that face value.",
"To play the computer, simply make guesses by typing",
"a, 2, 3, 4, 5, 6, 7, 8, 9, 10, j, q, or k when asked.",
"Hitting return gives you information about the size of",
"my hand and the pool, and tells you about my books.",
"Saying `p' as a first guess puts you into `pro' level;",
"The default is pretty dumb!",
"Good Luck!",
""
};
int instruct(void) {
register char **cpp;
printf( "\n" );
for( cpp = inst; **cpp != '\0'; ++cpp ){
printf( "%s\n", *cpp );
}
}
int game(void) {
shuffle();
deal( myhand, 7 );
deal( yourhand, 7 );
start( myhand );
for(;;){
register g;
/* you make repeated guesses */
for(;;) {
printf( "your hand is: " );
phand( yourhand );
printf( "you ask me for: " );
if( !move( yourhand, myhand, g=guess(), 0 ) ) break;
printf( "Guess again\n" );
}
/* I make repeated guesses */
for(;;) {
if( (g=myguess()) != NOMORE ){
printf( "I ask you for: %s\n", cname[g] );
}
if( !move( myhand, yourhand, g, 1 ) ) break;
printf( "I get another guess\n" );
}
}
}
/* reflect the effect of a move on the hands */
int move(HAND hs, HAND ht, int g, int v) {
/* hand hs has made a guess, g, directed towards ht */
/* v on indicates that the guess was made by the machine */
register int d;
char *sp, *tp;
sp = tp = "I";
if( v ) tp = "You";
else sp = "You";
if( g == NOMORE ){
d = draw();
if( d == NOMORE ) score();
else {
printf( "Empty Hand\n" );
if( !v ) printf( "You draw %s\n", cname[d] );
mark( hs, d );
}
return( 0 );
}
if( !v ) heguessed( g );
if( hs[g] == 0 ){
if( v ) error( "Rotten Guess" );
printf( "You don't have any %s's\n", cname[g] );
return(1);
}
if( ht[g] ){ /* successful guess */
printf( "%s have %d %s%s\n", tp, ht[g], cname[g], ht[g]>1?"'s":"" );
hs[g] += ht[g];
ht[g] = 0;
if( hs[g] == 4 ) madebook(g);
return(1);
}
/* GO FISH! */
printf( "%s say \"GO FISH!\"\n", tp );
newdraw:
d = draw();
if( d == NOMORE ) {
printf( "No more cards\n" );
return(0);
}
mark( hs, d );
if( !v ) printf( "You draw %s\n", cname[d] );
if( hs[d] == 4 ) madebook(d);
if( d == g ){
printf( "%s drew the guess, so draw again\n", sp );
if( !v ) hedrew( d );
goto newdraw;
}
return( 0 );
}
int madebook(int x) {
printf( "Made a book of %s's\n", cname[x] );
}
int score(void) {
register my, your, i;
my = your = 0;
printf( "The game is over.\nMy books: " );
for( i=1; i<=CTYPE;++i ){
if( myhand[i] == 4 ){
++my;
printf( "%s ", cname[i] );
}
}
printf( "\nYour books: " );
for( i=1; i<=CTYPE;++i ){
if( yourhand[i] == 4 ){
++your;
printf( "%s ", cname[i] );
}
}
printf( "\n\nI have %d, you have %d\n", my, your );
printf( "\n%s win!!!\n", my>your?"I":"You" );
exit(0);
}
# define G(x) { if(go) goto err; else go = x; }
int guess(void) {
/* get the guess from the tty and return it... */
register g, go;
go = 0;
for(;;) {
switch( g = getchar() ){
case 'p':
case 'P':
++proflag;
continue;
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
G(g-'0');
continue;
case 'a':
case 'A':
G(1);
continue;
case '1':
G(10);
continue;
case '0':
if( go != 10 ) goto err;
continue;
case 'J':
case 'j':
G(11);
continue;
case 'Q':
case 'q':
G(12);
continue;
case 'K':
case 'k':
G(13);
continue;
case '\n':
if( empty( yourhand ) ) return( NOMORE );
if( go == 0 ){
stats();
continue;
}
return( go );
case ' ':
case '\t':
continue;
default:
err:
while( g != '\n' ) g = getchar();
printf( "what?\n" );
continue;
}
}
}
/* the program's strategy appears from here to the end */
char try[100];
char ntry;
char haveguessed[CTSIZ];
char hehas[CTSIZ];
int start(HAND h) {
;
}
int hedrew(int d){
++hehas[d];
}
int heguessed(int d){
++hehas[d];
}
int myguess(void) {
register i, lg, t;
if( empty( myhand ) ) return( NOMORE );
/* make a list of those things which i have */
/* leave off any which are books */
/* if something is found that he has, guess it! */
ntry = 0;
for( i=1; i<=CTYPE; ++i ){
if( myhand[i] == 0 || myhand[i] == 4 ) continue;
try[ntry++] = i;
}
if( !proflag ) goto random;
/* get ones he has, if any */
for( i=0; i<ntry; ++i ){
if( hehas[try[i]] ) {
i = try[i];
goto gotguess;
}
}
/* is there one that has never been guessed; if so, guess it */
lg = 101;
for( i=0; i<ntry; ++i ){
if( haveguessed[try[i]] < lg ) lg = haveguessed[try[i]];
}
/* remove all those not guessed longest ago */
t = 0;
for( i=0; i<ntry; ++i ){
if( haveguessed[try[i]] == lg ) try[t++] = try[i];
}
ntry = t;
if( t <= 0 ) error( "bad guessing loop" );
random:
i = choose( try, ntry ); /* make a random choice */
gotguess: /* do bookkeeping */
hehas[i] = 0; /* he won't anymore! */
for( t=1; t<=CTYPE; ++t ){
if( haveguessed[t] ) --haveguessed[t];
}
haveguessed[i] = 100; /* will have guessed it */
return(i);
}

498
v7/games/fish.c.orig#b00008 Normal file
View File

@ -0,0 +1,498 @@
# include <stdio.h>
/* Through, `my' refers to the program, `your' to the player */
# define CTYPE 13
# define CTSIZ (CTYPE+1)
# define DECK 52
# define NOMORE 0
# define DOUBTIT (-1);
typedef char HAND[CTSIZ];
/* data structures */
short debug;
HAND myhand;
HAND yourhand;
char deck[DECK];
short nextcd;
int proflag;
/* utility and output programs */
shuffle(){
/* shuffle the deck, and reset nextcd */
/* uses the random number generator `rand' in the C library */
/* assumes that `srand' has already been called */
register i;
for( i=0; i<DECK; ++i ) deck[i] = (i%13)+1; /* seed the deck */
for( i=DECK; i>0; --i ){ /* select the next card at random */
deck[i-1] = choose( deck, i );
}
nextcd = 0;
}
choose( a, n ) char a[]; {
/* pick and return one at random from the n choices in a */
/* The last one is moved to replace the one chosen */
register j, t;
if( n <= 0 ) error( "null choice" );
j = rand() % n;
t = a[j];
a[j] = a[n-1];
return(t);
}
draw() {
if( nextcd >= DECK ) return( NOMORE );
return( deck[nextcd++] );
}
error( s ) char *s; {
fprintf( stderr, "error: " );
fprintf( stderr, s );
exit( 1 );
}
empty( h ) HAND h; {
register i;
for( i=1; i<=CTYPE; ++i ){
if( h[i] != 0 && h[i] != 4 ) return( 0 );
}
return( i );
}
mark( cd, hand ) HAND hand; {
if( cd != NOMORE ){
++hand[cd];
if( hand[cd] > 4 ){
error( "mark overflow" );
}
}
return( cd );
}
deal( hand, n ) HAND hand; {
while( n-- ){
if( mark( hand, draw() ) == NOMORE ) error( "deck exhausted" );
}
}
char *cname[] {
"NOMORE!!!",
"A",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K",
};
stats(){
register i, ct, b;
if( proflag ) printf( "Pro level\n" );
b = ct = 0;
for( i=1; i<=CTYPE; ++i ){
if( myhand[i] == 4 ) ++b;
else ct += myhand[i];
}
if( b ){
printf( "My books: " );
for( i=1; i<=CTYPE; ++i ){
if( myhand[i] == 4 ) printf( "%s ", cname[i] );
}
printf( "\n" );
}
printf( "%d cards in my hand, %d in the pool\n", ct, DECK-nextcd );
printf( "You ask me for: " );
}
phand( h ) HAND h; {
register i, j;
j = 0;
for( i = 1; i<= CTYPE; ++i ){
if( h[i] == 4 ) {
++j;
continue;
}
if( h[i] ){
register k;
k = h[i];
while( k-- ) printf( "%s ", cname[i] );
}
}
if( j ){
printf( "+ Books of " );
for( i=1; i<=CTYPE; ++i ){
if( h[i] == 4 ) printf( "%s ", cname[i] );
}
}
printf( "\n" );
}
main( argc, argv ) char * argv[]; {
/* initialize shuffling, ask for instructions, play game, die */
register c;
if( argc > 1 && argv[1][0] == '-' ){
while( argv[1][0] == '-' ) { ++argv[1]; ++debug; }
argv++;
argc--;
}
srand( getpid() );
printf( "instructions?\n" );
if( (c=getchar()) != '\n' ){
if( c != 'n' ) instruct();
while( getchar() != '\n' );
}
game();
}
/* print instructions */
char *inst[] {
"`Go Fish' is a childrens' card game.",
"The Object is to accumulate `books' of 4 cards",
"with the same face value.",
"The players alternate turns; each turn begins with one",
"player selecting a card from his hand, and asking the",
"other player for all cards of that face value.",
"If the other player has one or more cards of that face value",
"in his hand, he gives them to the first player, and the",
"first player makes another request.",
"Eventually, the first player asks for a card which",
"is not in the second player's hand: he replies `GO FISH!'",
"The first player then draws a card from the `pool' of",
"undealt cards. If this is the card he had last requested, he",
"draws again.",
"When a book is made, either through drawing or requesting,",
"the cards are laid down and no further action takes",
"place with that face value.",
"To play the computer, simply make guesses by typing",
"a, 2, 3, 4, 5, 6, 7, 8, 9, 10, j, q, or k when asked.",
"Hitting return gives you information about the size of",
"my hand and the pool, and tells you about my books.",
"Saying `p' as a first guess puts you into `pro' level;",
"The default is pretty dumb!",
"Good Luck!",
"",
};
instruct(){
register char **cpp;
printf( "\n" );
for( cpp = inst; **cpp != '\0'; ++cpp ){
printf( "%s\n", *cpp );
}
}
game(){
shuffle();
deal( myhand, 7 );
deal( yourhand, 7 );
start( myhand );
for(;;){
register g;
/* you make repeated guesses */
for(;;) {
printf( "your hand is: " );
phand( yourhand );
printf( "you ask me for: " );
if( !move( yourhand, myhand, g=guess(), 0 ) ) break;
printf( "Guess again\n" );
}
/* I make repeated guesses */
for(;;) {
if( (g=myguess()) != NOMORE ){
printf( "I ask you for: %s\n", cname[g] );
}
if( !move( myhand, yourhand, g, 1 ) ) break;
printf( "I get another guess\n" );
}
}
}
/* reflect the effect of a move on the hands */
move( hs, ht, g, v ) HAND hs, ht; {
/* hand hs has made a guess, g, directed towards ht */
/* v on indicates that the guess was made by the machine */
register d;
char *sp, *tp;
sp = tp = "I";
if( v ) tp = "You";
else sp = "You";
if( g == NOMORE ){
d = draw();
if( d == NOMORE ) score();
else {
printf( "Empty Hand\n" );
if( !v ) printf( "You draw %s\n", cname[d] );
mark( hs, d );
}
return( 0 );
}
if( !v ) heguessed( g );
if( hs[g] == 0 ){
if( v ) error( "Rotten Guess" );
printf( "You don't have any %s's\n", cname[g] );
return(1);
}
if( ht[g] ){ /* successful guess */
printf( "%s have %d %s%s\n", tp, ht[g], cname[g], ht[g]>1?"'s":"" );
hs[g] += ht[g];
ht[g] = 0;
if( hs[g] == 4 ) madebook(g);
return(1);
}
/* GO FISH! */
printf( "%s say \"GO FISH!\"\n", tp );
newdraw:
d = draw();
if( d == NOMORE ) {
printf( "No more cards\n" );
return(0);
}
mark( hs, d );
if( !v ) printf( "You draw %s\n", cname[d] );
if( hs[d] == 4 ) madebook(d);
if( d == g ){
printf( "%s drew the guess, so draw again\n", sp );
if( !v ) hedrew( d );
goto newdraw;
}
return( 0 );
}
madebook( x ){
printf( "Made a book of %s's\n", cname[x] );
}
score(){
register my, your, i;
my = your = 0;
printf( "The game is over.\nMy books: " );
for( i=1; i<=CTYPE;++i ){
if( myhand[i] == 4 ){
++my;
printf( "%s ", cname[i] );
}
}
printf( "\nYour books: " );
for( i=1; i<=CTYPE;++i ){
if( yourhand[i] == 4 ){
++your;
printf( "%s ", cname[i] );
}
}
printf( "\n\nI have %d, you have %d\n", my, your );
printf( "\n%s win!!!\n", my>your?"I":"You" );
exit(0);
}
# define G(x) { if(go) goto err; else go = x; }
guess(){
/* get the guess from the tty and return it... */
register g, go;
go = 0;
for(;;) {
switch( g = getchar() ){
case 'p':
case 'P':
++proflag;
continue;
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
G(g-'0');
continue;
case 'a':
case 'A':
G(1);
continue;
case '1':
G(10);
continue;
case '0':
if( go != 10 ) goto err;
continue;
case 'J':
case 'j':
G(11);
continue;
case 'Q':
case 'q':
G(12);
continue;
case 'K':
case 'k':
G(13);
continue;
case '\n':
if( empty( yourhand ) ) return( NOMORE );
if( go == 0 ){
stats();
continue;
}
return( go );
case ' ':
case '\t':
continue;
default:
err:
while( g != '\n' ) g = getchar();
printf( "what?\n" );
continue;
}
}
}
/* the program's strategy appears from here to the end */
char try[100];
char ntry;
char haveguessed[CTSIZ];
char hehas[CTSIZ];
start( h ) HAND h; {
;
}
hedrew( d ){
++hehas[d];
}
heguessed( d ){
++hehas[d];
}
myguess(){
register i, lg, t;
if( empty( myhand ) ) return( NOMORE );
/* make a list of those things which i have */
/* leave off any which are books */
/* if something is found that he has, guess it! */
ntry = 0;
for( i=1; i<=CTYPE; ++i ){
if( myhand[i] == 0 || myhand[i] == 4 ) continue;
try[ntry++] = i;
}
if( !proflag ) goto random;
/* get ones he has, if any */
for( i=0; i<ntry; ++i ){
if( hehas[try[i]] ) {
i = try[i];
goto gotguess;
}
}
/* is there one that has never been guessed; if so, guess it */
lg = 101;
for( i=0; i<ntry; ++i ){
if( haveguessed[try[i]] < lg ) lg = haveguessed[try[i]];
}
/* remove all those not guessed longest ago */
t = 0;
for( i=0; i<ntry; ++i ){
if( haveguessed[try[i]] == lg ) try[t++] = try[i];
}
ntry = t;
if( t <= 0 ) error( "bad guessing loop" );
random:
i = choose( try, ntry ); /* make a random choice */
gotguess: /* do bookkeeping */
hehas[i] = 0; /* he won't anymore! */
for( t=1; t<=CTYPE; ++t ){
if( haveguessed[t] ) --haveguessed[t];
}
haveguessed[i] = 100; /* will have guessed it */
return(i);
}

31
v7/games/fortune.c#b00008 Normal file
View File

@ -0,0 +1,31 @@
#include <stdio.h>
char line[500];
char bline[500];
main()
{
double p;
register char * l;
long t;
FILE *f;
f = fopen("/usr/local/games/lib/fortunes", "r");
if (f == NULL) {
printf("Memory fault -- core dumped\n");
exit(1);
}
time(&t);
srand(getpid() + (int)((t>>16) + t));
p = 1.;
for(;;) {
l = fgets(line, 500, f);
if(l == NULL)
break;
if(rand() < 32768./p)
strcpy(bline, line);
p += 1.;
}
fputs(bline, stdout);
return(0);
}

View File

@ -0,0 +1,31 @@
#include <stdio.h>
char line[500];
char bline[500];
main()
{
double p;
register char * l;
long t;
FILE *f;
f = fopen("/usr/games/lib/fortunes", "r");
if (f == NULL) {
printf("Memory fault -- core dumped\n");
exit(1);
}
time(&t);
srand(getpid() + (int)((t>>16) + t));
p = 1.;
for(;;) {
l = fgets(line, 500, f);
if(l == NULL)
break;
if(rand() < 32768./p)
strcpy(bline, line);
p += 1.;
}
fputs(bline, stdout);
return(0);
}

161
v7/games/hangman.c#b00008 Normal file
View File

@ -0,0 +1,161 @@
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define DICT "/usr/local/dict/words"
#define EDICT "/crp/dict/web2"
#define MAXERR 7
#define MINSCORE 0
#define MINLEN 7
char *dictfile;
int alive,lost;
FILE *dict;
long int dictlen;
float errors=0, words=0;
int setup(void);
int startnew(void);
int stateout(void);
int getguess(void);
int wordout(void);
int youwon(void);
int fatal(char *s);
double frand(void);
int getword(void);
int pscore(void);
int main(int argc, char **argv)
{
if(argc==1) dictfile=DICT;
else if(*argv[1]=='-') dictfile=EDICT;
else dictfile=argv[1];
setup();
for(;;)
{ startnew();
while(alive>0)
{ stateout();
getguess();
}
words=words+1;
if(lost) wordout();
else youwon();
}
}
int setup(void)
{ int tvec[2];
struct stat statb;
time((time_t*)tvec);
srand(tvec[1]+tvec[2]);
if((dict=fopen(dictfile,"r"))==NULL) fatal("no dictionary");
if(stat(dictfile,&statb)<0) fatal("can't stat");
dictlen=statb.st_size;
}
double frand(void)
{
return(rand()/32768.);
}
char word[26],alph[26],realword[26];
int startnew(void)
{ int i;
long int pos;
char buf[128];
for(i=0;i<26;i++) word[i]=alph[i]=realword[i]=0;
pos=frand()*dictlen;
fseek(dict,pos,0);
fscanf(dict,"%s\n",buf);
getword();
alive=MAXERR;
lost=0;
}
int stateout(void)
{ int i;
printf("guesses: ");
for(i=0;i<26;i++)
if(alph[i]!=0) putchar(alph[i]);
printf(" word: %s ",word);
printf("errors: %d/%d\n",MAXERR-alive,MAXERR);
}
int getguess(void)
{ char gbuf[128],c;
int ok=0,i;
loop:
printf("guess: ");
if(gets(gbuf)==NULL)
{ putchar('\n');
exit(0);
}
if((c=gbuf[0])<'a' || c>'z')
{ printf("lower case\n");
goto loop;
}
if(alph[c-'a']!=0)
{ printf("you guessed that\n");
goto loop;
}
else alph[c-'a']=c;
for(i=0;realword[i]!=0;i++)
if(realword[i]==c)
{ word[i]=c;
ok=1;
}
if(ok==0)
{ alive--;
errors=errors+1;
if(alive<=0) lost=1;
return;
}
for(i=0;word[i]!=0;i++)
if(word[i]=='.') return;
alive=0;
lost=0;
return;
}
int wordout(void)
{
errors=errors+2;
printf("the answer was %s, you blew it\n",realword);
}
int youwon(void)
{
printf("you win, the word is %s\n",realword);
}
int fatal(char *s)
{
fprintf(stderr,"%s\n",s);
exit(1);
}
int getword(void)
{ char wbuf[128],c;
int i,j;
loop:
if(fscanf(dict,"%s\n",wbuf)==EOF)
{ fseek(dict,0L,0);
goto loop;
}
if((c=wbuf[0])>'z' || c<'a') goto loop;
for(i=j=0;wbuf[j]!=0;i++,j++)
{ if(wbuf[j]=='-') j++;
wbuf[i]=wbuf[j];
}
wbuf[i]=0;
if(i<MINLEN) goto loop;
for(j=0;j<i;j++)
if((c=wbuf[j])<'a' || c>'z') goto loop;
pscore();
strcpy(realword,wbuf);
for(j=0;j<i;word[j++]='.');
}
long int freq[] =
{ 42066, 9228, 24412, 14500, 55162,
6098, 11992, 12648, 48241, 639,
2944, 33351, 15545, 35618, 36211,
16033, 937, 36686, 34957, 37544,
17621, 5453, 3028, 1556, 12875,
1743
};
int pscore(void)
{
if(words!=0) printf("(%4.2f/%.0f) ",errors/words,words);
}

View File

@ -0,0 +1,146 @@
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#define DICT "/usr/dict/words"
#define EDICT "/crp/dict/web2"
#define MAXERR 7
#define MINSCORE 0
#define MINLEN 7
char *dictfile;
int alive,lost;
FILE *dict;
long int dictlen;
float errors=0, words=0;
main(argc,argv) char **argv;
{
if(argc==1) dictfile=DICT;
else if(*argv[1]=='-') dictfile=EDICT;
else dictfile=argv[1];
setup();
for(;;)
{ startnew();
while(alive>0)
{ stateout();
getguess();
}
words=words+1;
if(lost) wordout();
else youwon();
}
}
setup()
{ int tvec[2];
struct stat statb;
time(tvec);
srand(tvec[1]+tvec[2]);
if((dict=fopen(dictfile,"r"))==NULL) fatal("no dictionary");
if(stat(dictfile,&statb)<0) fatal("can't stat");
dictlen=statb.st_size;
}
double frand()
{
return(rand()/32768.);
}
char word[26],alph[26],realword[26];
startnew()
{ int i;
long int pos;
char buf[128];
for(i=0;i<26;i++) word[i]=alph[i]=realword[i]=0;
pos=frand()*dictlen;
fseek(dict,pos,0);
fscanf(dict,"%s\n",buf);
getword();
alive=MAXERR;
lost=0;
}
stateout()
{ int i;
printf("guesses: ");
for(i=0;i<26;i++)
if(alph[i]!=0) putchar(alph[i]);
printf(" word: %s ",word);
printf("errors: %d/%d\n",MAXERR-alive,MAXERR);
}
getguess()
{ char gbuf[128],c;
int ok=0,i;
loop:
printf("guess: ");
if(gets(gbuf)==NULL)
{ putchar('\n');
exit(0);
}
if((c=gbuf[0])<'a' || c>'z')
{ printf("lower case\n");
goto loop;
}
if(alph[c-'a']!=0)
{ printf("you guessed that\n");
goto loop;
}
else alph[c-'a']=c;
for(i=0;realword[i]!=0;i++)
if(realword[i]==c)
{ word[i]=c;
ok=1;
}
if(ok==0)
{ alive--;
errors=errors+1;
if(alive<=0) lost=1;
return;
}
for(i=0;word[i]!=0;i++)
if(word[i]=='.') return;
alive=0;
lost=0;
return;
}
wordout()
{
errors=errors+2;
printf("the answer was %s, you blew it\n",realword);
}
youwon()
{
printf("you win, the word is %s\n",realword);
}
fatal(s) char *s;
{
fprintf(stderr,"%s\n",s);
exit(1);
}
getword()
{ char wbuf[128],c;
int i,j;
loop:
if(fscanf(dict,"%s\n",wbuf)==EOF)
{ fseek(dict,0L,0);
goto loop;
}
if((c=wbuf[0])>'z' || c<'a') goto loop;
for(i=j=0;wbuf[j]!=0;i++,j++)
{ if(wbuf[j]=='-') j++;
wbuf[i]=wbuf[j];
}
wbuf[i]=0;
if(i<MINLEN) goto loop;
for(j=0;j<i;j++)
if((c=wbuf[j])<'a' || c>'z') goto loop;
pscore();
strcpy(realword,wbuf);
for(j=0;j<i;word[j++]='.');
}
long int freq[]
{ 42066, 9228, 24412, 14500, 55162,
6098, 11992, 12648, 48241, 639,
2944, 33351, 15545, 35618, 36211,
16033, 937, 36686, 34957, 37544,
17621, 5453, 3028, 1556, 12875,
1743
};
pscore()
{
if(words!=0) printf("(%4.2f/%.0f) ",errors/words,words);
}

View File

@ -0,0 +1,141 @@
Some men are discovered; others are found out.
Words must be weighed, not counted.
By failing to prepare, you are preparing to fail.
He who spends a storm beneath a tree, takes life with a grain of TNT.
You attempt things that you do not even plan because of your extreme stupidity.
Take care of the luxuries and the necessities will take care of themselves.
Words are the voice of the heart.
Your mind understands what you have been taught; your heart, what is true.
A king's castle is his home.
He who has a shady past knows that nice guys finish last.
The universe is laughing behind your back.
The best prophet of the future is the past.
It is a poor judge who cannot award a prize.
Even the boldest zebra fears the hungry lion.
Money will say more in one moment than the most eloquent lover can in years.
Money may buy friendship but money can not buy love.
Might as well be frank, monsieur. It would take a miracle to get you out of Casablanca.
Creditors have much better memories than debtors.
Many pages make a thick book.
Every purchase has its price.
Do not underestimate the power of the Force.
You will step on the night soil of many countries.
Mind your own business, Spock. I'm sick of your halfbreed interference.
He who invents adages for others to peruse takes along rowboat when going on cruise.
Of all forms of caution, caution in love is the most fatal.
If you suspect a man, don't employ him.
The Tree of Learning bears the noblest fruit, but noble fruit tastes bad.
Stop searching forever. Happiness is unattainable.
A man who fishes for marlin in ponds will put his money in Etruscan bonds.
A good memory does not equal pale ink.
How sharper than a hound's tooth it is to have a thankless serpent.
You dialed 5483
It's later than you think.
Mistakes are oft the stepping stones to failure.
It's not reality that's important, but how you perceive things.
Promptness is its own reward, if one lives by the clock instead of the sword.
Like winter snow on summer lawn, time past is time gone.
Far duller than a serpent's tooth it is to spend a quiet youth.
Let not the sands of time get in your lunch.
The attacker must vanquish; the defender need only survive.
Standing on head makes smile of frown, but rest of face also upside down.
Deprive a mirror of its silver and even the Czar won't see his face.
Man's horizons are bounded by his vision.
To criticize the incompetent is easy; it is more difficult to criticize the competent.
He who has imagination without learning has wings but no feet.
Men seldom show dimples to girls who have pimples.
Troglodytism does not necessarily imply a low cultural level.
You cannot kill time without injuring eternity.
As goatherd learns his trade by goat, so writer learns his trade by wrote.
One man tells a falsehood, a hundred repeat it as true.
Crazee Edeee, his prices are INSANE!!!
It is better to wear out than to rust out.
When the wind is great, bow before it; when the wind is heavy, yield to it.
The wise shepherd never trusts his flock to a smiling wolf.
It is the wise bird who builds his nest in a tree.
How you look depends on where you go.
A plucked goose doesn't lay golden eggs.
A man who turns green has eschewed protein.
Put not your trust in money, but put your money in trust.
Even a hawk is an eagle among crows.
Even the smallest candle burns brighter in the dark.
People who take cat naps don't usually sleep in a cat's cradle.
A truly wise man never plays leapfrog with a Unicorn.
Do not clog intellect's sluices with bits of knowledge of questionable uses.
Let him who takes the Plunge remember to return it by Tuesday.
Try to divide your time evenly to keep others happy.
You have mail.
His heart was yours from the first moment that you met.
Sin has many tools, but a lie is the handle which fits them all.
Let a fool hold his tongue and he will pass for a sage.
With clothes the new are best, with friends the old are best.
He is truly wise who gains wisdom from another's mishap.
Beware of a dark-haired man with a loud tie.
Today is the last day of your life so far.
Flee at once, all is discovered.
Man who falls in vat of molten optical glass makes spectacle of self.
Go directly to jail. Do not pass Go, do not collect $200.
For a good time, call 8367-3100.
Those who can, do; those who can't, simulate.
Those who can, do; those who can't, write. Those who can't write work for the Bell Labs Record.
God does not play dice.
This fortune is inoperative. Please try another.
Laugh, and the world ignores you. Crying doesn't help either.
No amount of genius can overcome a preoccupation with detail.
You will feel hungry again in another hour.
You now have Asian Flu.
God made the integers; all else is the work of Man.
Disk crisis, please clean up!
You auto buy now.
Many are called, few are chosen. Fewer still get to do the choosing.
Try the Moo Shu Pork. It is especially good today.
Many are cold, but few are frozen.
The early worm gets the bird.
He who hesitates is sometimes saved.
Time is nature's way of making sure that everything doesn't happen at once.
The future isn't what it used to be. (It never was.)
Can't open /usr/lib/fortunes.
If God had wanted you to go around nude, He would have given you bigger hands.
It is better to have loved and lost than just to have lost.
A journey of a thousand miles begins with a cash advance from Sam.
Disk crunch - please clean up.
Center meeting at 4pm in 2C-543
I will never lie to you.
Spock: We suffered 23 casualties in that attack, Captain.
Your computer account is overdrawn. Please reauthorize.
1 bulls, 3 cows
It's hard to get ivory in Africa, but in Alabama the Tuscaloosa.
Waste not, get your budget cut next year.
Old MacDonald had an agricultural real estate tax abatement.
Snow Day - stay home.
Save gas, don't eat beans.
All that glitters has a high refractive index.
Ignore previous fortune.
When in doubt, lead trump.
23. ... r-q1
unix soit qui mal y pense
Even a cabbage may look at a king.
Honi soit la vache qui rit.
No directory
Don't eat yellow snow.
One Bell System - it works.
One Bell System - it sometimes works.
* UNIX is a Trademark of Bell Laboratories.
chess tonight
External Security:
Peters hungry, time to eat lunch.
MOUNT TAPE U1439 ON B3, NO RING
A foolish consistency is the hobgoblin of little minds.
IOT trap -- core dumped
IOT trap -- mos dumped
/usr/news/gotcha
Rotten wood can not be carved - Confucius (Analects, Book 5, Ch. 9)
System going down at 1:45 this afternoon for disk crashing.
: is not an identifier
Quantity is no substitute for quality, but its the only one we've got.
Those who can do, those who can't, write.
The more things change, the more they'll never be the same again.
New crypt. See /usr/news/crypt.
You might have mail.
You can't go home again, unless you set $HOME
You are in a maze of twisty little passages, all alike.

482
v7/games/quiz.c#b00008 Normal file
View File

@ -0,0 +1,482 @@
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define NF 10
#define NL 300
#define NC 200
#define SL 100
#define NA 10
int tflag;
int xx[NL];
char score[NL];
int rights;
int wrongs;
int guesses;
FILE *input;
int nl = 0;
int na = NA;
int inc;
int ptr = 0;
int nc = 0;
char line[150];
char response[100];
char *tmp[NF];
int _select[NF];
int cmp(char *u, char *v);
int disj(int s);
int eat(int s, char c);
int string(int s);
int fold(int c);
int publish(char *t);
int pub1(int s);
int _segment(char *u, char *w[]);
int perm(char *u[], int m, char *v[], int n, int p[]);
int find(char *u[], int m);
int readindex(void);
int talloc(void);
int badinfo(void);
int next(void);
void done(int, int);
int instruct(char *info);
int dunno(void);
int query(char *r);
int readline(void)
{
char *t;
register c;
loop:
for (t=line; c=getc(input), *t=c, c!=EOF; t++) {
nc++;
if(*t==' '&&(t==line||t[-1]==' '))
t--;
if(*t=='\n') {
if(t[-1]=='\\') /*inexact test*/
continue;
while(t>line&&t[-1]==' ')
*--t = '\n';
*++t = 0;
return(1);
}
if(t-line>=NC) {
printf("Too hard for me\n");
do {
*line = getc(input);
if(*line==0377)
return(0);
} while(*line!='\n');
goto loop;
}
}
return(0);
}
char *eu;
char *ev;
int cmp(char *u, char *v)
{
int x;
eu = u;
ev = v;
x = disj(1);
if(x!=1)
return(x);
return(eat(1,0));
}
int disj(int s)
{
int t, x;
char *u;
u = eu;
t = 0;
for(;;) {
x = string(s);
if(x>1)
return(x);
switch(*ev) {
case 0:
case ']':
case '}':
return(t|x&s);
case '|':
ev++;
t |= s;
s = 0;
continue;
}
if(s) eu = u;
if(string(0)>1)
return(2);
switch(*ev) {
case 0:
case ']':
return(0);
case '}':
return(1);
case '|':
ev++;
continue;
default:
return(2);
}
}
}
int string(int s)
{
int x;
for(;;) {
switch(*ev) {
case 0:
case '|':
case ']':
case '}':
return(1);
case '\\':
ev++;
if(*ev==0)
return(2);
if(*ev=='\n') {
ev++;
continue;
}
default:
if(eat(s,*ev)==1)
continue;
return(0);
case '[':
ev++;
x = disj(s);
if(*ev!=']' || x>1)
return(2);
ev++;
if(s==0)
continue;
if(x==0)
return(0);
continue;
case '{':
ev++;
x = disj(s);
if(*ev!='}'||x>1)
return(2);
ev++;
continue;
}
}
}
int eat(int s, char c)
{
if(*ev!=c)
return(2);
if(s==0) {
ev++;
return(1);
}
if(fold(*eu)!=fold(c))
return(0);
eu++;
ev++;
return(1);
}
int fold(int c)
{
if(c<'A'||c>'Z')
return(c);
return(c|040);
}
int publish(char *t)
{
ev = t;
pub1(1);
}
int pub1(int s)
{
for(;;ev++){
switch(*ev) {
case '|':
s = 0;
continue;
case ']':
case '}':
case 0:
return;
case '[':
case '{':
ev++;
pub1(s);
continue;
case '\\':
if(*++ev=='\n')
continue;
default:
if(s)
putchar(*ev);
}
}
}
int _segment(char *u, char *w[])
{
char *s;
int i;
char *t;
s = u;
for(i=0;i<NF;i++) {
u = s;
t = w[i];
while(*s!=':'&&*s!='\n'&&s-u<SL) {
if(*s=='\\') {
if(s[1] == '\n') {
s += 2;
continue;
}
*t++ = *s++;
}
*t++ = *s++;
}
while(*s!=':'&&*s!='\n')
s++;
*t = 0;
if(*s++=='\n') {
return(i+1);
}
}
printf("Too many facts about one thing\n");
return(0);
}
int perm(char *u[], int m, char *v[], int n, int p[])
{
int i, j;
int x;
for(i=0;i<m;i++) {
for(j=0;j<n;j++) {
x = cmp(u[i],v[j]);
if(x>1) badinfo();
if(x==0)
continue;
p[i] = j;
goto uloop;
}
return(0);
uloop: ;
}
return(1);
}
int find(char *u[], int m)
{
int n;
while(readline()){
n = _segment(line,tmp);
if(perm(u,m,tmp+1,n-1,_select))
return(1);
}
return(0);
}
int readindex(void)
{
xx[0] = nc = 0;
while(readline()) {
xx[++nl] = nc;
if(nl>=NL) {
printf("I've forgotten some of it;\n");
printf("I remember %d items.\n", nl);
break;
}
}
}
int talloc(void)
{
int i;
for(i=0;i<NF;i++)
tmp[i] = malloc(SL);
}
int main(int argc, char *argv[])
{
register j;
int i;
int x;
int z;
char *info;
long tm;
int count;
info = "/usr/local/games/quiz.k/index";
time(&tm);
inc = (int)tm&077774|01;
loop:
if(argc>1&&*argv[1]=='-') {
switch(argv[1][1]) {
case 'i':
if(argc>2)
info = argv[2];
argc -= 2;
argv += 2;
goto loop;
case 't':
tflag = 1;
argc--;
argv++;
goto loop;
}
}
input = fopen(info,"r");
if(input==NULL) {
printf("No info\n");
exit(0);
}
talloc();
if(argc<=2)
instruct(info);
signal(SIGINT, done);
argv[argc] = 0;
if(find(&argv[1],argc-1)==0)
dunno();
fclose(input);
input = fopen(tmp[0],"r");
if(input==NULL)
dunno();
readindex();
if(!tflag || na>nl)
na = nl;
/* stdout->_flag |= _IONBF; */
for(;;) {
i = next();
fseek(input,xx[i]+0L,0);
z = xx[i+1]-xx[i];
for(j=0;j<z;j++)
line[j] = getc(input);
_segment(line,tmp);
if(*tmp[_select[0]] == '\0' || *tmp[_select[1]] == '\0') {
score[i] = 1;
continue;
}
publish(tmp[_select[0]]);
printf("\n");
for(count=0;;count++) {
if(query(response)==0) {
publish(tmp[_select[1]]);
printf("\n");
if(count==0) wrongs++;
score[i] = tflag?-1:1;
break;
}
x = cmp(response,tmp[_select[1]]);
if(x>1) badinfo();
if(x==1) {
printf("Right!\n");
if(count==0) rights++;
if(++score[i]>=1 && na<nl)
na++;
break;
}
printf("What?\n");
if(count==0) wrongs++;
score[i] = tflag?-1:1;
}
guesses += count;
}
}
int query(char *r)
{
char *t;
for(t=r;;t++) {
if(read(0,t,1)==0)
done(0,0);
if(*t==' '&&(t==r||t[-1]==' '))
t--;
if(*t=='\n') {
while(t>r&&t[-1]==' ')
*--t = '\n';
break;
}
}
*t = 0;
return(t-r);
}
int next(void)
{
int flag;
inc = inc*3125&077777;
ptr = (inc>>2)%na;
flag = 0;
while(score[ptr]>0)
if(++ptr>=na) {
ptr = 0;
if(flag) done(0,0);
flag = 1;
}
return(ptr);
}
void done(int x, int y)
{
printf("\nRights %d, wrongs %d, ", rights, wrongs);
if(guesses)
printf("extra guesses %d, ", guesses);
printf("score %d%%\n",100*rights/(rights+wrongs));
exit(0);
}
int instruct(char *info)
{
int i, n;
printf("Subjects:\n\n");
while(readline()) {
printf("-");
n = _segment(line,tmp);
for(i=1;i<n;i++) {
printf(" ");
publish(tmp[i]);
}
printf("\n");
}
printf("\n");
input = fopen(info,"r");
if(input==NULL)
abort();
readline();
_segment(line,tmp);
printf("For example,\n");
printf(" quiz ");
publish(tmp[1]);
printf(" ");
publish(tmp[2]);
printf("\nasks you a ");
publish(tmp[1]);
printf(" and you answer the ");
publish(tmp[2]);
printf("\n quiz ");
publish(tmp[2]);
printf(" ");
publish(tmp[1]);
printf("\nworks the other way around\n");
printf("\nType empty line to get correct answer.\n");
exit(0);
}
int badinfo(void){
printf("Bad info %s\n",line);
}
int dunno(void)
{
printf("I don't know about that\n");
exit(0);
}

473
v7/games/quiz.c.orig#b00008 Normal file
View File

@ -0,0 +1,473 @@
#include <stdio.h>
#include <signal.h>
#define NF 10
#define NL 300
#define NC 200
#define SL 100
#define NA 10
int tflag;
int xx[NL];
char score[NL];
int rights;
int wrongs;
int guesses;
FILE *input;
int nl = 0;
int na = NA;
int inc;
int ptr = 0;
int nc = 0;
char line[150];
char response[100];
char *tmp[NF];
int select[NF];
char *malloc();
readline()
{
char *t;
register c;
loop:
for (t=line; c=getc(input), *t=c, c!=EOF; t++) {
nc++;
if(*t==' '&&(t==line||t[-1]==' '))
t--;
if(*t=='\n') {
if(t[-1]=='\\') /*inexact test*/
continue;
while(t>line&&t[-1]==' ')
*--t = '\n';
*++t = 0;
return(1);
}
if(t-line>=NC) {
printf("Too hard for me\n");
do {
*line = getc(input);
if(*line==0377)
return(0);
} while(*line!='\n');
goto loop;
}
}
return(0);
}
char *eu;
char *ev;
cmp(u,v)
char *u, *v;
{
int x;
eu = u;
ev = v;
x = disj(1);
if(x!=1)
return(x);
return(eat(1,0));
}
disj(s)
{
int t, x;
char *u;
u = eu;
t = 0;
for(;;) {
x = string(s);
if(x>1)
return(x);
switch(*ev) {
case 0:
case ']':
case '}':
return(t|x&s);
case '|':
ev++;
t |= s;
s = 0;
continue;
}
if(s) eu = u;
if(string(0)>1)
return(2);
switch(*ev) {
case 0:
case ']':
return(0);
case '}':
return(1);
case '|':
ev++;
continue;
default:
return(2);
}
}
}
string(s)
{
int x;
for(;;) {
switch(*ev) {
case 0:
case '|':
case ']':
case '}':
return(1);
case '\\':
ev++;
if(*ev==0)
return(2);
if(*ev=='\n') {
ev++;
continue;
}
default:
if(eat(s,*ev)==1)
continue;
return(0);
case '[':
ev++;
x = disj(s);
if(*ev!=']' || x>1)
return(2);
ev++;
if(s==0)
continue;
if(x==0)
return(0);
continue;
case '{':
ev++;
x = disj(s);
if(*ev!='}'||x>1)
return(2);
ev++;
continue;
}
}
}
eat(s,c)
char c;
{
if(*ev!=c)
return(2);
if(s==0) {
ev++;
return(1);
}
if(fold(*eu)!=fold(c))
return(0);
eu++;
ev++;
return(1);
}
fold(c)
char c;
{
if(c<'A'||c>'Z')
return(c);
return(c|040);
}
publish(t)
char *t;
{
ev = t;
pub1(1);
}
pub1(s)
{
for(;;ev++){
switch(*ev) {
case '|':
s = 0;
continue;
case ']':
case '}':
case 0:
return;
case '[':
case '{':
ev++;
pub1(s);
continue;
case '\\':
if(*++ev=='\n')
continue;
default:
if(s)
putchar(*ev);
}
}
}
segment(u,w)
char *u, *w[];
{
char *s;
int i;
char *t;
s = u;
for(i=0;i<NF;i++) {
u = s;
t = w[i];
while(*s!=':'&&*s!='\n'&&s-u<SL) {
if(*s=='\\') {
if(s[1] == '\n') {
s += 2;
continue;
}
*t++ = *s++;
}
*t++ = *s++;
}
while(*s!=':'&&*s!='\n')
s++;
*t = 0;
if(*s++=='\n') {
return(i+1);
}
}
printf("Too many facts about one thing\n");
return(0);
}
perm(u,m,v,n,p)
int p[];
char *u[], *v[];
{
int i, j;
int x;
for(i=0;i<m;i++) {
for(j=0;j<n;j++) {
x = cmp(u[i],v[j]);
if(x>1) badinfo();
if(x==0)
continue;
p[i] = j;
goto uloop;
}
return(0);
uloop: ;
}
return(1);
}
find(u,m)
char *u[];
{
int n;
while(readline()){
n = segment(line,tmp);
if(perm(u,m,tmp+1,n-1,select))
return(1);
}
return(0);
}
readindex()
{
xx[0] = nc = 0;
while(readline()) {
xx[++nl] = nc;
if(nl>=NL) {
printf("I've forgotten some of it;\n");
printf("I remember %d items.\n", nl);
break;
}
}
}
talloc()
{
int i;
for(i=0;i<NF;i++)
tmp[i] = malloc(SL);
}
main(argc,argv)
char *argv[];
{
register j;
int i;
int x;
int z;
char *info;
long tm;
extern done();
int count;
info = "/usr/games/quiz.k/index";
time(&tm);
inc = (int)tm&077774|01;
loop:
if(argc>1&&*argv[1]=='-') {
switch(argv[1][1]) {
case 'i':
if(argc>2)
info = argv[2];
argc -= 2;
argv += 2;
goto loop;
case 't':
tflag = 1;
argc--;
argv++;
goto loop;
}
}
input = fopen(info,"r");
if(input==NULL) {
printf("No info\n");
exit(0);
}
talloc();
if(argc<=2)
instruct(info);
signal(SIGINT, done);
argv[argc] = 0;
if(find(&argv[1],argc-1)==0)
dunno();
fclose(input);
input = fopen(tmp[0],"r");
if(input==NULL)
dunno();
readindex();
if(!tflag || na>nl)
na = nl;
stdout->_flag |= _IONBF;
for(;;) {
i = next();
fseek(input,xx[i]+0L,0);
z = xx[i+1]-xx[i];
for(j=0;j<z;j++)
line[j] = getc(input);
segment(line,tmp);
if(*tmp[select[0]] == '\0' || *tmp[select[1]] == '\0') {
score[i] = 1;
continue;
}
publish(tmp[select[0]]);
printf("\n");
for(count=0;;count++) {
if(query(response)==0) {
publish(tmp[select[1]]);
printf("\n");
if(count==0) wrongs++;
score[i] = tflag?-1:1;
break;
}
x = cmp(response,tmp[select[1]]);
if(x>1) badinfo();
if(x==1) {
printf("Right!\n");
if(count==0) rights++;
if(++score[i]>=1 && na<nl)
na++;
break;
}
printf("What?\n");
if(count==0) wrongs++;
score[i] = tflag?-1:1;
}
guesses += count;
}
}
query(r)
char *r;
{
char *t;
for(t=r;;t++) {
if(read(0,t,1)==0)
done();
if(*t==' '&&(t==r||t[-1]==' '))
t--;
if(*t=='\n') {
while(t>r&&t[-1]==' ')
*--t = '\n';
break;
}
}
*t = 0;
return(t-r);
}
next()
{
int flag;
inc = inc*3125&077777;
ptr = (inc>>2)%na;
flag = 0;
while(score[ptr]>0)
if(++ptr>=na) {
ptr = 0;
if(flag) done();
flag = 1;
}
return(ptr);
}
done()
{
printf("\nRights %d, wrongs %d, ", rights, wrongs);
if(guesses)
printf("extra guesses %d, ", guesses);
printf("score %d%%\n",100*rights/(rights+wrongs));
exit(0);
}
instruct(info)
char *info;
{
int i, n;
printf("Subjects:\n\n");
while(readline()) {
printf("-");
n = segment(line,tmp);
for(i=1;i<n;i++) {
printf(" ");
publish(tmp[i]);
}
printf("\n");
}
printf("\n");
input = fopen(info,"r");
if(input==NULL)
abort();
readline();
segment(line,tmp);
printf("For example,\n");
printf(" quiz ");
publish(tmp[1]);
printf(" ");
publish(tmp[2]);
printf("\nasks you a ");
publish(tmp[1]);
printf(" and you answer the ");
publish(tmp[2]);
printf("\n quiz ");
publish(tmp[2]);
printf(" ");
publish(tmp[1]);
printf("\nworks the other way around\n");
printf("\nType empty line to get correct answer.\n");
exit(0);
}
badinfo(){
printf("Bad info %s\n",line);
}
dunno()
{
printf("I don't know about that\n");
exit(0);
}

View File

@ -0,0 +1,44 @@
Algeria:Alg[iers|er]
Botswana:Gaberones
Burundi:Bujumbura
Cameroun:Yaound['e|e'|e]
Central Africa{n Rep{ublic}}:Bangui
Chad:Ndjamena
Congo:Brazzaville
Dahomey:Porto Novo
Ethiopia:Addis Ababa
Gabon:Libreville
Ghana:Accra
Guinea-Bissau:Bissau
Guinea:Conakry
Ivory Coast:Abidjan
Kenya:Nairobi
Lesotho:Maseru
Liberia:Monrovia
Libya:Tripoli|Al Bayda{'}
Malagasy{ Rep{ublic}}|Madagascar:Tananarive
Malawi:Zomba
Mali:Bamako
Mauritania:Nouakchott
Morocco:Rabat
Mo[z|,c|c,|c]ambique:Louren[,c|c,|c]o Marques
Namibia:Windhoek
Niger:Niamey
Nigeria:Lagos
Rhodesia:Salisbury
Rwanda:Kigali
Senegal:Dakar
Sierra Leone:Freetown
Somali{ Rep{ublic}}:Mogadis[cio|hu]
Sudan:Khartoum
Swaziland:Mbabane
Tanzania:Dar es Salaam
Togo:Lom['e|e'|e]
Tunisia:Tunis
Uganda:Kampala
United Arab Rep{ublic}|Egypt:Cairo
Upper Volta:Ouagadougou
Zambia:Lusaka
Za["i|i"|i]re:Kinshasa
{Rep{ublic} of }South Africa:Pretoria
{The }Gambia:Bathurst

View File

@ -0,0 +1,27 @@
Argentina:Buenos Aires
Bahamas:Nassau
Barbados:Bridgetown
Bolivia:La Paz|Sucre
Bra[z|s]il:Brasilia
Canada:Ottawa
Chile:Santiago
Colombia:Bogot['a|a'|a]
Costa Rica:San Jose
Cuba:Ha[v|b]ana
Dominican Republic:Santo Domingo
Ecuador:Quito
El Salvador:San Salvador
Guatemala:Guatemala
Guyana:Georgetown
Haiti:Port au Prince
Honduras:Tegucigalpa
Jamaica:Kingston
Mexico:Mexico
Nicaragua:Managua
Panama:Panama
Paraguay:Asunci['o|o'|o]n
Peru:Lima
Trinidad[ and Tobago|]:Port of Spain
United States|US{A}:Washington
Uruguay:Montevideo
Venezuela:Caracas

View File

@ -0,0 +1,124 @@
201:northern new jersey|NJ:newark
202:washington d c|DC:
203:connecticut|CT:
204:manitoba:
205:alabama|AL:
206:western washington state|WA:seattle
207:maine|ME:
208:idaho|ID:
209:central california|CA:fresno
212:new york city, new york|NY:
213:los angeles, california|CA:
214:northeastern texas|TX:dallas
215:southeastern pennsylvania|PA:philadelphia
216:northeastern ohio|OH:akron
217:central illinois|IL:springfield
218:northern minnesota|MN:duluth
219:northern indiana|IN:south bend
301:maryland|MD:
302:delaware|DE:
303:colorado|CO:
304:west virginia|WV:
305:southeastern florida|FL:miami
306:saskatchewan:
307:wyoming|WY:
308:western nebraska|NE:omaha
309:northwestern illinois|IL:peoria
312:chicago, illinois|IL:
313:eastern michigan|MI:detroit
314:southeastern missouri|MO:jefferson city
315:northern central new york|NY:syracuse
316:southern kansas|KS:wichita
317:central indiana|IN:indianapolis
318:western louisiana|LA:shreveport
319:eastern iowa|IA:cedar rapids
401:rhode island|RI:
402:eastern nebraska|NE:north platte
403:alberta:
404:northern georgia|GA:atlanta
405:western oklahoma|OK:oklahoma city
406:montana|MT:
408:central coastal california|CA:san jose
412:western pennsylvania|PA:pittsburgh
413:western massachusetts|MA:springfield
414:southeastern wisconsin|WI:milwaukee
415:san francisco, california|CA:
416:southern central ontario:toronto
417:southwestern missouri|MO:springfield
418:northeastern quebec:quebec
419:northwestern ohio|OH:toledo
501:arkansas|AR:
502:western kentucky|KY:louisville
503:oregon|OR:
504:eastern louisiana|LA:new orleans
505:new mexico|NM:
506:new brunswick:
507:southern minnesota|MN:rochester
509:eastern washington state|WA:spokane
512:southern texas|TX:austin
513:southwestern ohio|OH:dayton
514:southwestern quebec:montreal
515:central iowa|IA:des moines
516:long island, new york|NY:
517:central michigan|MI:lansing
518:northeastern new york|NY:albany
519:southwestern ontario:windsor
601:mississippi|MS:
602:arizona|AZ:
603:new hampshire|NH:
604:british columbia:
605:south dakota|SD:
606:eastern kentucky|KY:ashland
607:southern central new york|NY:ithaca, binghamton
608:southwestern wisconsin|WI:madison
609:southern new jersey|NJ:trenton
612:central minnesota|MN:minneapolis
613:southeastern ontario:ottawa
614:southeastern ohio|OH:columbus
615:eastern tennessee|TN:nashville
616:western michigan|MI:grand rapids
617:eastern massachusetts|MA:boston
618:southern illinois|IL:centralia
701:north dakota|ND:
702:nevada|NV:
703:western virginia|VA:arlington
704:western north carolina:charlotte
705:northeastern ontario:sault ste. marie
707:northwestern california|CA:santa rosa
709:newfoundland:
712:western iowa|IA:council bluffs
713:southeastern texas|TX:houston
714:southern california|CA:san diego
715:northern wisconsin|WI:superior
716:northern western new york|NY:buffalo, rochester
717:eastern pennsylvania|PA:wilkes-barre, scranton
801:utah|UT:
802:vermont|VT:
803:south carolina|SC:
804:eastern virginia|VA:richmond
805:southern central coastal california|CA:bakersfield
806:panhandle texas|TX:amarillo
807:western ontario:fort william
808:hawaii|HI:
809:bermuda, puerto rico, virgin islands, caribbean:
812:southern indiana|IN:evansville
813:southwestern florida|FL:st. petersburg
814:central pennsylvania|PA:erie
815:northeastern illinois|IL:rockford
816:northern missouri|MO:kansas city
817:northern central texas|TX:fort worth
819:northwestern quebec:trois rivieres
901:western tennessee|TN:memphis
902:nova scotia, prince edward island:
903:western mexico:mexicali
904:northern florida|FL:jacksonville
905:eastern mexico:mexico city
906:upper michigan|MI:escanaba
907:alaska|AK:
912:southern georgia|GA:savannah
913:northern kansas|KS:topeka
914:southern new york|NY:westchester county
915:western texas|TX:el paso
916:northeastern california|CA:sacramento
918:eastern oklahoma|OK:tulsa
919:eastern north carolina|NC:raleigh

View File

@ -0,0 +1,45 @@
63 - ... = 55:8
147 - 3 = ...:144
614 - 9 ...:605
465 - 7 = ...:458
563 - ... = 560:3
33 - 14 = ...:19
42 - ... = 37:5
264 - 3 = ...:261
763 - 8 = ...:755
375 - 6 = ...:369
736 - ... = 728:8
62 - 34 = ...:28
75 - 8 = ...:67
244 - ... = 230:14
478 - 19 = ...:459
78 - ... = 75:3
679 - 5 = ...:674
564 - 7 = ...:557
761 - 5 = ...:756
718 - ... = 716:2
56 - 18 = ...:38
65 - ... = 48:17
748 - 5 = ...:743
856 - 8 = ...:848
763 - 5 = ...:758
445 - ... = 436:9
94 - 55 = ...:39
42 - 9 = ...:33
483 - ... = 455:28
742 - ... = 714:28
84 - ... = 75:9
569 - 7 = ...:562
856 - 7 = ...:849
324 - 6 = ...:318
437 - ... = 432:5
84 - 56 = ...:28
81 - ... = 65:16
326 - 4 = ...:322
643 - 7 = ...:636
546 - 9 = ...:537
842 - ... = 835:7
53 - 39 = ...:14
63 - 48 = ...:15
57 - 38 = ...:19
52 - 26 = ...:26

View File

@ -0,0 +1,41 @@
Afghanistan:Kabul
Australia:Canberra
Bahrein:Manama
Bangladesh:Dacca
Bhutan:Thimbu
Burma:Rangoon
China:Peking
Cyprus:Nicosia
India:New Delhi
Indonesia:Djakarta
Iran:Tehran
Iraq:Baghdad
Israel:Jerusalem
Japan:Tokyo
Jordan:Amman
Khmer|Cambodia:P{h}nom Penh
Kuwait:Al-kuwait
Laos:Vientiane
Lebanon:Beirut
Malaysia:Kuala Lumpur
Maldive Islands:Male
Mongolia:Ulan Bator
Nepal:Katmandu
North Korea:P{'}yongyang
North Yemen:San{'}a
Oman:Muscat
Pakistan:Islamabad
Papua[-| ]New Guinea:Port Moresby
Phillipines:Quezon City
Qatar:Doha
Saudi Arabia:Riyadh|J{ei}ddah
Singapore:Singapore
South Korea:Seoul
South Yemen:Aden
Sri Lanka:Colombo
Syria:Damascus
Taiwan:Taipei
Thailand:Bangkok
Turkey:Ankara
United Arab Emirates:Abu Dhabi
Vietnam:Hanoi

View File

@ -0,0 +1,21 @@
cub:lion|tiger|bear
kitten:cat|fox|skunk|rabbit|bobcat|panther
gosling:goose
colt|foal:horse|donkey|zebra
puppy:dog
pup:seal|fox|beaver
duckling:duck
fawn:deer
piglet|shoat:pig
lamb:sheep
kid:goat|antelope
chick:chicken
tadpole|polliwog:frog|toad
joey:kangaroo
calf:cow|whale|moose|elephant|buffalo|giraffe
caterpillar:butterfly|moth
elver:eel
eaglet:eagle
owlet:owl
fingerling|fry:fish
nestling:bird

228
v7/games/quiz.k/bard#000000 Normal file
View File

@ -0,0 +1,228 @@
The quality of mercy is not strain['|e]d:\
It droppeth as the gentle rain from heaven:\
{The }Merchant{ of Venice{ IV-i}}:\
Portia
Friends{,} Romans{,} Countrymen:\
lend me your ears{;}:\
{Julius }Caesar{ III-ii}:\
{Mark }Antony
Neither a borrower nor a lender be:\
For loan oft loses both itself and friend{.}:\
Hamlet{ I-iii}:\
Polonius
To be{,} or not to be{\:}:\
that is the question{\:}:\
Hamlet{ III-i}:\
Hamlet
Alas{,} poor Yorick{!}:\
I knew him{,} Horatio{;}:\
Hamlet{ V-i}:\
Hamlet
Double{,} double toil and trouble{;}:\
Fire burn and cauldron bubble{.}:\
Macbeth{ IV-i}:\
Witch{es}
By the pricking of my thumbs{,}:\
Something wicked this way comes{.}:\
Macbeth{ IV-i}:\
{Second |2nd }Witch
Out, damned spot! out, I say!:\
:\
Macbeth{ V-i}:\
Lady Macbeth
Unbidden guests:\
Are often welcomest when they are gone{.}:\
{King }Henry VI{,} Part I{ I-ii}:\
She is a woman{,} therefore may be woo'd{;}:\
She is a woman{,} therefore may be [won|screw'd]{.}:\
Titus Andronicus{ II-i}:\
Demetrius
Such duty as the subject owes the prince{,}:\
Even such a woman oweth to her husband{.}:\
{The }Taming of the Shrew{ V-ii}:\
Kate
Who is Silvia{?} what is she{,}:\
That all our swains commend her{?}:\
{The }Two Gentlemen of Verona{ IV-ii}:\
Thurio
Tu-whit{,} tu-who[ - | |--]a merry note{,}:\
While greasy Joan doth keel the pot{.}:\
Love's Labo{u}r Lost{ V-ii}:\
Winter
My only love sprung from my only hate{!}:\
Too early seen unknown{,} and known too late{!}:\
Romeo{ and Juliet{ I-v}}:\
Juliet
But{,} soft{!} what light through yonder window breaks{?}:\
It is the east{,} and Juliet is the sun{!}:\
Romeo{ and Juliet{ II-ii}}:\
Romeo
What's in a name{?} That which we call a rose:\
By any other name would smell as sweet{.}:\
Romeo{ and Juliet{ II-ii}}:\
Juliet
Good night{,} good night{!} parting is such sweet sorrow{,}:\
That I shall say good night till it be morrow{.}:\
Romeo{ and Juliet{ II-ii}}:\
Juliet
A plague o['|n] both your houses{!}:\
They have made worms' meat of me{.}:\
Romeo{ and Juliet{ III-i}}:\
Mercutio
This royal throne of kings{,} this scepter['|e]d isle{,}:\
This earth of majesty{,} this seat of Mars{,}:\
{King }Richard II{ II-i}:\
John of Gaunt
Not all the water in a rough rude sea:\
Can wash the balm from an anointed king{.}:\
{King }Richard II{ III-ii}:\
{King }Richard II
I'll put a girdle round the earth:\
In forty minutes{.}:\
{A }Midsummer[-| ]Night's Dream{ II-i}:\
Puck
I can call spirits from the vasty deep{.}:\
Why{,} so can I{,} or so can any man{;}:\
{King }Henry IV{,} Part I{ II-iv}:\
There are more things in heaven and earth{,} Horatio{,}:\
Than are dream[t|ed] of in your philosophy{.}:\
Hamlet{ I-v}:\
Hamlet
The time is out of joint{;} O cursed spite{,}:\
That ever I was born to set it right{!}:\
Hamlet{ I-v}:\
Hamlet
Once more unto the breach{,} dear friends{,} once more{;}:\
Or close the wall up with our English dead{.}:\
{King }Henry V{ III-i}:\
{King }Henry V
Was ever woman in this humour woo['|e]d{?}:\
Was ever woman in this humour [won|screw'd]{?}:\
{King }Richard III{ I-ii}:\
{King }Richard III
Now is the winter of our discontent:\
Made glorious summer by this sun of York:\
{King }Richard III{ I-i}:\
{King }Richard III
There['s| is] a divinity that shapes our ends{,}:\
Rough[-| ]hew them how we will{.}:\
Hamlet{ V-ii}:\
Hamlet
There is a tide in the affairs of men:\
Which{,} taken at the flood{,} leads on to fortune{;}:\
{Julius }Caesar{ IV-iii}:\
Brutus
Never{,} never{,} never{,} never{,} never{.}:\
Pray you undo this button{.}{ Thank you{,} sir{.}}:\
{King }Lear{ V-iii}:\
{King }Lear
I grow{,} I prosper{\:}:\
Now{,} gods{,} stand up for bastards{!}:\
{King }Lear{ I-ii}:\
Edmund
The better part of valour is discretion{;}:\
in the which better part I have saved my life{.}:\
{King }Henry IV{,} Part I{ V-iv}:\
Falstaff
Asses are made to bear{,} and so are you{.}:\
Women are made to bear{,} and so are you{.}:\
{The }Taming of the Shrew{ II-i}:\
Full fathom five thy father lies{;}:\
Of his bones are coral made{;}:\
{The }Tempest{ I-ii}:\
Ariel
She lov['|e]d me for the dangers I had pass['|e]d{;}:\
And I lov['|e]d her that she did pity them{.}:\
Othello{ I-iii}:\
Othello
Uneasy lies the head that wears a crown{.}:\
Many good morrows to your Majesty{!}:\
{King }Henry IV{,} Part II{ III-i}:\
Mislike me not for my complexion{,}:\
The shadow['|e]d livery of the burnish['|e]d sun{.}:\
{The }Merchant{ of Venice{ II-i}}:\
Morocco
Cowards die many times before their deaths{;}:\
The valiant never taste of death but once{.}:\
{Julius }Caesar{ II-ii}:\
Caesar
O{h}{!|,} Pardon me{,} thou bleeding piece of earth{,}:\
That I am meek and gentle with these butchers{.}:\
{Julius }Caesar{ III-i}:\
{Mark }Antony
The play's the thing:\
Wherein I'll catch the conscience of the king{.}:\
Hamlet{ II-ii}:\
Hamlet
How sharper than a serpent's tooth it is:\
to have a thankless child{.}:\
{King }Lear{ I-iv}:\
{King }Lear
Had I but served my God with half the zeal I served my king:\
He would not in [mine|my] old age have left me naked to [mine|my] enemies{.}:\
{King }Henry VIII{ IV-ii}:\
{Cardinal }Wolsey
It seems she hangs upon the cheek of night:\
Like a rich jewel in an Ethiop's ear{.}:\
Romeo{ and Juliet{ I-v}}:\
Romeo
Where the bee sucks{,} there suck I{;}:\
In a cowslip's bell I lie{.}:\
{The }Tempest{ V-i}:\
Ariel
O brave new world{,}:\
That has such people [in't|in it]{!}:\
{The }Tempest{ V-i}:\
Miranda
Why{,} then the world's mine oyster{,}:\
Which I with sword will open{.}:\
{The }Merry Wives of Windsor{ II-ii}:\
Falstaff
A goodly apple rotten at the heart{\:}:\
O{h}{,} what a goodly outside falsehood hath{!|.}:\
{The }Merchant{ of Venice{ I-iii}}:\
Antonio
I never kill['|e]d a mouse{,} nor hurt a fly{;}:\
I trod upon a worm against my will{,}:\
Pericles{ IV-i}:\
Marina
Golden lads and girls all must{,}:\
Like chimney sweepers{,} come to dust{.}:\
Cymbeline{ IV-ii}:\
Guiderius
You blocks, you stones, you worse than senseless things!:\
O you hard hearts{,} you cruel men of Rome{.}:\
{Julius }Caesar{ I-i}:\
Marullus
A horse{!|,} a horse{!|,} my kingdom for a horse{!}:\
:\
{King }Richard III{ V-iv}:\
{King }Richard III
My salad days,:\
When I was green in judg{e}ment, cold in blood{,}:\
Antony [and|&] Cleopatra{ I-v}:\
Cleopatra
Age cannot wither her, nor custom stale:\
Her infinite variety{.}:\
Antony [and|&] Cleopatra{ II-iii}:\
Enobarbus
Give me some music\: music, moody food:\
Of us that trade in love{.}:\
Antony [and|&] Cleopatra{II-v}:\
Cleopatra
'Tis better playing with a lion's whelp,:\
Than with an old one dying{.}:\
Antony [and|&] Cleopatra:\
Enobarbus
The barge she sat in, like a burnished throne,:\
Burned on the water{.} The poop was burnished gold{;|.}:\
Antony [and|&] Cleopatra:\
Enobarbus
Done like a Frenchman - turn and turn again!:\
:\
{King }Henry VI{,} Part I{ III-iii}:\
{Joan }Pucelle|{Saint |St{.} }Joan{ of Arc}

View File

@ -0,0 +1,12 @@
rabbit:dragon
dragon:snake
snake:horse
horse:sheep
sheep:monkey
monkey:rooster
rooster:dog
dog:boar
boar:rat
rat:ox
ox:tiger
tiger:rabbit

View File

@ -0,0 +1,88 @@
ants:colony|hill
apes:shrewdness
asses:pace|bunch
badgers:cete
bass:shoal
bears:sloth
bees:swarm
birds:dissimulation
brats:passel
candidates:slate
caterpillars:army
cats:clowder
cattle:drove|herd
chickens:peep|flock
crows:murder
curs:cowardice
dogs:pack
doves:dule
ducks:[pad|ba]dling
earthquakes:swarm
eggs:clutch
elephants:herd
elk:gang
ferrets:business
finches:charm
firemen:brigade
fish:school
foxes:skulk
geese in flight:skein
geese on water:gaggle
goats:trip
hawks:cast
hens:brood
herons:siege
horses:haras|team
hounds:kennel
jellyfish:smack
kangaroos|monkeys:troop
kittens:kindle
lapwings:deceit
larks:exaltation|bevy
leopards:leap
lions:pride
locusts:plague
magpies:tidings
maidens|quail:bevy
martens:richness
men:band
moles:labor
monkeys|kangaroos:troop
mountains:range
mules:barren|baren
nightingales:watch
operating companies:at&t|bell system
owls:parliament
partridges|grouse:covey
peacocks:ostentation
pheasants:bouquet
plovers:congregation
ponies:string
prisoners:gang
pups:litter
quail|maidens:bevy
rabbits:nest
ravens:unkindness
rhinoceroses:crash
roebucks:bevy
rooks:building
seals:pod
sheep:flock
ships:fleet
snipe:walk|wisp
sparrows:host
squirrels:dray
starlings:murmuration
stars:constellation
storks:mustering
swallows:flight
teal:spring
toads:knot
turkeys:rafter
turtledoves:pitying
whales:gam|pod
witches:coven
wolves:route
woodcocks:fall
woodpeckers:descent
{wild }swine:sounder

84
v7/games/quiz.k/ed#000000 Normal file
View File

@ -0,0 +1,84 @@
prepare to add text at beginning of file:0a|1i
find name of file being edited:f
print last 3 lines of file:$-[2|-],$p
print previous line:[-|^]{p}|{.}-{1}{p}
print whole file:1,$p|g/[^|$]/p
delete this line and next:.{,|;}[{.}+{1}|.1]d
prepare to replace text from here to just before next "PP":\
.{,|;}/[PP|{^}\\.PP]/-{1}c
find next "1.2":/1\\.2/{p}
find next 2-or-more digit number:\
/\[[0|1]-9\]\[0-9\]/{p}
move rest of this paragraph (separated by "PP") to end of previous one:\
[.,|{.}+{1},|.1,]/[PP|{^}\\.PP]/-{1}m[??|?{^}{\\.}PP?]-{1}
print every "Oxygen" or "oxygen":[g|1,$g]/\[[Oo|oO]\]xygen/[p|.p]
change each "BTL" in file to "Bell Laboratories" and check:\
[g|1,$g]/BTL/[s|.s]/[/|BTL/]Bell Laboratories/gp
combine every even-numbered line with the next odd-numbered line:\
2,${-{1}}g/[^|$]/[j|.,{.}+{1}j|.,.1j]
print next "SH" and following line:\
/SH/;[{.}+{1}|.1]p|/SH/,[//|/SH/][{.}+{1}|.1]p
print from next "TS" to following "TE":/TS/;/TE/p
reverse order of lines in whole file:[g|1,$g]/^/[m|.m]0
replace each string of x's in current line by one x:\
[s|.s]/[x|\[x\]][x|\[x\]]*/x/g{p}{ (not s/x*/x/g)}
change first "hte" in current line to "the" and check:[s|.s]/hte/the/p
combine previous line and this one:\
[-,|^,|{.}-{1},].j
go to line after third "PP" ahead:\
/[PP|{^}\\.PP]/;[//|/[PP|{^}\\.PP]/];[//|/[PP|{^}\\.PP]/]\
[{+}1|+]|;[{.}+{1}|.1]{ (not ...p)}
exchange current line with previous line:\
[[-|^]m|{.}-{1}m].|{.}m[[--|^^]|{.}-2]
move everything from here through "stop." to end of file:\
.,/stop\\./m$
current line has 2 fields separated by 1 blank; exchange them:\
[s|.s]/[\\|^\\]([.|\[^ \]]*\\) \\([.|\[^ \]]*\\)[/|$/]\\2 \\1/{p}
insert a "0" after last "0" on current line:\
[s|.s]/[.*0/&0|^.*0/&0|0\\(\[^0\]*\\)$/[0&|00\1]|0\[^0\]*$/0&\
|\[^0\]*$/0&]/{p}
replace "a*b" by "a**b":s/[a\\*b|a[*]b]/a**b/{p}|\
s/\\*/**/p
attach the word "extra" to the end of the current line:\
[s|.s]/$/{ }extra/{p}
replace "ATT" in current line by "AT&T":\
[s|.s]/ATT/AT\\&T/{g}{p}
double the length of the current line by repetition:\
[s|.s]/[.*|.|^.*$]/&&/{p}
look for another line containing what you just looked for://
find the previous line that contains a capital letter:?\[A-Z\]?{p}
delete the next line that contains only capital letters:\
/^\[A-Z\]*$/d|/^\[A-Z\]\[A-Z\]*$/d
place a copy of current line at the end of the file:\
t$|.{,.}t$
find how many lines there are:=|$=
find the number of the current line:.=
delete the first 3 lines of the file:1,3d
delete every line that doesn't begin with "A":\
[v|1,$v]/^A/d{ (not g/^\[^A\]/d)}
delete every empty line from here through next "LP":\
.,/[LP|{{^}\\.}LP]/g/^$/d
print the line after each "AU":\
[g|1,$g]/[AU|{^}\\.AU]/[{.}+{1}|.1]{p}
delete everything after "proud" from current line:\
[s|.s]/proud.*/proud/{p}
delete part of current line from "alpha" through "omega":\
[s|.s]/alpha.*omega//{p}
save everything up through current line in file "prefix":1,.w prefix
prepare to add text at end of file:$a
append the contents of file "suffix" to this file:$r suffix
go back 10 lines:{.}-10{p}|----------
change every "01" in current line to "1":[s|.s]/01/1/g{p}
go to next line that contains a double capital letter:\
/\\(\[A-Z\]\\)\\1/{p}
place parens () around current line:\
[s|.s]/[.*|^.*$]/(&)/{p}
the current line is too long for your terminal; print it to fit:\
l|.l
put the work you've done back in the original file:w
append the whole file to the file "unfinished":\
[W|1,$W] unfinished
insert "\\&" at beginning of current line:\
[s|.s]/^/\\\\\\&/{p}
list your current directory:!ls
stop work on current file and shift to file "other":e other

View File

@ -0,0 +1,103 @@
H:1:1.008:Hydrogen
He:2:4.003:Helium
Li:3:6.94:Lithium
Be:4:9.013:Beryllium
B:5:10.82:Boron
C:6:12.011:Carbon
N:7:14.008:Nitrogen
O:8:16.0:Oxygen
F:9:19.0:Fluorine
Ne:10:20.183:Neon
Na:11:22.991:Sodium
Mg:12:24.32:Magnesium
Al:13:26.98:Aluminum
Si:14:28.09:Silicon
P:15:30.975:Phosphorus
S:16:32.066:Sulphur
Cl:17:35.457:Chlorine
Ar:18:39.944:Argon
K:19:39.1:Potassium
Ca:20:40.08:Calcium
Sc:21:44.96:Scandium
Ti:22:47.9:Titanium
V:23:50.95:Vanadium
Cr:24:52.01:Chromium
Mn:25:54.94:Manganese
Fe:26:55.85:Iron
Co:27:58.94:Cobalt
Ni:28:58.71:Nickel
Cu:29:63.54:Copper
Zn:30:65.38:Zinc
Ga:31:69.72:Gallium
Ge:32:72.6:Germanium
As:33:74.91:Arsenic
Se:34:78.96:Selenium
Br:35:79.916:Bromine
Kr:36:83.8:Krypton
Rb:37:85.48:Rubidium
Sr:38:87.63:Strontium
Y:39:88.92:Yttrium
Zr:40:91.22:Zirconium
Nb:41:92.91:Niobium
Mo:42:95.95:Molybdenum
Tc:43:(99):Technetium
Ru:44:101.1:Ruthenium
Rh:45:102.91:Rhodium
Pd:46:106.4:Palladium
Ag:47:107.88:Silver
Cd:48:112.41:Cadmium
In:49:114.82:Indium
Sn:50:118.7:Tin
Sb:51:121.76:Antimony
Te:52:127.61:Tellurium
I:53:126.91:Iodine
Xe:54:131.3:Xenon
Cs:55:132.91:Cesium
Ba:56:137.36:Barium
La:57:138.92:Lanthanum
Ce:58:140.13:Cerium
Pr:59:140.92:Praseodymium
Nd:60:144.27:Neodymium
Pm:61:(145):Promethium
Sm:62:150.35:Samarium
Eu:63:152.0:Europium
Gd:64:157.26:Gadolinium
Tb:65:158.93:Terbium
Dy:66:162.51:Dysprosium
Ho:67:164.94:Holmium
Er:68:167.27:Erbium
Tm:69:168.94:Thulium
Yb:70:173.04:Ytterbium
Lu:71:174.99:Lutetium
Hf:72:178.5:Hafnium
Ta:73:180.95:Tantalum
W:74:183.86:Tungsten
Re:75:186.22:Rhenium
Os:76:190.2:Osmium
Ir:77:192.2:Iridium
Pt:78:195.09:Platinum
Au:79:197.0:Gold
Hg:80:200.61:Mercury
Tl:81:204.39:Thallium
Pb:82:207.21:Lead
Bi:83:209.0:Bismuth
Po:84:(210):Polonium
At:85:(210):Astatine
Rn:86:(222):Radon
Fr:87:(223):Francium
Ra:88:(226):Radium
Ac:89:(227):Actinium
Th:90:232.05:Thorium
Pa:91:(231):Protactinium
U:92:238.07:Uranium
Np:93:(237):Neptunium
Pu:94:(242):Plutonium
Am:95:(243):Americium
Cm:96:(248):Curium
Bk:97:(247):Berkelium
Cf:98:(249):Californium
Es:99:(254):Einsteinium
Fm:100:(253):Fermium
Md:101:(256):Mendelevium
No:102:(253):Nobelium
Lw:103:(259):Lawrencium

View File

@ -0,0 +1,33 @@
Albania:Tirana|Tirane"
Andorra:Andorra la V[ell|iej]a
Austria:Vienna|Wien
Belgium:Brussel[s|]|Bruxelles
Bulgaria:Sofi[a|ya]
Czechoslovakia:Prague|Praha
Denmark:Copenhagen|K[o|o/]benhavn
East Germany:Berlin
United Kingdom|England|Great Britain|UK:London
Finland:Helsinki
France:Paris
Greece:Athens
Hungary:Budapest
Iceland:Reykjavik
Ireland|Eire:Dublin
Italy:Rom[e|a]
Liechtenstein:Vaduz
Luxembourg:Luxembourg
Malta:Valletta
Monaco:Monte Carlo
Netherlands|Holland:The Hague|'sGravenhage|den Haag|Amsterdam
Norway:Oslo
Poland:Wars[aw|zawa]
Portugal:Lisbo[n|a]
R[u|o]mania:Bucharest|Bucuresti
San Marino:San Marino
Spain:Madrid
Sweden:Stockholm
Switzerland:Bern{e}
Turkey:Ankara
USSR|Russia:Mos[cow|kva]
[West |]Germany:Bonn
Yugoslavia:Belgrade|Beograd

Binary file not shown.

View File

@ -0,0 +1,7 @@
$luw$:{I} [loose|destroy]
$eluon$:{I} [loosed|destroyed|was loosing|was destroying]
$elusa$:{I} [loosed|destroyed]
$leluka$:{I} have [loosed|destroyed]
$lusw$:{I} will [loose|destroy]
$luswn$:[loosing|destroying]
$lusas$:{having} [loosed|destroyed]

View File

@ -0,0 +1,12 @@
manco capac:sinchi roca
sinchi roca:lloque yupanqui
lloque yupanqui:mayta capac
mayta capac:capac yupanqui
capac yupanqui:inca roca
inca roca:yahuar huacac
yahuar huacac:viracocha
viracocha:pachacuti
pachacuti:tupa inca yupanqui
tupa inca yupanqui:huayna capac
huayna capac:huascar
huascar:atahuallpa

View File

@ -0,0 +1,30 @@
/usr/local/games/quiz.k/state:state:cap{ital}:abbr{ev{iation}}:flower
/usr/local/games/quiz.k/america:America{n}:cap{ital}
/usr/local/games/quiz.k/europe:Europe{an}:cap{ital}
/usr/local/games/quiz.k/africa:Africa{n}:cap{ital}
/usr/local/games/quiz.k/pres:pres{ident}:term:succ{essor}
/usr/local/games/quiz.k/sov:sov{ereign}:cen{t{ury}}:succ{essor}
/usr/local/games/quiz.k/seq-easy:easy{-}{seq{uence}}:next:name
/usr/local/games/quiz.k/seq-hard:hard{-}{seq{uence}}:next:name
/usr/local/games/quiz.k/posneg:pos{itive}:neg{ative}
/usr/local/games/quiz.k/bard:Shakespeare{{-}line{s}}|line{s}:next:work:char{acter}
/usr/local/games/quiz.k/murders:victim:killer
/usr/local/games/quiz.k/collectives:ind{ividuals}:coll{ective}
/usr/local/games/quiz.k/trek:star:trek
/usr/local/games/quiz.k/babies:baby:adult
/usr/local/games/quiz.k/poetry:poem{-}line:next:poem:author
/usr/local/games/quiz.k/midearth:M[iddle{-}Earth|E]:cap{ital}
/usr/local/games/quiz.k/inca:inca:succ{essor}
/usr/local/games/quiz.k/morse:clear|alpha{bet{ic}}:morse
/usr/local/games/quiz.k/sexes:male:female
/usr/local/games/quiz.k/greek:greek:english
/usr/local/games/quiz.k/latin:latin:english
/usr/local/games/quiz.k/locomotive:locomotive:name
/usr/local/games/quiz.k/ucc:section:ucc
/usr/local/games/quiz.k/chinese:year:next
/usr/local/games/quiz.k/elements:symbol:number:weight:element
/usr/local/games/quiz.k/province:province:cap{ital}
/usr/local/games/quiz.k/asia:Asia{n}:cap{ital}
/usr/local/games/quiz.k/arith:arith{metic}:ans{wer}
/usr/local/games/quiz.k/areas:area{-code}:state{-region}:city
/usr/local/games/quiz.k/ed:function:ed-command

View File

@ -0,0 +1,157 @@
condo:{I }found
condidi:{I }founded
laedo:{I }[injure|thwart]
impello:{I }[drive|force]
impulit:{he }[drove|forced]
sino:{I }permit
sinat:{he }permit{s}
dolor:pain|grief
invideo:{I }[envy|hate]
invisus:[hated|envied]
immitis:cruel|harsh
arceo:{I }[keep away|hinder|prevent]
ratis:ship
antrum:cave
freno:rein{ in}|curb|check
celsus:lofty
spelunca:cave{rn}
foedus (n.):agreement|treaty|truce
foedera:agreements|treaties
laxus:loose|free
habena:rein{s}
mulceo:soothe|calm
fluctus (n.):wave{s}
exigo:finish|spend
exegit:{he }[finished|spent]
opto (v.):desire|wish
optat:{he }[desire{s}|wish{es}]
capesso:seize|carry out
concilio (v.):secure|gain
converto:reverse
procella:blast|gust
polus:sky|heaven
mico:flash|gleam
extemplo:immediately
frigus (n.):cold|chill
ingemo:groan
os (n.):mouth
effundo:pour{ out}
corripio:snatch|catch
harena:sand
excutio:shake{ off}
nare:{to }swim
rima:crack|fissure
fatisco:gape{ open}
disjicio:scatter|disperse
dolus (n.):deceit
luo:wash{ away}|atone{ for}
cito (adv.):quickly|soon
tumidus:swollen
fugo:put to flight|drive out
adnitor:strive
seditio:riot|uprising
fax:fire{-}brand
volo (v.):fly
arrigo:prick up
cunctus:whole|entire
flecto:turn|guide
sinus:bay|fold|curve|gulf
scindo:split|divide
rupes:crag|cliff
geminus:twin
minatur:{he }threaten{s}
coruscus:flashing|waving
horreo:bristle
nemus:grove
nemora:groves
umbra:shade|shadow
intus:within
dulcis:sweet|fresh
sedile:seat|bench
fessus:weary|tired
uncus:hooked|curved
morsus:bite
artus:joint|limb
silex:flint
scintilla:spark
folium:leaf
aridus:dry
corrumpo:spoil|ruin
corrupit:{he }[spoil{ed}|ruin{ed}]
frux:grain
torreo:parch
celsus:high|lofty
cervus:stag
erro:wander
armentum:herd
pasco:feed|nourish
pascor:graze
arcus:bow
turba:crowd
sterno:strew
humus:ground|earth
vinum:wine
maereo:mourn|sorrow
ignarus:unknowing|ignorant|inexperienced
rabies:rage|fury
penitus:within
sono (v.):sound|roar
maestus:sad|gloomy
forsan:perhaps
olim:someday|sometime
memini:{I }remember
varius:different
discrimen:crisis|danger
quiesco:become quiet
refert:{he }[say{s}|tell{s}]
vultus:face|countenance
cor:heart
corda:hearts
dolor:pain|grief
daps:feast
dapes:feasts
viscus:flesh
seco:cut
tremo:quiver
pinguis:fat|rich
mensa:table
sermo:talk|discourse
dubius:doubtful|wavering
pius:dutiful|devoted|loyal
gemo:lament|moan|bemoan
crudelis:cruel|bitter
lumen:light|eye
lumina:lights|eyes
tristis:sad
lacrima:tear
niteo:shine|glisten
fulmen:thunderbolt|lightning
fulmina:thunderbolts
funus:death|disaster
funera:deaths|disasters
orbis terrarum:world
ductor:leader
dicio (n.):power
fons:spring|source
fontes:springs|sources
arvum:land
infandus:unspeakable
rideo:laugh
osculum:lip
libo:sip|touch|kiss
nata:daughter
haereo:{I }[stick to|adhere]
promitto:primise
sublimis:high|uplifted|up high
quando:since|when|because
arcanum:{a }secret
ferox:fierce|savage
contundo:crush
albus:white
donec:until
sacerdos:priest{ess}
lupus:wolf
nutrix:nurse
nutrices:nurses
fulvus:tawny|yellow
meta:limit|boundary

View File

@ -0,0 +1,11 @@
4-4-0:American
4-6-0:Mogul
4-4-2:Atlantic
4-6-2:Pacific
2-8-0:Consolidation
2-8-2:Mikado
4-8-2:Mountain
2-8-4:Berkshire
4-6-4:Hudson
4-8-4:Northern
2-10-2:Decapod

View File

@ -0,0 +1,10 @@
Shire:Michel Delving|Hobbiton
Mordor:Minas Morgul
Gondor:Minas Tirith
Umbar:{City of the }Corsairs
Rhovanion:Esgaroth{ upon the Long Lake}
Rohan:Edoras
Lothl['o|o|o']rien:Caras Galadon
Breeland:Bree
Arnor:Ann['u|u'|u]minas
Arthedain:Fornost{ Erain}|Norbury of the Kings

View File

@ -0,0 +1,26 @@
A:.-
B:-...
C:-.-.
D:-..
E:.
F:..-.
G:--.
H:....
I:..
J:.---
K:-.-
L:.-..
M:--
N:-.
O:---
P:.--.
Q:--.-
R:.-.
S:...
T:-
U:..-
V:...-
W:.--
X:-..-
Y:-.--
Z:--..

View File

@ -0,0 +1,25 @@
Cock Robin:{the }sparrow
sleep|Duncan:Macbeth
{the }cat:curiosity|care
{John {F{.} }}Kennedy|JFK:{Lee Harvey }Oswald|{the }FBI|{the }CIA
{Lee Harvey }Oswald:{Jack }Ruby|{the }FBI|{the }CIA
{Martin Luther }King:{James {Earl }}Ray|{the }FBI|{the }CIA
[Bobby |Robert {F{.} }]Kennedy|RFK:{Sirhan }Sirhan|{the }FBI|{the }CIA
Christ:{the }Romans|{Pontius }Pilate|{the }CIA
{Sharon }Tate:{Charles }Manson
Charles Lindbergh Jr{.}:{Bruno }Hauptman{n}
{Mr{.} }{{and }Mrs{.} }Borden|{her }parents:Lizzie{ Borden}
{Prof{essor} }{James }Moriarty:{Sherlock }Holmes
Achilles:Paris
Abel:Cain
{the }nurses:{Richard }Speck
{J{.} |Julius }Caesar:Brutus{ et al.}
Pompeii:Vesuvius
{Abraham |Abe }Lincoln:{John {Wilkes }}Booth
{Yukio }Mishima:{Yukio }Mishima
{Alexander }Hamilton:{Aaron }Burr
Cleopatra:{the |an }asp
[Ann Boleyn|Catharine Howard]:Henry{ VIII}
vaudeville:{the }movies|film
{the }movies|film:TV|television
{the }VA patients:{the }nurses

View File

@ -0,0 +1,184 @@
Come live with me and be my love:\
And we will all the pleasures prove:\
{The }Passionate Shepherd{ to his Love}:\
{Christopher }Marlowe
Shall I compare thee to a summer's day{?}:\
Thou art more lovely and more temperate:\
Sonnet 18:\
{William }Shakespeare
Fine knacks for ladies, cheap, choice, brave, and new!:\
Good pennyworths{! }but money cannot move:\
Fine Knacks{ for Ladies}:\
{John }Dowland
My mind to me a kingdom is:\
Such perfect joy therein I find:\
My Mind to Me a Kingdom Is:\
{Sir }{Edward }Dyer
Underneath this stone doth lie:\
As much beauty as could die:\
Epitaph on Elizabeth{,} {L. H.}:\
{Ben }Jonson
Death be not proud, though some have called thee:\
Mighty and dreadful{,} for thou art not so:\
{Holy }Sonnet{s}{ 10}:\
{John }Donne
Gather ye rose-buds while ye may:\
Old Time is still a-flying:\
To the Virgins{,} {To Make Much of Time}:\
{Robert }Herrick
Why so pale and wan, fond lover?:\
Prithee{,} why so pale{?}:\
Song:\
{Sir }{John }Suckling
Stone walls do not a prison make:\
Nor iron bars a cage:\
To Althea{,} From Prison:\
{Richard }Lovelace
I could not love thee (Dear) so much,:\
Lov['|e]d I not hono{u}r more:\
To Lucasta{, Going to the Wars}:\
{Richard }Lovelace
I saw Eternity the other night:\
Like a great ring of pure and endless light:\
{The }World:\
{Henry }Vaughan
Come and trip it as you go,:\
On the light fantastic toe:\
L'Allegro:\
{John }Milton
When I consider how my light is spent:\
Ere half my days in this dark world and wide:\
On His Blindness|When I Consider:\
{John }Milton
The grave's a fine and private place{,}:\
But none{,} I think{,} do there embrace{.}:\
To His Coy Mistress:\
{Andrew }Marvel
Great wits are sure to madness near allied:\
And thin partitions do their bounds divide:\
Absalom and Achitophel|Absalom:\
{John }Dryden
A little learning is a dangerous thing{;}:\
Drink deep{,} or taste not the Pierian spring{.}:\
{An }Essay on Criticism|{On }Criticism:\
{Alexander }Pope
The curfew tolls the knell of parting day{,}:\
The lowing herd wind slowly o'er the lea:\
Elegy{ Written in a Country Church{-| }Yard:\
{Thomas }Gray
The best laid schemes o' mice an' men gang aft a-gley{,}:\
An{'|d} lea{'|v}e us nought but grief an{'|d} pain for promised joy{.}:\
To a Mouse:\
{Robert }Burns
Tiger! tiger! burning bright!:\
In the forests of the night:\
{The }Tiger:\
{William }Blake
My heart leaps up when I behold:\
A rainbow in the sky:\
My Heart Leaps Up:\
{William }Wordsworth
The world is too much with us; late and soon{,}:\
Getting and spending{,} we lay waste our powers:\
{The }World is Too Much With Us|Sonnet:\
{William }Wordsworth
A sadder and a wiser man{,}:\
He rose the morrow morn:\
{The }{Rime of }{The }Ancient Mariner:\
{Samuel }{Taylor }Coleridge
In Xanadu did Kubla Khan:\
A stately pleasure{-| }dome decree:\
Kubla Khan:\
{Samuel }{Taylor }Coleridge
She walks in beauty, like the night:\
Of cloudless climes and starry skies:\
She Walks in Beauty:\
{George Gordon, }{Lord }Byron
I want a hero- an uncommon want{,}:\
When every year and month sends forth a new one:\
Don Juan{ Canto I}:\
{George Gordon, }{Lord }Byron
A thing of beauty is a joy forever.:\
Its loveliness increases{;|.} {it will never/Pass into nothingness}:\
Endymion{ Book I}:\
{John }Keats
Matched with an aged wife, I mete and dole:\
Unequal laws unto a savage race:\
Ulysses:\
{Alfred{,} }{Lord }Tennyson
He will hold thee, when his passion shall have spent its novel force{,}:\
Something better than his dog{,} a little dearer than his horse:\
Locksley Hall:\
{Alfred{,} }{Lord }Tennyson
'Tis better to have loved and lost:\
Than never to have loved at all:\
{In }Memoriam{ A. H. H.}:\
{Alfred{,} }{Lord }Tennyson
Kind hearts are more than coronets,:\
And simple faith than Norman blood{.}:\
Lady Clara Vere de Vere:\
{Alfred{,} }{Lord }Tennyson
Oh, to be in England:\
Now that April's there:\
Home{-| }Thoughts{,} From Abroad:\
{Robert }Browning
Ah, but a man's reach should exceed his grasp{,}:\
Or what's a heaven for{?}:\
Andrea Del Sarto:\
{Robert }Browning
How do I love thee? Let me count the ways.:\
I love thee to the depth and breadth and height:\
Sonnet{s} {From the Portuguese}{ 43}:\
{Elizabeth }{Barrett }Browning
A Book of Verses underneath the Bough{,}:\
A Jug of Wine, a Loaf of Bread{-|,| }and Thou:\
{The }Rubaiyat{ of Omar Khayyam}{ 12}:\
{Edward }Fitzgerald
The Moving Finger writes; and, having writ,:\
Moves on{\:|,|.} nor all your Piety nor Wit:\
{The }Rubaiyat{ of Omar Khayyam}{ 71}:\
{Edward }Fitzgerald
Ah Love! could you and I with Him conspire:\
To grasp this sorry Scheme of Things entire:\
{The }Rubaiyat{ of Omar Khayyam}{ 99}:\
{Edward }Fitzgerald
Remember me when I am gone away,:\
Gone far away into the silent land:\
Remember:\
{Christina }Rossetti
Home is the sailor, home from the sea,:\
And the hunter home from the hill:\
Requiem:\
{Robert }{Louis }Stevenson
I fled Him, down the nights and down the days;:\
I fled Him, down the arches of the years:\
{The }Hound of Heaven:\
{Francis }Thompson
So 'ere's to you, Fuzzy-Wuzzy, at your 'ome in the Soudan;:\
You're a {pore|poor} benighted {'|h}eathen but a first class fightin{'|g} man:\
Fuzzy{-| }Wuzzy:\
{Rudyard }Kipling
Morns abed and daylight slumber:\
Were not meant for man alive:\
Reveille:\
{A{.}{ }E{.}{ }}Houseman
I will arise and go now, and go to Innisfree,:\
And a small cabin build there{,} of clay and wattles made:\
{The }{Lake Isle of }Innisfree:\
{William }{Butler }Yeats
I must go down to the seas again, to the lonely sea and the sky,:\
And all I ask is a tall ship and a star to steer her by:\
Sea{-| }Fever:\
{John }Masefield
April is the cruelest month, breeding:\
Lilacs out of the dead land:\
{The }Waste{ }Land:\
{T{.}{ }S{.}{ }}Eliot
Now as I was young and easy under the apple boughs:\
About the little house and happy as the grass was green:\
Fern Hill:\
{Dylan }Thomas
Of Man's first disobedience, and the fruit:\
Of that forbidden tree{,} whose mortal taste:\
Paradise Lost:\
{John }Milton

View File

@ -0,0 +1,50 @@
large|big:small
on:off
standing up:sitting down
inside:outside
high:low
old:new|young
hot:cold
out:in
heavy|dark:light
daytime:night[time| time]
stop|come:go
top:bottom
floor:ceiling
near:far
run:walk
empty|hungry:full
backwards:f[or|ront]wards
big|large:little|small
fat|thick:thin|skinny
bright|light:dark|dull
right:wrong|left
give:take|receive|get
buy:sell
shiny|bright:dull
dawn:dusk
fall down|go to bed:[get|stand|rise] up
asleep:awake
up:down
open[|ed|]:close[d|]
smile:frown|cry
happy|glad:sad
hard:soft|easy
boy|woman|lady:girl|man
fast:slow
wet:dry
covered|hid[den|]:uncovered|open
good:bad
always|sometimes|now:never|sometimes
beautiful|pretty:ugly
rough:smooth
hairy:bald||smooth
above:below
yin:yang
sweet:sour
if:unless
from|fro:to
with[|in|]:without|against
after:before
together:apart
plus:minus

View File

@ -0,0 +1,38 @@
{G{eorge} }Washington:1789-{17}97:{J{ohn} }Adams
{J{ohn} }Adams:1797-1801:{T{homas} }Jefferson
{T{homas} }Jefferson:1801-{{18}0}9:{J{ames} }Madison
{J{ames} }Madison:1809-{18}17:{J{ames} }Monroe
{J{ames} }Monroe:1817-1825:{J{ohn} }{Q{uincy} }Adams
{J{ohn} }{Q{uincy} }Adams:1825-{{18}2}9:{A{ndrew} }Jackson
{A{ndrew} }Jackson:1829-{18}37:{M{artin} }Van Buren
{M{artin} }Van Buren:1837-{18}41:{W{illiam|m} }{H{enry} }Harrison
{W{illiam|m} }{H{enry} }Harrison:1841:{J{ohn} }Tyler
{J{ohn} }Tyler:1841-{{18}4}5:{J{ames} }{K{nox} }Polk
{J{ames} }{K{nox} }Polk:1845-{{18}4}9:{Z{achary} }Taylor
{Z{achary} }Taylor:1849-{18}50:{M{illard} }Fillmore
{M{illard} }Fillmore:1850-{{18}5}3:{F{ranklin} }Pierce
{F{ranklin} }Pierce:1853-{{18}5}7:{J{ames} }Buchanan
{J{ames} }Buchanan:1857-{18}61:{A{braham|be} }Lincoln
{A{braham|be} }Lincoln:1861-{{18}6}5:{A{ndrew} }Johnson
{A{ndrew} }Johnson:1865-{{18}6}9:{U{lysses} }{S{impson} }Grant
{U{lysses} }{S{impson} }Grant:1869-{18}77:{R{utherford} }{B{irchard} }Hayes
{R{utherford} }{B{irchard} }Hayes:1877-{18}81:{J{ames} }{A{bram} }Garfield
{J{ames} }{A{bram} }Garfield:1881:{C{hester} }{A{lan} }Arthur
{C{hester} }{A{lan} }Arthur:1881-{{18}8}5:{G{rover} }Cleveland{ (1st term)}
{G{rover} }Cleveland{ (1st term)}:1885-{{18}8}9:{B{enjamin} }Harrison
{B{enjamin} }Harrison:1889-{18}93:{G{rover} }Cleveland{ (2nd term)}
{G{rover} }Cleveland{ (2nd term)}:1893-{18}97:{W{illiam|m} }McKinley
{W{illiam|m} }McKinley:1897-1901:{T{heodore|eddy} }Roosevelt|TR
{T{heodore|eddy} }Roosevelt|TR:1901-{{19}0}9:{W{illiam|m} }{H{oward} }Taft
{W{illiam|m} }{H{oward} }Taft:1909-{19}13:{W{oodrow} }Wilson
{W{oodrow} }Wilson:1913-{19}21:{W{arren} }{G{amaliel} }Harding
{W{arren} }{G{amaliel} }Harding:1921-{{19}2}3:{C{alvin} }Coolidge
{C{alvin} }Coolidge:1923-{{19}2}9:{H{erbert} }Hoover
{H{erbert} }Hoover:1929-{19}33:{F{ranklin} }{D{elano} }Roosevelt|FDR
{F{ranklin} }{D{elano} }Roosevelt|FDR:1933-{19}45:{H{arry} }{S }Truman
{H{arry} }{S }Truman:1945-{19}53:{D{wight} }{D{avid} }Eisenhower
{D{wight} }{D{avid} }Eisenhower:1953-{19}61:{J{ohn} }{F{itzgerald} }Kennedy|JFK
{J{ohn} }{F{itzgerald} }Kennedy|JFK:1961-{{19}6}3:{L{yndon} }{B{aines} }Johnson|LBJ
{L{yndon} }{B{aines} }Johnson|LBJ:1963-{{19}6}9:{R{ichard} }{M{ilhouse} }Nixon
{R{ichard} }{M{ilhouse} }Nixon:1969-{19}74:{G{erald} }{R{obert} }Ford
{G{erald} }{R{obert} }Ford:1974-:

View File

@ -0,0 +1,13 @@
Newfoundland{ and Labrador}:[St.|Saint] John's
New Brunswick:Fredericton
Prince Edward Island:Charlottetown
Nova Scotia:Halifax
Quebec:Quebec
Ontario:Toronto
Manitoba:Winnipeg
Saskatchewan:Regina
Alberta:Edmonton
British Columbia:Victoria
Yukon Territory:Whitehorse
Northwest Territories:Yellowknife
Canada:Ottawa

View File

@ -0,0 +1,14 @@
1,2,3,4,5,6:7{(integers)}:integers|[natural|counting] numbers
1,2,3,5,8,13:21{(Fibonacci)}:Fibonacci{ seq{ence}| numbers}
1,2,4,8,16,32:64{(powers of 2)}:powers of 2|2[**|^]n
1,2,6,24,120,720:5040{(factorials)}:factorials|n!
1,3,5,7,9,11:13{(odd nos.)}:odd [integ|numb]ers
1,3,6,10,15,21:28{(triangular)}:triangular{ numbers}|C(n,2)
1,3,9,27,81:243{(powers of 3)}:powers of 3|3[**|^]n
1,4,9,16,25:36{(squares)}:squares|n[**|^]2
1,4,16,64:256{(powers of 4)}:powers of 4|4[**|^]n
1,5,25,125:625{(powers of 5)}:powers of 5|5[**|^]n
1,8,27,64,125:216{(cubes)}:cubes|n[**|^]3
2,3,5,7,11,13:17{(primes)}:prime[ number]s
2,4,6,8,10,12:14{(even nos.)}:even [integ|numb]ers|multiples of 2|2n
3,6,9,12,15:18{(3n)}:multiples of 3|3n

View File

@ -0,0 +1,15 @@
1,1,2,1,2,2,3,1,2,2,3,2,3,3,4:1{(1's in binary nos)}:number of 1's in binary numbers
1,1,2,2,4,2,6,4,6,4,10:4{(phi(n))}:Euler's [totient|phi]{ function}|phi(n)
1,2,2,4,2,4,2,4,6,2:6{(diff of primes)}:diff{erences} [between|of] primes
1,2,4,11,34:156{(unlabeled graphs)}:{unlabeled }graphs
1,2,5,14,42,132:429{(Catalan)}:Catalan{ numbers}
1,2,5,16,61:272{(Euler)}:Euler{ numbers}
1,3,12,60,360:2520{(n!/2)}:Even permutations|n!/2
1,3,16,125,1296,16807:262144{(n**(n-2))}:{labeled }trees|n[**|^](n-2)
1,4,10,20,35,56:84{(C(n,3))}:Tetrahedral{ numbers}|C(n,3)
1,4,11,20,31,44,61:100{(n**2 base 8)}:[Squares|n[**|^]2} base 8|octal squares
1,4,16,256:65536{(2**2**n)}:{labeled }boolean functions|2[**|^]2[**|^]n
1,6,28:496{(perfect nos)}:perfect{ numbers}
2,7,1,8,2,8:1{(e)}:{digits of }e
3,1,4,1,5,9:2{(pi)}:{digits of }pi
3,7,31,127:8191{(Mersenne primes)}:Mersenne{ primes}

View File

@ -0,0 +1,26 @@
Y|y:X|x
abbot:abbess
alumnus:alumna
ambassador:ambassadress
boar:sow
buck:doe
bull:cow
cob:pen
colt:filly
curator:curatrix
dog:bitch|vixen
duke:duchess
drake:duck
effeminate|womanish:mannish
gander:goose
gentleman:lady|gentlewoman
jack:jenny
lad:lass
manly:womanly
marquis:marchioness[|e]|marquise
monk:nun
[O|o]edipus complex:[E|e]lectra[| complex]
prince:princess
ram:ewe
rooster|cock:hen
stallion:mare

View File

@ -0,0 +1,42 @@
W[illia|]m [I|1|the Conqueror]:11:W[illia|]m [II|2|Rufus|the Red]
W[illia|]m [II|2|Rufus|the Red]:11:Hen[ry|] [I|1]
Hen[ry|] [I|1]:12:Stephen
Stephen:12:Hen[ry|] [II|2]
Hen[ry|] [II|2]:12:Rich[ard|] [I|1]
Rich[ard|] [I|1]:12:John
John:13|12-13:Hen[ry|] [III|3]
Hen[ry|] [III|3]:13:Ed[w[ard|]|] [I|1]
Ed[w[ard|]|] [I|1]:13-14|13|14:Ed[w[ard|]|] [II|2]
Ed[w[ard|]|] [II|2]:14:Ed[w[ard|]|] [III|3]
Ed[w[ard|]|] [III|3]:14:Rich[ard|] [II|2]
Rich[ard|] [II|2]:14:Hen[ry|] [IV|4] Part 1
Hen[ry|] [IV|4] Part 1:15|14-15:Hen[ry|] [IV|4] Part 2
Hen[ry|] [IV|4] Part 2:15|14-15:Hen[ry|] [V|5]
Hen[ry|] [V|5]:15:Hen[ry|] [VI|6]
Hen[ry|] [VI|6]:15:Ed[w[ard|]|] [IV|4]
Ed[w[ard|]|] [IV|4]:15:Ed[w[ard|]|] [V|5]
Ed[w[ard|]|] [V|5]:15:Rich[ard|] [III|3]
Rich[ard|] [III|3]:15:Hen[ry|] [VII|7]
Hen[ry|] [VII|7]:15-16|15|16:Hen[ry|] [VIII|8]
Hen[ry|] [VIII|8]:16:Ed[w[ard|]|] [VI|6]
Ed[w[ard|]|] [VI|6]:16:Mary
Mary:16:Eliz[abeth|][ [I|1]|]
Elizabeth[ [I|1]|]:16-17|16:Ja[me|]s [I|1]
Ja[me|]s [I|1]:17:Cha[rle|]s [I|1]
Cha[rle|]s [I|1]:17:[Oliver |]Cromwell
[Oliver |]Cromwell:17:Rich[ard|] Cromwell
Rich[ard|] Cromwell:17:Ch[arle|]s [II|2]
Cha[rle|]s [II|2]:17:Ja[me|]s [II|2]
Ja[me|]s [II|2]:17:W[illia|]m and Mary
W[illia|]m and Mary:17-18|17:Anne
Anne:18:Geo[rge|] [I|1]
Geo[rge|] [I|1]:18:Geo[rge|] [II|2]
Geo[rge|] [II|2]:18:Geo[rge|] [III|3]
Geo[rge|] [III|3]:18-19|18|19:Geo[rge|] [IV|4]
Geo[rge|] [IV|4]:19:W[illia|]m [IV|4]
W[illia|]m [IV|4]:19:Victoria
Victoria:19:Ed[w[ard|]|] [VII|7]
Ed[w[ard|]|] [VII|7]:19-20|19|20:Geo[rge|] [V|5]
Geo[rge|] [V|5]:20:Ed[w[ard|]|] [VIII|8]
Ed[w[ard|]|] [VIII|8]:20:Geo[rge|] [VI|6]
Geo[rge|] [VI|6]:20:Eliz[abeth|] [II|2]

View File

@ -0,0 +1,2 @@
The son went behind a cloud.:sun
Did you see the monky at the zoo?:monkey

View File

@ -0,0 +1,50 @@
Alabama|Ala|AL:Montgomery:AL:camellia
Alaska|AK:Juneau:AK:forget{-| }me{-| }not
Arizona|Ariz|AZ:Phoenix:AZ:{saguaro }cactus{ blossom}
Arkansas|Ark|AR:Little Rock:AR:apple{ blossom}
Cal{if{ornia}}|CA:Sacramento:CA:{golden }poppy
Col{o{rado}}|CO:Denver:CO:{Rocky Mountain }columbine
Conn{ecticut}|CT:Hartford:CT:{mountain }laurel
Del{aware}|DE:Dover:DE:peach{ blossom}
Fl{orid}a|FL:Tallahassee:FL:orange{ blossom}
Georgia|Ga:Atlanta:GA:{Cherokee }rose
Hawaii|HI:Honolulu:HI:hibiscus
Idaho|Ida|ID:Boise:ID:syringa
Ill{inois}|IL:Springfield:IL:violet
Ind{iana}|IN:Indianapolis:IN:peony
Iowa|Ia:Des Moines:IA:{wild }rose
Kans{as}|Kan|KS:Topeka:KS:sun{ }flower
Kentucky|Ky:Frankfort:KY:goldenrod
Louisiana|La:Baton Rouge:LA:magnolia
Maine|Me:Augusta:ME:{white }pine{ }cone{ and}{ tassel}
Maryland|Md:Annapolis:MD:blackeyed susan
Mass{achusetts}|MA:Boston:MA:{trailing }arbutus
Mich{igan}|MI:Lansing:MI:apple{ blossom}
Minn{esota}|MN:Saint Paul|St Paul:MN:{showy }lady{-|'s | }slipper
Miss{issippi}|MS:Jackson:MS:magnolia
Missouri|Mo:Jefferson City:MO:hawthorn
Mont{ana}|MT:Helena:MT:bitterroot
Nebraska|Neb|NE|NB:Lincoln:NE|NB:goldenrod
Nevada|Nev|NV:Carson City:NV:sagebrush
New Hampshire|NH:Concord:NH:{purple }lilac
New Jersey|NJ:Trenton:NJ:violet
New Mexico|NM:Santa Fe:NM:yucca
New York|NY:Albany:NY:rose
N{orth} Carolina|NC:Raleigh:NC:{flowering }dogwood
N{orth} Dakota|ND:Bismarck:ND:{wild }{prairie }rose
Ohio|OH|O:Columbus:OH:{scarlet }carnation
Oklahoma|Okla|OK:Oklahoma City:OK:mistletoe
Oregon|Ore|OR:Salem:OR:{Oregon }grape
Pennsylvania|Pa:Harrisburg:PA:{mountain }laurel
Rhode Island|RI:Providence:RI:violet
S{outh} Carolina|SC:Columbia:SC:{yellow }jasmine
S{outh} Dakota|SD:Pierre:SD:{American }pasque{{f| f}lower}
Tenn{essee}|TN:Nashville:TN:iris
Texas|Tex|TX:Austin:TX:blue{-| }bonnet
Utah|UT:Salt Lake City:UT:{sego }lily
Vermont|Vt:Montpelier:VT:{red }clover
Virginia|Va:Richmond:VA:{flowering }dogwood
Wash{ington}|WA:Olympia:WA:{western }rhododendron
W{est} Virginia|W{ }Va|WV:Charleston:WV:rhododendron
Wisconsin|Wis|WI:Madison:WI:violet
Wyo{ming}|WY:Cheyenne:WY:Indian paint brush

View File

@ -0,0 +1,19 @@
captain's name:{James |Jim }{T. }Kirk|{james |jim}{t. }kirk
first officers name:Spock|spock|Mr. Spock|mr. spock
name of ship:{the }{u.s.s. }enterprise|Enterprise
name of the "good guys":{the }Federation|federation|{the }federation
name of the "bad guys":{the }klingons|{the }romulans
nickname of chief engineer:scotty|Scotty
nickname of chief medical officer:bones|Bones
machine use for transportation to surface of nearby planet:transporter|shuttlecraft
main engines of ship:warp engines|warp
number of crew:400|four hundred
hand-held weapon:phaser
type of torpedoes used on the ship:photon torpedoes|photon
name of electronic protective device on ship:shields|shield
name of device that makes a ship invisible:cloaking device|cloak|cloaking
type of voice that the on-board computer has:female|feminine|woman's
where first officer comes from:vulcan|Vulcan
rare, but very powerful enemies:romulans|Romulans
reaction that main engines operate on:matter-antimatter{ reaction}|matter/antimatter{ reaction}
slow engines used in emergencies:impulse engines|impulse

127
v7/games/quiz.k/ucc#000000 Normal file
View File

@ -0,0 +1,127 @@
1-103:supplementary general principles of law applicable
1-106:remedies to be liberally administered
1-201:general definitions
1-203:obligation of good faith
1-205:course of dealing and usage of trade
1-206:statue of frauds for kinds of personal property not otherwise covered
2-103:definitions-sales
2-201:statute of frauds
2-208:course of performance or practical consideration
2-302:unconscionable contract or clause
2-310:open time for payment or running of credit
2-319:FOB and FAS terms
2-320:CIF and C&F terms
2-323:form of bill of lading required in overseas shipment
2-401:passing of title; reservation for security
2-402:rights of seller's creditors against sold goods
2-403:powr to transfer; good faith purchase of goods; entrusting
2-501:insurable interest in goods; manner of identification of goods
2-502:buyer's right to goods on seller's insolvency
2-503:manner of seller's tender of delivery
2-506:rights of financing agency
2-507:effect of seller's tender; delivery on condition
2-508:cure by seller of improper tender or delivery; replacement
2-509:risk of loss in the absence ogf breach
2-510:effect of breach on risk of loss
2-513:buyer's right to inspection of goods
2-601:buyer's rights on improper delivery
2-602:manner and effect of rightful rejection
2-603:merchant buyer's duties as to rightfully rejected goods
2-605:waiver of buyer's objections by failure to particularize
2-606:what constitutes acceptance of goods
2-607:effect of acceptance; notice of breach
2-608:revocation of acceptance in whole or in part
2-609:right to adequate assurance of performance
2-610:anticipatory repudiation
2-611:retraction of anticipatory repudiation
2-612:installment contract; breach
2-702:seller's remedies on discovery o buyer's insolvency
2-703:seller's remedies in general
2-705:seller's stoppage of delivery in transit or otherwise
2-706:seller's resale including contract for resale
2-708:seller's damages for non-acceptance or repudiation
2-709:action for the price
2-711:buyer's remedies in general; buyer's security interest in rejected goods
2-712:cover; buyer's procurement of substitute goods
2-713:buyer's damages for on-delivery or repudiation
2-714:buyer's damages for breach in regard to accepted goods
2-715:buyer's incidental and consequential damages
2-716:buyer's right to specific performance or replevin
3-102:definitions-commercial paper
3-104:form of negotiable instruments; draft; check; certificate of deposit; note
3-110:payable to order
3-111:payable to bearer
3-201:transfer: right to indorsement
3-202:negotiation
3-204:special indorsement; blank indorsement
3-301:rights of a holder
3-302:holder in due course
3-305:rights of a holder in due course
3-306:rights of one not holder in due course
3-401:signature
3-404:unauthorized signature
3-405:impostors; signature in name of payee
3-406:negligence contributing to alteration or unauthorized signature
3-407:alteration
3-410:definition and operation of acceptance
3-411:certification of a check
3-413:contract of maker, drawer and acceptor
3-414:contract of indorser; order of liability
3-417:warranties on presentment and transfer
3-418:finality of payment or acceptance
3-419:conversion of instrument; innocent representative
3-501:when presentment, notice of dishonor, and protest necessary or permissible
3-502:unexcused delay; discharge
3-503:time or presentment
3-507:dishonor; holder's right of recourse; term allowing representment
3-508:notice of dishonor
3-511:waived or excused presentment, protest or notice of dishonor or delay therein
3-601:discharge of parties
3-802:effect of instrument on obligation for which it is given
3-804:lost,destroyed or stolen instruments
4-104:definitions-bank deposits and collections
4-105:banks-depositary, intermediary, collecting, payor, presenting, remitting
4-207:warranties of customer and collecting bank on transfer or presentment of items
4-208:security interest of collecting bank in items, accompanying documents and proceeds
4-209:when bank gives value for purposes of holder in due course
4-211:media of remittance; provision and final settlement in remittance cases
4-213:final payment of item by payor bank
4-401:when bank may charge customer's account
4-406:customer's duty to discover and report unauthorized signature or alteration
4-402:bank liability to customer for wrongful dishonor
4-407:payor bank's right to subrogation on improper payment
5-111:warranties on transfer and presentment (letters of credit)
5-114:issuer's duty and privilege to honor; right to reimbursement
5-115:remedy for improper dishonor or anticipatory repudiaion (letters of credit)
7-104:negotiable and non-negotiable warehouse receipt, bill of lading, other title
7-204:duty of care; contractual limitation of warehouseperson's liability
7-301:liability for non-receipt or misdescription
7-403:obligation of warehouseperson or carrier to deliver; excuse
7-404:no liability for good faith delivery pursuant to receipt or bill
7-501:form of negotiation and requirements of due negotiation
7-502:rights acquired by due negotiation
7-503:document of title to goods defeated in certain cases
7-504:rights acquired in absence of due negotiation; effect of diversion
7-507:warranties on negotiation or transfer of receipt or bill
7-508:warranties of collecting bank as to documents
9-105:definitions-secured transactions
9-107:definitions "purchase money security interest"
9-109:classification of goods; consumer goods; equipment; farm products; inventory
9-113:security interests arising under article on sales
9-203:attachment and enforceability of security interest; proceeds; formal requisites
9-206:agreement not to asserr defenses against assignee; modification of sales warranties
9-301:persons who take priority over unperfected security interests
9-302:when filing is required to perfect security interest
9-303:when security interest is perfected
9-304:perfection of security interest in instruments, documents
9-305:when possession by secured party perfects security interest without filing
9-306:proceeds; secured party's rights on disposition of collateral
9-307:protection of buyers of goods
9-310:periority of certain liens arising by opration of law (mechanic's liens)
9-311:alienability of debtor's rights; judicial process
9-312:priorities among conflicting security interests in the same collateral
9-405:assignment of security interest
9-501:default; procedure when security agreement covers real and personal property
9-503:secured party's right to take possession after default
9-504:secured party's right to dispose of collateral after default
9-505:compulsory disposition of collateral; acceptance of collateral as discharge of obligation

381
v7/games/wump.c#b00008 Normal file
View File

@ -0,0 +1,381 @@
/*
* wumpus
* stolen from PCC Vol 2 No 1
*/
#include <stdio.h>
#include <stdlib.h>
#define NBAT 3
#define NROOM 20
#define NTUNN 3
#define NPIT 3
struct room
{
int tunn[NTUNN];
int flag;
} room[NROOM];
int rline(void);
int rnum(int n);
int tunnel(int i);
int near(struct room *ap, int ahaz);
int icomp(int *p1, int *p2);
int rin(void);
char *intro[] = {
"\n",
"Welcome to 'Hunt the Wumpus.'\n",
"\n",
"The Wumpus lives in a cave of %d rooms.\n",
"Each room has %d tunnels leading to other rooms.\n",
"\n",
"Hazards:\n",
"\n",
"Bottomless Pits - Some rooms have Bottomless Pits in them.\n",
" If you go there, you fall into the pit and lose!\n",
"Super Bats - Some other rooms have super bats.\n",
" If you go there, a bat will grab you and take you to\n",
" somewhere else in the cave where you could\n",
" fall into a pit or run into the . . .\n",
"\n",
"Wumpus:\n",
"\n",
"The Wumpus is not bothered by the hazards since\n",
"he has sucker feet and is too big for a bat to lift.\n",
"\n",
"Usually he is asleep.\n",
"Two things wake him up:\n",
" your entering his room\n",
" your shooting an arrow anywhere in the cave.\n",
"If the wumpus wakes, he either decides to move one room or\n",
"stay where he was. But if he ends up where you are,\n",
"he eats you up and you lose!\n",
"\n",
"You:\n",
"\n",
"Each turn you may either move or shoot a crooked arrow.\n",
"\n",
"Moving - You can move to one of the adjoining rooms;\n",
" that is, to one that has a tunnel connecting it with\n",
" the room you are in.\n",
"\n",
"Shooting - You have 5 arrows. You lose when you run out.\n",
" Each arrow can go from 1 to 5 rooms.\n",
" You aim by telling the computer\n",
" The arrow's path is a list of room numbers\n",
" telling the arrow which room to go to next.\n",
" The list is terminated with a 0.\n",
" The first room in the path must be connected to the\n",
" room you are in. Each succeeding room must be\n",
" connected to the previous room.\n",
" If there is no tunnel between two of the rooms\n",
" in the arrow's path, the arrow chooses one of the\n",
" three tunnels from the room it's in and goes its\n",
" own way.\n",
"\n",
" If the arrow hits the wumpus, you win!\n",
" If the arrow hits you, you lose!\n",
"\n",
"Warnings:\n",
"\n",
"When you are one or two rooms away from the wumpus,\n",
"the computer says:\n",
" 'I smell a Wumpus'\n",
"When you are one room away from some other hazard, it says:\n",
" Bat - 'Bats nearby'\n",
" Pit - 'I feel a draft'\n",
"\n",
0
};
#define BAT 01
#define PIT 02
#define WUMP 04
int arrow;
int loc;
int wloc;
int tchar;
int main(int argc, char **argv) {
register i, j;
register struct room *p;
int k;
struct room *xx;
k=near(xx, 0); // TEST
printf("Instructions? (y-n) ");
if(rline() == 'y')
for(i=0; intro[i]; i++)
printf(intro[i], i&1? NROOM: NTUNN);
/*
* initialize the room connections
*/
init:
p = &room[0];
for(i=0; i<NROOM; i++) {
for(j=0; j<NTUNN; j++)
p->tunn[j] = -1;
p++;
}
k = 0;
for(i=1; i<NROOM; ) {
j = rnum(NROOM);
p = &room[j];
if(j == k || p->tunn[0] >= 0 || p->tunn[1] >= 0)
continue;
p->tunn[1] = k;
room[k].tunn[0] = j;
k = j;
i++;
}
p = &room[0];
for(i=0; i<NROOM; i++) {
for(j=0; j<NTUNN; j++) {
if(p->tunn[j] < 0)
p->tunn[j] = tunnel(i);
if(p->tunn[j] == i)
goto init;
for(k=0; k<j; k++)
if(p->tunn[j] == p->tunn[k])
goto init;
}
qsort(&p->tunn[0], NTUNN, 2, icomp);
p++;
}
/*
* put in player, wumpus,
* pits and bats
*/
setup:
arrow = 5;
p = &room[0];
for(i=0; i<NROOM; i++) {
p->flag = 0;
p++;
}
for(i=0; i<NPIT; ) {
p = &room[rnum(NROOM)];
if((p->flag&PIT) == 0) {
p->flag |= PIT;
i++;
}
}
for(i=0; i<NBAT; ) {
p = &room[rnum(NROOM)];
if((p->flag&(PIT|BAT)) == 0) {
p->flag |= BAT;
i++;
}
}
i = rnum(NROOM);
wloc = i;
room[i].flag |= WUMP;
for(;;) {
i = rnum(NROOM);
if((room[i].flag&(PIT|BAT|WUMP)) == 0) {
loc = i;
break;
}
}
/*
* main loop of the game
*/
loop:
printf("You are in room %d\n", loc+1);
p = &room[loc];
if(p->flag&PIT) {
printf("You fell into a pit\n");
goto done;
}
if(p->flag&WUMP) {
printf("You were eaten by the wumpus\n");
goto done;
}
if(p->flag&BAT) {
printf("Theres a bat in your room\n");
loc = rnum(NROOM);
goto loop;
}
for(i=0; i<NTUNN; i++)
if(near(&room[p->tunn[i]], WUMP))
goto nearwump;
if (near(p, WUMP)) {
nearwump:
printf("I smell a wumpus\n");
}
if (near(p, BAT))
printf("Bats nearby\n");
if (near(p, PIT))
printf("I feel a draft\n");
printf("There are tunnels to");
for(i=0; i<NTUNN; i++)
printf(" %d", p->tunn[i]+1);
printf("\n");
again:
printf("Move or shoot (m-s) ");
switch(rline()) {
case 'm':
if(tchar == '\n')
printf("which room? ");
i = rin()-1;
for(j=0; j<NTUNN; j++)
if(i == p->tunn[j])
goto groom;
printf("You hit the wall\n");
goto again;
groom:
loc = i;
if(i == wloc)
goto mwump;
goto loop;
case 's':
if(tchar == '\n')
printf("Give list of rooms terminated by 0\n");
for(i=0; i<5; i++) {
j = rin()-1;
if(j == -1)
break;
ranarw:
for(k=0; k<NTUNN; k++)
if(j == p->tunn[k])
goto garow;
j = rnum(NROOM);
goto ranarw;
garow:
p = &room[j];
if(j == loc) {
printf("You shot yourself\n");
goto done;
}
if(p->flag&WUMP) {
printf("You slew the wumpus\n");
goto done;
}
}
if(--arrow == 0) {
printf("That was your last shot\n");
goto done;
}
goto mwump;
}
goto again;
mwump:
p = &room[wloc];
p->flag &= ~WUMP;
i = rnum(NTUNN+1);
if(i != NTUNN)
wloc = p->tunn[i];
room[wloc].flag |= WUMP;
goto loop;
done:
printf("Another game? (y-n) ");
if(rline() == 'y') {
printf("Same room setup? (y-n) ");
if(rline() == 'y')
goto setup;
goto init;
}
}
int tunnel(int i)
{
register struct room *p;
register n, j;
int c;
c = 20;
loop:
n = rnum(NROOM);
if(n == i)
if(--c > 0)
goto loop;
p = &room[n];
for(j=0; j<NTUNN; j++)
if(p->tunn[j] == -1) {
p->tunn[j] = i;
return(n);
}
goto loop;
}
int rline(void)
{
register char c, r;
while((c=getchar()) == ' ');
r = c;
while(c != '\n' && c != ' ') {
if(c == '\0')
exit(0);
c = getchar();
}
tchar = c;
return(r);
}
int rnum(int n) {
static first[2];
if(first[1] == 0) {
time(first);
srand((first[1]*first[0])^first[1]);
}
return((rand()/32768.0) * n);
}
int rin(void)
{
register n, c;
n = 0;
c = getchar();
while(c != '\n' && c != ' ') {
if(c<'0' || c>'9') {
while(c != '\n') {
if(c == 0)
exit(0);
c = getchar();
}
return(0);
}
n = n*10 + c-'0';
c = getchar();
}
return(n);
}
int near(struct room *ap, int ahaz)
{
register struct room *p;
register int haz, i;
p = ap;
haz = ahaz;
for(i=0; i<NTUNN; i++)
if(room[p->tunn[i]].flag & haz)
return (1);
return(0);
}
int icomp(int *p1, int *p2)
{
return(*p1 - *p2);
}

375
v7/games/wump.c.orig#b00008 Normal file
View File

@ -0,0 +1,375 @@
#
/*
* wumpus
* stolen from PCC Vol 2 No 1
*/
#define NBAT 3
#define NROOM 20
#define NTUNN 3
#define NPIT 3
struct room
{
int tunn[NTUNN];
int flag;
} room[NROOM];
char *intro[]
{
"\n",
"Welcome to 'Hunt the Wumpus.'\n",
"\n",
"The Wumpus lives in a cave of %d rooms.\n",
"Each room has %d tunnels leading to other rooms.\n",
"\n",
"Hazards:\n",
"\n",
"Bottomless Pits - Some rooms have Bottomless Pits in them.\n",
" If you go there, you fall into the pit and lose!\n",
"Super Bats - Some other rooms have super bats.\n",
" If you go there, a bat will grab you and take you to\n",
" somewhere else in the cave where you could\n",
" fall into a pit or run into the . . .\n",
"\n",
"Wumpus:\n",
"\n",
"The Wumpus is not bothered by the hazards since\n",
"he has sucker feet and is too big for a bat to lift.\n",
"\n",
"Usually he is asleep.\n",
"Two things wake him up:\n",
" your entering his room\n",
" your shooting an arrow anywhere in the cave.\n",
"If the wumpus wakes, he either decides to move one room or\n",
"stay where he was. But if he ends up where you are,\n",
"he eats you up and you lose!\n",
"\n",
"You:\n",
"\n",
"Each turn you may either move or shoot a crooked arrow.\n",
"\n",
"Moving - You can move to one of the adjoining rooms;\n",
" that is, to one that has a tunnel connecting it with\n",
" the room you are in.\n",
"\n",
"Shooting - You have 5 arrows. You lose when you run out.\n",
" Each arrow can go from 1 to 5 rooms.\n",
" You aim by telling the computer\n",
" The arrow's path is a list of room numbers\n",
" telling the arrow which room to go to next.\n",
" The list is terminated with a 0.\n",
" The first room in the path must be connected to the\n",
" room you are in. Each succeeding room must be\n",
" connected to the previous room.\n",
" If there is no tunnel between two of the rooms\n",
" in the arrow's path, the arrow chooses one of the\n",
" three tunnels from the room it's in and goes its\n",
" own way.\n",
"\n",
" If the arrow hits the wumpus, you win!\n",
" If the arrow hits you, you lose!\n",
"\n",
"Warnings:\n",
"\n",
"When you are one or two rooms away from the wumpus,\n",
"the computer says:\n",
" 'I smell a Wumpus'\n",
"When you are one room away from some other hazard, it says:\n",
" Bat - 'Bats nearby'\n",
" Pit - 'I feel a draft'\n",
"\n",
0,
};
#define BAT 01
#define PIT 02
#define WUMP 04
int arrow;
int loc;
int wloc;
int tchar;
main()
{
register i, j;
register struct room *p;
int k, icomp();
printf("Instructions? (y-n) ");
if(rline() == 'y')
for(i=0; intro[i]; i++)
printf(intro[i], i&1? NROOM: NTUNN);
/*
* initialize the room connections
*/
init:
p = &room[0];
for(i=0; i<NROOM; i++) {
for(j=0; j<NTUNN; j++)
p->tunn[j] = -1;
p++;
}
k = 0;
for(i=1; i<NROOM; ) {
j = rnum(NROOM);
p = &room[j];
if(j == k || p->tunn[0] >= 0 || p->tunn[1] >= 0)
continue;
p->tunn[1] = k;
room[k].tunn[0] = j;
k = j;
i++;
}
p = &room[0];
for(i=0; i<NROOM; i++) {
for(j=0; j<NTUNN; j++) {
if(p->tunn[j] < 0)
p->tunn[j] = tunnel(i);
if(p->tunn[j] == i)
goto init;
for(k=0; k<j; k++)
if(p->tunn[j] == p->tunn[k])
goto init;
}
qsort(&p->tunn[0], NTUNN, 2, icomp);
p++;
}
/*
* put in player, wumpus,
* pits and bats
*/
setup:
arrow = 5;
p = &room[0];
for(i=0; i<NROOM; i++) {
p->flag = 0;
p++;
}
for(i=0; i<NPIT; ) {
p = &room[rnum(NROOM)];
if((p->flag&PIT) == 0) {
p->flag =| PIT;
i++;
}
}
for(i=0; i<NBAT; ) {
p = &room[rnum(NROOM)];
if((p->flag&(PIT|BAT)) == 0) {
p->flag =| BAT;
i++;
}
}
i = rnum(NROOM);
wloc = i;
room[i].flag =| WUMP;
for(;;) {
i = rnum(NROOM);
if((room[i].flag&(PIT|BAT|WUMP)) == 0) {
loc = i;
break;
}
}
/*
* main loop of the game
*/
loop:
printf("You are in room %d\n", loc+1);
p = &room[loc];
if(p->flag&PIT) {
printf("You fell into a pit\n");
goto done;
}
if(p->flag&WUMP) {
printf("You were eaten by the wumpus\n");
goto done;
}
if(p->flag&BAT) {
printf("Theres a bat in your room\n");
loc = rnum(NROOM);
goto loop;
}
for(i=0; i<NTUNN; i++)
if(near(&room[p->tunn[i]], WUMP))
goto nearwump;
if (near(p, WUMP)) {
nearwump:
printf("I smell a wumpus\n");
}
if (near(p, BAT))
printf("Bats nearby\n");
if (near(p, PIT))
printf("I feel a draft\n");
printf("There are tunnels to");
for(i=0; i<NTUNN; i++)
printf(" %d", p->tunn[i]+1);
printf("\n");
again:
printf("Move or shoot (m-s) ");
switch(rline()) {
case 'm':
if(tchar == '\n')
printf("which room? ");
i = rin()-1;
for(j=0; j<NTUNN; j++)
if(i == p->tunn[j])
goto groom;
printf("You hit the wall\n");
goto again;
groom:
loc = i;
if(i == wloc)
goto mwump;
goto loop;
case 's':
if(tchar == '\n')
printf("Give list of rooms terminated by 0\n");
for(i=0; i<5; i++) {
j = rin()-1;
if(j == -1)
break;
ranarw:
for(k=0; k<NTUNN; k++)
if(j == p->tunn[k])
goto garow;
j = rnum(NROOM);
goto ranarw;
garow:
p = &room[j];
if(j == loc) {
printf("You shot yourself\n");
goto done;
}
if(p->flag&WUMP) {
printf("You slew the wumpus\n");
goto done;
}
}
if(--arrow == 0) {
printf("That was your last shot\n");
goto done;
}
goto mwump;
}
goto again;
mwump:
p = &room[wloc];
p->flag =& ~WUMP;
i = rnum(NTUNN+1);
if(i != NTUNN)
wloc = p->tunn[i];
room[wloc].flag =| WUMP;
goto loop;
done:
printf("Another game? (y-n) ");
if(rline() == 'y') {
printf("Same room setup? (y-n) ");
if(rline() == 'y')
goto setup;
goto init;
}
}
tunnel(i)
{
register struct room *p;
register n, j;
int c;
c = 20;
loop:
n = rnum(NROOM);
if(n == i)
if(--c > 0)
goto loop;
p = &room[n];
for(j=0; j<NTUNN; j++)
if(p->tunn[j] == -1) {
p->tunn[j] = i;
return(n);
}
goto loop;
}
rline()
{
register char c, r;
while((c=getchar()) == ' ');
r = c;
while(c != '\n' && c != ' ') {
if(c == '\0')
exit();
c = getchar();
}
tchar = c;
return(r);
}
rnum(n)
{
static first[2];
if(first[1] == 0) {
time(first);
srand((first[1]*first[0])^first[1]);
}
return((rand()/32768.0) * n);
}
rin()
{
register n, c;
n = 0;
c = getchar();
while(c != '\n' && c != ' ') {
if(c<'0' || c>'9') {
while(c != '\n') {
if(c == 0)
exit();
c = getchar();
}
return(0);
}
n = n*10 + c-'0';
c = getchar();
}
return(n);
}
near(ap, ahaz)
struct room *ap;
{
register struct room *p;
register haz, i;
p = ap;
haz = ahaz;
for(i=0; i<NTUNN; i++)
if(room[p->tunn[i]].flag & haz)
return (1);
return(0);
}
icomp(p1, p2)
int *p1, *p2;
{
return(*p1 - *p2);
}