[comp.lang.c] Another Silly programming puzzle....

t-iaind@microsoft.UUCP (Iain Davidson) (04/03/89)

(This is my first BIG post, so if you want to flame, flame low and send away)

   For those still silly over the LAST puzzle/challange.... here's another one.

Puzzle:
  Write a "simple" program to convert rec.humor (rot13) jokes to
    a output readable by human eyes...

Simple rules:
   1) It works.
   2) I can understand it.
   3) Sources in "C", Pascal, MOD-2, Pilot, or csh-source
                  format are acceptable.

Two catagories.
   a) fastest
   b) smallest (least # of characters not including standard_IO includes or
        main(arg,arg) {} code, and  ignoring white space '/n', <SPACE>
        (CR's,LF's,etc) for readablity.

Two levels of difficulty:
  1) using builtin functions of a OS   i.e. ">" "<" for UNIX
  2) using standard file operations of open/close.

  Here's an example 
( not working and NOT tested, only by my limited knowledge of c )


  main()
  {
	char c;

	while((c=getchar()!=EOF)
		if( (('a' < c) && ('z' > c)) || (('A' < c) && ('Z' > c)) ) {
			c=lower(c);
			putchar( (c>'m' : c-13 ? c+13) );
		}
}


(I'll summurize and post results..., good luck and may the gods go with you...)

Iain Davidson, formally of (Bellingham, WA)'s BelAmi! Fame

UUCP: {uucp|uw-beaver}!microsof!t-iaind       (How did he move that "t" ???)
BITNET:  microsof!t-iaind@beaver.cs.washington.edu
    for really smart mailers:  t-iaind@microsoft.BITNET or .CSNET or .UUCP
********** Disclaimer: *********
  My employer and fellow employees will (have, has) disclaim anything I say
past, future, or present......  so there !!!!.... :P
-----------------------------------------------------------------

deven@pawl.rpi.edu (Deven Corzine) (04/03/89)

[rot13 filter]

tr 'a-zA-Z' 'n-za-mN-ZA-M'

[I don't read comp.lang.c, by the way.]

Deven
--
------- shadow@pawl.rpi.edu ------- Deven Thomas Corzine ---------------------
Cogito  shadow@acm.rpi.edu          2346 15th Street            Pi-Rho America
ergo    userfxb6@rpitsmts.bitnet    Troy, NY 12180-2306         (518) 272-5847
sum...     In the immortal words of Socrates:  "I drank what?"     ...I think.

kevin@uts.amdahl.com (Kevin Clague) (04/03/89)

In article <1210@microsoft.UUCP> t-iaind@microsoft.UUCP (Iain Davidson) writes:
>(This is my first BIG post, so if you want to flame, flame low and send away)
>
>   For those still silly over the LAST puzzle/challange.... here's another one.

Please DO NOT post replies to this in comp.sys.amiga.tech.
Try comp.sys.amiga if you must.
-- 
UUCP:  kevin@uts.amdahl.com
  or:  {sun,decwrl,hplabs,pyramid,seismo,oliveb}!amdahl!kevin
DDD:   408-737-5481
USPS:  Amdahl Corp.  M/S 249,  1250 E. Arques Av,  Sunnyvale, CA 94086

[  Any thoughts or opinions which may or may not have been expressed  ]
[  herein are my own.  They are not necessarily those of my employer. ]

rabaeza@watdragon.waterloo.edu (Ricardo A. Baeza-Yates) (04/04/89)

In article <1210@microsoft.UUCP> t-iaind@microsoft.UUCP (Iain Davidson) writes:
>(This is my first BIG post, so if you want to flame, flame low and send away)
>
>   For those still silly over the LAST puzzle/challange.... here's another one.

#include <stdio.h>
#include <ctype.h>

main()
{
int c;

for( ;(c=getchar())!=EOF; putchar(c))
	if( isalpha(c) ) c = (lower(c)>'m') : c-13 ? c+13);
}


-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
rabaeza@watmum.waterloo.{edu,cdn}  519-885-1211 x3497  Ricardo Baeza-Yates
rabaeza@watmum.uwaterloo.ca                            CS Dept., U. Waterloo 
uunet!watmath!watmum!rabaeza                           Waterloo, Ont. N2L3G1

edw@pinot.zehntel.com (Ed Wright) (04/06/89)

In article <1210@microsoft.UUCP> t-iaind@microsoft.UUCP (Iain Davidson) writes:
>(This is my first BIG post, so if you want to flame, flame low and send away)
Noooooo Problem
>   For those still silly over the LAST puzzle/challange.... here's another one.
>
>Puzzle:
>  Write a "simple" program to convert rec.humor (rot13) jokes to
>    a output readable by human eyes...
A new challange ! Thank god
>Simple rules:
>   1) It works.
>   2) I can understand it.
No fair imposing unrealistic restrictions
>   3) Sources in "C", Pascal, MOD-2, Pilot, or csh-source
>                  format are acceptable.
>
>UUCP: {uucp|uw-beaver}!microsof!t-iaind       (How did he move that "t" ???)
>BITNET:  microsof!t-iaind@beaver.cs.washington.edu
:-)
Here are some of my favorites

man tr
man mail
man ceasar

talk root

mail root
subject: How do I do this ?

and of course the ever popular old favorite :-) /bin/rm -F -r *
should fix most rotation problems in your current working directory.

I suppose there is always... naw..... not reading "the book"

I think the best reply to one of these was the guy who a few months
back posted a loverly csh script that was rot 13.

:-)

NOw remember the tricks you have seen here today were done by skilled
proffessionals who do them every day. DO NOT TRY these tricks
at home without close parental supervision.


Ed Wright
     KA9AHQ   sun or ucbvax or varian ! zehntel!edw   edw@zehntel.COM

reeder@reed.UUCP (Doug Reeder) (04/06/89)

program decode(input, output, code, plain);
{decode cypher}

const
  NumTestLines = 10;

type
  lowercase = 'a' ..'z';

var
  coding : array[lowercase] of lowercase;
  LetterSet, LowerCaseSet : set of char;
  code, plain : text;
  print : boolean;

function lookup(c : char) : char;
begin
  if c in LetterSet then begin
    if c in LowerCaseSet then
      lookup := coding[c]
    else
      lookup := coding[chr(ord(c)+32)];
  end
  else
    lookup := c;
end;

procedure WriteCoding(var tf : text);
var ch : char;
begin
  writeln(tf);
  for ch := 'a' to 'z' do write(tf,ch);
  writeln(tf);
  for ch := 'a' to 'z' do write(tf,coding[ch]);
  writeln(tf);
end;

procedure TryRotations(var print : boolean);
var
  ch,response : char;
  rotation,lines : integer;
  continue : boolean;
begin
  rotation := 1;
  print := false;
  continue := true;
  repeat
    for ch := 'a' to 'z' do 
      coding[ch] := chr(((ord(ch)-ord('a') + rotation) mod 26) + ord('a'));
    lines :=0;
    reset(code);
    page(output);
    repeat
      if eoln(code) then begin
        writeln;
        lines := lines + 1;
      end
      else
        write(lookup(code^));
      get(code);
    until (lines = NumTestLines)or eof(code);
    write('Okay?  [y,n,q] '); readln(response);
    if response = 'y' then begin
      continue := false;
      print := true;
      WriteCoding(output);
    end;
    if response = 'q' then begin continue := false; print := false; end;
    rotation := rotation +1;
  until (continue = false) or (rotation = 26);
end;

procedure PrintOut;
begin
    reset(code);
    rewrite(plain);
    repeat
      if eoln(code) then 
        writeln(plain)
      else
        write(plain,lookup(code^));
      get(code);
    until eof(code);
end;


procedure setup;
begin
  LetterSet := ['a'..'z','A'..'Z'];
  LowerCaseSet := ['a'..'z'];
end;

begin {decode}
  setup;
  TryRotations(print);
  if print then PrintOut;
end.


    
-- 
Doug Reeder                         USENET: ...!tektronix!reed!reeder
Institute of Knowledge              BITNET: reeder@reed.BITNET
Jinx                             from ARPA: tektronix!reed!reeder@berkeley.EDU
reeder@knowledge.JINX               Box 971 Reed College,Portland,OR 97202

wechsler@leah.Albany.Edu (Steve Wechsler) (04/07/89)

Please remove rec.humor from this thread!  

Thanks for your cooperation...
-- 
Steve Wechsler                  | Internet: wechsler@leah.albany.edu
Bitnet:   consp01@bingvaxa      |           consp01@bingvaxu.cc.binghamton.edu
Sometimes, late at night, someone gets the urge to pet a small furry animal.
That's where I come in.  My name's Friday.  I carry a badger.

kyle@ritcsh.UUCP (Kyle Saunders) (04/07/89)

In article <1210@microsoft.UUCP>, t-iaind@microsoft.UUCP (Iain Davidson) writes:
> (This is my first BIG post, so if you want to flame, flame low and send away)
> 
>    For those still silly over the LAST puzzle/challange.... here's another one.
> 
> Puzzle:
>   Write a "simple" program to convert rec.humor (rot13) jokes to
>     a output readable by human eyes...
> 

C version: (uses redirection/pipes)

#include <studio.h>

main()
{
	char c;

	while ((c = getchar()) != EOF) {
		if ((c >= 'A') && (c <= 'Z'))
			c = ((c-'A'+13) % 26) + 'A';
		else if ((c >= 'a') && (c <= 'z'))
			c = ((c-'a'+13) % 26) + 'a';
		putchar(c);
	}
}

sh version: (also uses redirection/pipes)

#rot13.sh
#!/bin/sh
tr A-MN-Za-mn-z N-ZA-Mn-za-m


- Kyle Saunders
Computer Science House @ Rochester Institute of Technology
{known.galaxy}!ccicpg!cci632!ritcsh!kyle or kyle%ritcsh@rit.RIT.EDU

dgr0093%ritcv@cs.rit.edu (340 Ok) (04/07/89)

I wasn't going to post this, but decoding rot13 text is much easier than that
last program would indicate. I wrote this a few months ago, and it's a full
text filter, so you can pipe things at it as well as calling it with a 
filename to translate. I find the "text filter guts" very useful for building
other simple text filters.

Of course, "rot13 file | rot13" just types out the original file, so you can be
silly with it, too, if you're so inclined. :)

program rot13;

type
  line = string[120];

var
  buf: line;

  function rot13 (inp:line): line;

  var
    count: integer;

  begin
    for count := 1 to length(inp) do
      case inp[count] of
        'A'..'M', 'a'..'m': inp[count] := chr(ord(inp[count])+13);
        'N'..'Z', 'n'..'z': inp[count] := chr(ord(inp[count])-13)
      end;
    rot13 := inp
  end;

begin
  if paramcount > 0 then begin
    close (input);
    assign (input, paramstr(1));
    {$I-} reset (input); {$I+}
    if ioresult <> 0 then begin
      writeln ('Error opening ',paramstr(1), ' as input: aborting');
      halt
    end
  end;
  repeat
    readln (buf);
    writeln (rot13(buf))
  until eof (input)
end.

-------------------------------------------------------------------
  Dave Rutherford   Michelangelo H. Jones   DGR0093@RITVAX.BITNET
-------------------------------------------------------------------

850347s@aucs.UUCP (Hume Smith) (04/07/89)

reeder@reed.UUCP (Doug Reeder) almost, but not quite, wrote
}- program decode(input, output, code, plain);
}- [ ... ]
}- end.

exactly why i hate pascal - a hundred lines of illegibility instead of the
2 or 3 you'd have in C.

i wonder if i can do this in Lisp...
-- 
Hume Smith	Wolfville  Nova Scotia
BITNET		850347s@Acadia
Internet	850347s%Acadia.BITNET@CUNYVM.CUNY.EDU
UUCP		{uunet|watmath|utai|garfield}!dalcs!aucs!850347s

chris@mimsy.UUCP (Chris Torek) (04/07/89)

In article <1039@cs.rit.edu> dgr0093%ritcv@cs.rit.edu (340 Ok) writes:
>I wasn't going to post this, but decoding rot13 text is much easier than that
>last program would indicate. ...

Not necessarily:

>type
>  line = string[120];
	...
>      case inp[count] of
>        'A'..'M', 'a'..'m': inp[count] := chr(ord(inp[count])+13);
>        'N'..'Z', 'n'..'z': inp[count] := chr(ord(inp[count])-13)
	...
>  if paramcount > 0 then begin
>    close (input);
>    assign (input, paramstr(1));
>    {$I-} reset (input); {$I+}
>    if ioresult <> 0 then begin
	...

`Gee, I tried this program on the IBM% and it failed.  After making
it compile by ripping out the param code, I got really weird output.
Can anyone explain this?' :-)
-----
% that means `370-derivative machine', not `IBM PC'
-----

Hint: it also fails on a Univac 1100 series machine if you run it in
Fieldata mode, rather than ASCII.

It is possible to write this program in portable C (such that it runs
on IBM 370-architecture systems, Fieldata machines, CDC's 6-bit codes,
etc., assuming you can compile under those machines in the first place)
by using the library `is*' routines.  It may be possible to write it
in portable ISO Pascal, but the above is not it.  Indeed, the above
fails miserably on input without newlines.

I guess the moral is: if you post Pascal code to comp.lang.c, look
out! :-)  (I overrode the followup-to line to get this into comp.lang.pascal
rather than comp.lang.c, and put in my own to send followups to
comp.lang.pascal.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris

850347s@aucs.UUCP (Hume Smith) (04/08/89)

850347s@aucs.UUCP (Hume Smith) almost, but not quite, wrote
}- exactly why i hate pascal - a hundred lines of illegibility instead of the
}- 2 or 3 you'd have in C.
}- 
}- i wonder if i can do this in Lisp...

read that carefully, i do mean the 2 or 3 lines of illegibilty :-)

this runs under franz lisp... i recommend compiling it though.
Usage: (rot13 t_filename)

(def alpha<=
  (lambda (&rest x)
    (if (or (null x) (null (cdr x)))
        t
        (and (or(eq (car x) (cadr x)) (alphalessp (car x) (cadr x)))
             (apply 'alpha<= (cdr x))))))

(def rot13
  (lambda (file)
    ((lambda (port)
             (do ((X))
                 ((null (setq X (readc port))))
                 (princ
                  (cond ((or (alpha<= 'a X 'm)
                             (alpha<= 'A X 'M))
                         (ascii (+ (getcharn X 1) 13)))
                        ((or (alpha<= 'n X 'z)
                             (alpha<= 'N X 'Z))
                         (ascii (- (getcharn X 1) 13)))
                        (t X))))
             (close port))
     (infile file))))
--
now: HAS THIS BLEEDIN' ROT13 NONSENSE GONE ON LONG ENOUGH?
-- 
Hume Smith	Wolfville  Nova Scotia
BITNET		850347s@Acadia
Internet	850347s%Acadia.BITNET@CUNYVM.CUNY.EDU
UUCP		{uunet|watmath|utai|garfield}!dalcs!aucs!850347s

rr@sun2.cs.uh.edu (Ravindran Ramachandran) (04/08/89)

In article <1744@aucs.UUCP> 850347s@aucs.UUCP (Hume Smith) writes:
>reeder@reed.UUCP (Doug Reeder) almost, but not quite, wrote
>}- program decode(input, output, code, plain);
>}- [ ... ]
>}- end.
>
>exactly why i hate pascal - a hundred lines of illegibility instead of the
>2 or 3 you'd have in C.
>
>i wonder if i can do this in Lisp...

Write a parallel program to implement this:
Use 27 nodes. Each node is sent the corresponding character, and it outputs
the ROT13ed character. Have a `manager' node to collect all the characters
back together and output it.

 -- Ravi.

Disclaimer: My computer typed this in when I was not looking.

reeder@reed.UUCP (Doug Reeder) (04/09/89)

In article <1744@aucs.UUCP> 850347s@aucs.UUCP (Hume Smith) writes about my
pascal program:
>
>exactly why i hate pascal - a hundred lines of illegibility instead of the
>2 or 3 you'd have in C.

Alert readers will have noticed that my program decodes from an unknown
rotation to plain text, not merely from ROT13, and depends on no compiler
specific features.


-- 
Doug Reeder                         USENET: ...!tektronix!reed!reeder
Institute of Knowledge              BITNET: reeder@reed.BITNET
Jinx                             from ARPA: tektronix!reed!reeder@berkeley.EDU
reeder@knowledge.JINX               Box 971 Reed College,Portland,OR 97202

crew@polya.Stanford.EDU (Roger Crew) (04/10/89)

In article <1751@aucs.UUCP> 850347s@aucs.UUCP (Hume Smith) writes:
>In <850347s@aucs.UUCP> (Hume Smith) almost, but not quite, wrote
>> exactly why i hate pascal - a hundred lines of illegibility instead of the
>> 2 or 3 you'd have in C.
> 
> read that carefully, i do mean the 2 or 3 lines of illegibilty :-)

Three lines of illegibility?  No problem...

main(){
  register b;
  while(~(b=getchar()))
    putchar(1+(('@'^--b&'_')<26?b^="\r\017\r\023\025\027\025\023\035\037\035\023\025"[b%32%13]:b));
}

--
Roger Crew					``Beam Wesley into the sun!''
Usenet:    {arpa gateways, decwrl, uunet, rutgers}!polya.stanford.edu!crew
Internet:  crew@polya.Stanford.EDU

) (04/11/89)

	Well, since so many other people sent their own rot13 decryption 
	programs, here's one I wrote a while back.  This version will let
	you do the usual piping bit as well as working from vi.  It will
	also let you specify source and destination filenames on the command
	line.

#include	<stdio.h>

#ifndef	MSDOS
#include	<sys/file.h>
#else
#include	<fcntl.h>
#include	<sys/types.h>
#include	<sys/stat.h>
#include	<io.h>
#endif

#define		BUFSIZE	1024			/* Buffer I/O to gain speed*/

main(ac,av)
char **av;
{
	char	*c,				/* Pointer to current char */
		tmpbuf[BUFSIZE];		/* I/O buffer		   */
	int	in,				/* Input file handle	   */
		out,				/* Output file handle	   */
		numbytes,			/* Number of bytes read	   */
		i,				/* Generic index	   */
		mode = 0666,			/* File permission mode	   */
		usrmask = 0;			/* File mode mask	   */

	usrmask = umask(usrmask);		/* Get users umask	   */
	umask(usrmask);				/* Reset it to its orig val*/
	mode ^= usrmask;			/* Create file permission  */

	/*
	 * Find out where I/O is coming from/going to.
	 */

	in  = (ac == 1 ? 0 : open(av[1],O_RDONLY));
	out = (ac <  3 ? 1 : open(av[2],O_CREAT|O_TRUNC|O_WRONLY,mode));
	if (in < 0 || out < 0) {
		fprintf(stderr,"%s: File access error\n",*av);
		exit(-1);
	}

	/*
	 * Let's rot away!  (Doesn't that sound morbid?!)
	 */

	while ((numbytes = read(in,tmpbuf,BUFSIZE)) > 0) {
		for (c = tmpbuf, i = 0; i < numbytes ; ++c, ++i) 
			if ((*c >= 'A') && (*c <= 'Z')) 
				*c = ((*c - 'A' + 13) % 26) + 'A';
			else if ((*c >= 'a') && (*c <= 'z'))
				*c = ((*c - 'a' + 13) % 26) + 'a';
		write(out,tmpbuf,numbytes);
	}
	close(in);
	close(out);
	exit(0);
}
-- 
Kevin Hanson		(516) 434-3071	| To know me is to discover how truly
Linotype Co. R & D  Dept.		| 	demented a person can be ;-).
425 Oser Ave.  Hauppauge, NY  11788	|
...!philabs!mergvax			|