From garrett at scriptpro.com Wed Sep 1 13:21:46 2004 From: garrett at scriptpro.com (Garrett Goebel) Date: Wed Sep 1 13:22:06 2004 Subject: [Kc] Perl Quiz of the Week #23 Message-ID: From: Mark Jason Dominus [mailto:mjd@plover.com] Sent: Wednesday, September 01, 2004 11:50 AM To: perl-qotw@plover.com Subject: [Retrieved]Perl Quiz of the Week #23 IMPORTANT: Please do not post solutions, hints, or other spoilers until at least 60 hours after the date of this message. Thanks. IMPORTANT: S'il vous plat, attendez au minimum 60 heures aprs la date de ce message avant de poster solutions, indices ou autres rvlations. Merci. WICHTIG: Bitte schicken Sie keine Lsungen, Tipps oder Hinweise fr diese Aufgabe vor Ablauf von 60 Stunden nach dem Datum dieser Mail. Danke. ---------------------------------------------------------------- Write a program, 'parens', which gets a command line argument, n', which is an integer. The program should print all the properly-balanced strings of parentheses of length 2n. For example, given the argument '3', the program should print these five lines: ((())) (()()) (())() ()(()) ()()() in some order. (The order is not important.) For the argument '1'; the output should be: () and for argument '4', the output should be: (((()))) ((()())) ((())()) ((()))() (()(())) (()()()) (()())() (())(()) (())()() ()((())) ()(()()) ()(())() ()()(()) ()()()() in some order. [ ADMIN: I'm still hoping someone will step forward to write a report about expert quiz #22. - MJD ] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.pm.org/pipermail/kc/attachments/20040901/6afbf9e0/attachment.htm From whatever at davidnicol.com Fri Sep 3 00:44:01 2004 From: whatever at davidnicol.com (david nicol) Date: Fri Sep 3 00:44:08 2004 Subject: [Kc] Perl Quiz of the Week #23 In-Reply-To: References: Message-ID: <1094190241.1518.173.camel@plaza.davidnicol.com> On Wed, 2004-09-01 at 13:21, Garrett Goebel wrote: > From: Mark Jason Dominus [mailto:mjd@plover.com] > Sent: Wednesday, September 01, 2004 11:50 AM > To: perl-qotw@plover.com > Subject: [Retrieved]Perl Quiz of the Week #23 > > > > IMPORTANT: Please do not post solutions, hints, or other spoilers > until at least 60 hours after the date of this message. > Thanks. i've got one. A sorted (perl quiz23.pl 10 | sort | tail ) result is here. This does not constitute a hint or spoiler in any way I can see. [david@plaza perlhacking]$ time perl quiz23.pl 10 > /dev/null real 0m25.162s user 0m25.044s sys 0m0.027s [david@plaza perlhacking]$ perl quiz23.pl 10 | sort | tail ()()()()()()(()(())) ()()()()()()(()()()) ()()()()()()(()())() ()()()()()()(())(()) ()()()()()()(())()() ()()()()()()()((())) ()()()()()()()(()()) ()()()()()()()(())() ()()()()()()()()(()) ()()()()()()()()()() -- david nicol "Someday, everything's going to be different when I paint my masterpiece." From garrett at scriptpro.com Thu Sep 9 08:41:44 2004 From: garrett at scriptpro.com (Garrett Goebel) Date: Thu Sep 9 08:41:55 2004 Subject: [Kc] Perl 'Expert' Quiz of the Week #23 Message-ID: IMPORTANT: Please do not post solutions, hints, or other spoilers until at least 60 hours after the date of this message. Thanks. IMPORTANTE: Por favor, no enviis soluciones, pistas, o cualquier otra cosa que pueda echar a perder la resolucin del problema hasta que hayan pasado por lo menos 60 horas desde el envo de este mensaje. Gracias. WICHTIG: Bitte schicken Sie keine Lsungen, Tipps oder Hinweise fr diese Aufgabe vor Ablauf von 60 Stunden nach dem Datum dieser Mail. Danke. VNIMANIE: Pozhalujsta ne shlite reshenija, nameki na reshenija, i voobshe lyubye podskazki v techenie po krajnej mere 60 chasov ot daty etogo soobshenija. Spasibo. Qing3 Zhu4Yi4: Qing3 Ning2 Deng3Dao4 Jie1Dao4 Ben3 Xin4Xi2 Zhi1Hou4 60 Xiao3Shi2, Zai4 Fa1Biao3 Jie3Da2, Ti2Shi4, Huo4 Qi2Ta1 Hui4 Xie4Lou4 Da2An4 De5 Jian4Yi4. Xie4Xie4. ---------------------------------------------------------------- The aim this fortnight is to write a tetris game -- a problem that should be both fun to write and fun to use. The problem is split into three milestones. Each milestone adds functionality to the game to the point where we can play each other across the internet. #----------------------------------------------------------------------- PRIMARY MILESTONE: Write a single-user tetris game. #----------------------------------------------------------------------- Tetris is a simple graphical game that can be implemented on almost any interface, from a text display to a full-blown three dimensional graphical interface. A game grid is 10 spaces wide and 20 spaces high. Gravity pulls random blocks toward the bottom of the grid until the bottom surface of any portion of the block touches another block or the bottom of the game grid. Gravity pulls blocks downward at a rate starting at one space per second (we'll call that the 'gravity-period'. The player can alter the way the block drops in four ways: - Move left: The player can move the dropping block one space to the left - Move right: The player can move the dropping block one space to the right - Move down: The player can move the dropping block one space down - Rotate: The player can rotate the block clockwise 90 degrees (optionally you may also allow an anti-clockwise rotate) The player is not limited to the number of actions they take in each gravity-period by anything other than the speed of the interface. There are seven block shapes that fall: ## @@ %% *** &&& ++++ $$$ ## @@ %% * & $ Once the block reaches ground-level another gravity-period elapses before it is cemented in place. This allows the player to move the block left or right at the last moment, as shown below. The '#' block is moved: 4|&& | |&& | 3|& ## | |&## | 2|& ## | |&## | 1+----------+ +----------+ ABCDEFGHIJ ABCDEFGHIJ Each time a complete horizonal row in the grid is completed, its contents disappear and the contents of the rows above it drop down to fill the vacated spaces. The example below shows a block landing and completing row 2. One gravity-period later, row 2 has disappeared, and rows 3 and 4 have dropped down one space: 4|&& | | | 3|&## & | |&& | 2|&##++++&&&| |&## & | 1|++++ ++++| |++++ ++++| +----------+ +----------+ ABCDEFGHIJ ABCDEFGHIJ After each 10 complete rows are deleted in this way, the difficulty level increases. Difficulty level $n's gravity-period is (1 / 1.3**($n-1)) seconds. Each completed row scores the user $c * $n where $c is the number of blocks removed at a single time (in the default grid, that would be 10 times the number of rows removed as there are 10 columns). The aim of the game is to successfully place as many blocks as possible before one of the blocks touches the top of the grid. Here's a game that's finished -- you'll note that the top '%' block touches the top of the grid: +----------+ 20| % | 19| %% | 18| % | 17| + | 16| + | 15| + | 14| + | 13| && | 12| & | 11| & | 10| + | 9| + | 8| + | 7| + | 6| & | 5| & | 4| && | 3| ## | 2| ## | 1|++++ | +----------+ ABCDEFGHIJ The player scores one point for each unit of the perimeter of the dropped shape that touches a previously dropped block or the edge of the grid. In the example game below, the '&' block was dropped onto a blank grid and scored 5 points. Then the '$' block was then dropped and scored 3 points: two points for its two contacts with the '&' block and one point for its contact with the bottom of the grid: 4| $ | 3|& $$ | 2|&&&$ | 1+----------+ ABCDEFGHIJ You may choose to use any reasonable interface that you want. It will be interesting to see solutions in ncurses, tk or anything else. (Note that I'll be testing it on MacOS-X and RedHat linux) The interface should show the entire game grid and should also show which block will drop next. Any of the above options can be changed except the block shapes. You can allow users to change the gravity-period or the grid size. However, the defaults are as above. The default action keys should be: Z - left X - right / - down ' - rotate If you have extra time, you may want to implement some of the following extensions to the project: #----------------------------------------------------------------------- EXTENSION 1 Allow two-user game play #----------------------------------------------------------------------- In this version of the quiz you will allow a second user to select which block will drop next. This selection will be from three randomly selected blocks and should be selected using the 1, 2 and 3 keys. These three pieces should be displayed in the interface. Should the second player not select a block before it is needed, one should be selected at random from the three choices. #----------------------------------------------------------------------- EXTENSION 2 Write a split engine/interface tetris game #----------------------------------------------------------------------- In this version of the quiz the interface should be split from the engine. Two interfaces should be able to link to a given engine, one for each player. (Optionally, extra interfaces may connect but only to view the game, not play) The interface should connect to the engine via a network socket. The command set should be standardised so your interface can plug into my engine or vice versa. The client will send the server commands on each keypress: LEFT RIGHT DOWN ROTATE A second client (for player 2) can send: ONE TWO THREE to indicate the selected piece. In the split game (where the two players are using different clients) there is no requirement for player 1 to see the three options given to player 2 until one becomes the 'next block'. The server will send the client diffs of the game board. The following change would be transmitted as: D03 D02 B03#B02# 4|&& | |&& | 3|& ## | |&## | 2|& ## | |&## | 1+----------+ +----------+ ABCDEFGHIJ ABCDEFGHIJ The format of the message string is: ($col,$row,$piece) =~ /([A-J])(\d\d)([\Q#@%*&+$\E])/ #----------------------------------------------------------------------- REFERENCES #----------------------------------------------------------------------- Screenshot of original tetris: http://www.mobygames.com/images/shots/original/1018986079-00.gif History of tetris (from Atari's point of view -- there was a court battle): http://www.atarihq.com/tsr/special/tetrishist.html Javascript Implementation of the game if you've never played it: http://www.js-games.de/eng/games/tetris -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.pm.org/pipermail/kc/attachments/20040909/4f5b59d5/attachment.htm From garrett at scriptpro.com Thu Sep 9 08:42:06 2004 From: garrett at scriptpro.com (Garrett Goebel) Date: Thu Sep 9 09:02:52 2004 Subject: [Kc] Solutions and Discussion for Perl Quiz of the Week #22 (Expert Ed ition) Message-ID: Sample solutions and discussion Perl Quiz of The Week #22 (20040825) Write a program, 'wordladder', which gets two arguments, which are words of the same length, and which constructs and prints a "word ladder" from the first word to the second word. A word ladder from word AAA to word BBB is a sequence of dictionary words such that: 1. the first word in the sequence is word AAA 2. each word in the sequence after the first differs from the previous word in exactly one letter position 3. the last word in the sequence is word BBB For example, given the two words "love" and "hate", the program might print the word ladder: love hove have hate Or it might print: love lave have hate It might also print a longer word ladder, such as love lore lobe robe role rose lose lost most mosh moth math hath hate If the program is unable to find a word ladder, it should print an appropriate error message to the standard error, and exit with a failure status. The program should also accept an optional third argument, which, if specified, is the name of a dictionary file which contains the permissible words. If the third argument is omitted, the program should use a default dictionary. Sample word lists are available from http://perl.plover.com/qotw/words/ --------------------------------------------------- [ MJD: This week's report is a collaboration between three people. Ron Isaacson tested and timed the many solutions and wrote up a timing report. Daniel Martin read over the solutions and analyzed the algorithms used. I selected one sample solution and wrote up an explanation of how it works. My very grateful thanks to Prs. Isaacson and Martin for bailing me out of this one when I bit of far more than I could chew. I now turn you over to Pr. Martin. ] [Daniel Martin] This was a popular quiz, judging by the number of solutions. 23 solutions were submitted from 21 different people. Three solutions weren't tested for one reason or another, leaving 21 solutions to be tested and timed. Many thanks to Ron Isaacson for doing the time-testing. The overall algorithm used by each solution can be classified as follows: - "Expanding circles": 1) Start with just the word AAA as your working set. 2) Find every word which is only one letter different from something in the working set and that hasn't been seen before and make that your new working set. 3) Repeat (2) until BBB is in the working set. This solution can be viewed as Dijkstra's shortest-path algorithm applied to the specifics of this problem. (see http://en.wikipedia.org/wiki/Dijkstra's_algorithm) A variant of this has the circles expanding from both AAA and BBB, and stopping when the two sets intersect. One solution, from Rod Adams, computed each subsequent expanding circle by gathering the words that might be in the next working set and then eliminating those that were not adjacent to something in the previous working set. (It then switched to the more standard version based on an estimate as to which method would be faster) - "workqueue": 1) Place AAA in a queue. 2) Pull a word from the queue and push onto the queue all the adjacent words we haven't seen before. 3) Repeat (2) until BBB is pulled from the queue. (Variation: until BBB is about to be pushed onto the queue) This solution can be viewed as the A* algorithm applied to the specifics of this problem with no estimate of future path length. (see http://en.wikipedia.org/wiki/A-star_search_algorithm) A few people extended this by using a full-blown priority queue, with the priority of a word being (distance from w to BBB) + (length of path to w from AAA) This is the A* algorithm with a distance estimate. As before, there were also bi-directional variants that attacked the path from both ends, stopping when the words seen intersected. Yes, sometimes the classification between "workqueue" and "expanding circles" was a bit of a judgement call about how the code was organized overall. In general if - "depth first": 1) Start at AAA. 2) Pick an adjacent word that hasn't been visited yet. 3) Repeat (2) until you reach BBB or visit everything. If there are no available adjacent words, backtrack. Only two solutions attempted this. Both also sorted the adjacent words so as to first try words closer to BBB. After overall algorithm choice, there were still several other design decisions that could be made. A common source of variation was in how the dictionary was stored. Most solutions used a variation on this design: (code adapted from Colin Meyer's solution) open DICT, '<', $DICT or die "can't open $DICT: $!"; @words = grep length( $_ ) == $SIZE, map { chomp; lc } ; close DICT; for my $w ( @words ) { my @rungs = map { my $c = $w; substr( $c, $_, 1 ) = '_'; $c } 0..($SIZE-1);; push @{ $rung2word{ $_ } }, $w for @rungs; } That is, stored the dictionary as a hash of pattern => wordlist, where "pattern" is the word in question with one character replaced by an '_' (or '?' or '.' or '\0') and "wordlist" is a reference to all words with that pattern. Occasionally, the map word => patternlist would also be recorded. Storing the words in a hash that mapped each word to 1 (or some other value) was also popular. (So that keys %words was used whenever the full list of words was needed) A few stored the dictionary in a single giant array, searching through it with regexps or with Inline::C functions when finding adjacent words. There were also some non-perl solutions submitted: 1 in PIR (Parrot Intermediate Representation - assembly language for Perl 6, sort of), 2 in python, and 1 in scheme. Unfortunately, I have no PIR interpreter and neither of my scheme interpreters was able to handle the submitted scheme solution (guile chokes on the variable name with asterisks in it and mzscheme doesn't know about 'sort'). The python solutions were tested along with the others. Several of the solutions failed to check for certain edge cases. For example, if AAA == BBB, 4 solutions found no path. 3 more solutions found a path only if AAA was adjacent to something (so testing on "transubstantiationalist transubstantiationalist" showed no path for those, but testing "love love" did find a path) Also, some solutions had trouble with very large dictionaries or with long paths. At least one solution made the erroneous assumption that if AAA and BBB differ only in positions 1, 3, and 5, then all the words along the path from AAA to BBB will differ from each other only in positions 1, 3, and 5. This is shown false by the path from "axal" to "utah" in the Web2 dictionary, which among other words passes through "itch". Because of the large number of solutions, I won't go through each one and list the classification. Instead, this chart might be useful: dictionary ->|sig>wordlist|word>1|@DICT search method | | | ================================================== Expanding circles| 0 | 1 | 2 2-dir version | 5 | 0 | 1 -------------------------------------------------- workqueue | 3 | 2 | 0 + distance ver | 2 | 0 | 0 2-dir version | 0 | 1 | 0 -------------------------------------------------- depth first | 0 | 2 | 1 I didn't classify the scheme solution from Greg Bacon, nor the PIR solution from Ingo Blechschmidt. I also did not classify the perl solution sent in by David B., since I was unable to puzzle it out. (I was also unable to test it - it's doing something that eats memory like crazy.) I will note that in general, the depth first solutions all performed very poorly on this quiz, despite two of them coding crucial parts in C. The overall fastest solution was mine, the 2-direction workqueue, though not by much. Ron Isaacson's beautifully-formatted timing report is available at: http://perl.plover.com/qotw/misc/e022/report.html The raw timing data, and the submitted programs, are available at http://perl.plover.com/qotw/misc/e022/ Although the problem merely specified _a_ path from AAA to BBB, many solutions found the shortest path. Therefore, some people speculated on what the "longest shortest path" might be for different word lengths in the different dictionaries. The results can be found in the thread starting here: http://perl.plover.com/~alias/list.cgi?1:mss:2054 ---------------------------------------------------------------- [Mark Dominus] I've decided to use Zed Lopez's program as this week's sample solution. According to Ron Isaacson's report, it's consistently one of the very fastest sumbissions, and it's much shorter than the other comparably fast solutions. Part of that may be due to Zed's use of the Tree::Simple module, which provides functions that manage tree structures: #!/usr/bin/perl use strict; use warnings; use Tree::Simple; And part of it may be due to a somewhat excessively terse coding style, as seen here: my ($start_word, $destination_word, $dictionary_file) = @ARGV; die "You must specify two words of equal length" unless defined $start_word and defined $destination_word and length $start_word == length $destination_word; But on the whole I found the program straightforward and easy to understand. In Daniel Martin's classification, this was an "expanding circles" solution, of the "two directions at once variety". Pr. Lopez's program maintains two working sets of words, and operates on them alternately. On each pass, it finds all the words that are one step removed from the words in the current working set, and replaces the current working set with this new set of words. When it finds a word that is already in the *other* working set, it knows it has found a complete path. $dictionary_file ||= "/usr/share/dict/web2"; open (FH, $dictionary_file) or die "Couldn't open $dictionary_file: $!"; $start_word = lc $start_word; $destination_word = lc $destination_word; my %dict; while () { chomp; $dict{lc $_} = 1 if length $_ == length $start_word and $_ !~ /[^a-zA-Z]/; } close(FH); die "$start_word is not in dictionary" unless exists $dict{$start_word}; die "$destination_word is not in dictionary" unless exists $dict{$destination_word}; The dictionary is the usual Perl implementation of a set, with words as keys, and the values always 1. This code handles the special case if the start word and the end word being the same. Had I thought about it in advance, I might have ruled this out when I posed the problem: print "$start_word\n" and exit if $start_word eq $destination_word; $list and $next_nodes are the main data structures of the program: my ($list, $next_nodes); { my $top = Tree::Simple->new($start_word); my $bottom = Tree::Simple->new($destination_word); $list = [{$start_word => $top}, {$destination_word => $bottom}]; $next_nodes = [[$top],[$bottom]]; } The Tree::Simple objects keep track of tree structures whose roots are labeled with the start and end words; each tree node is labeled with another word. If BBB is in the start-word tree, then a word ladder from the start word to BBB can be found by tracing the path from BBB back to the root. The program's wordchain() function does this: sub word_chain { my $node = shift; my @words; while (1) { push @words, $node->getNodeValue(); last if $node->isRoot; $node = $node->getParent; } return @words; } (->getNodeValue returns the word with which the node is labeled.) $list contains exactly two hashes, one working 'down' from the source word and the other working 'up' from the destination word. Each hash maps words to the Tree::Simple objects that represent them. $next_nodes contains the two 'working sets'. The main loop of the program is: for (my $x = 0; ; $x = !$x) { $next_nodes->[$x] = find_next_nodes($next_nodes->[$x], $x); } The '$x = !$x' is a little obscure; he really means '$x = 1 - $x' here. The main loop alternates between the two working sets, replacing the old working set with the set of words adjacent to it. Calculating this new set of words is the job of find_next_nodes(): sub find_next_nodes { my ($nodes, $x) = @_; my @next_nodes; for my $node (@$nodes) { my $orig_word = $node->getNodeValue(); for (my $i = 0; $i < length $orig_word; $i++) { my $word = $orig_word; for my $char ('a'..'z') { next if $char eq substr $orig_word, $i, 1; substr $word, $i, 1, $char; This last line uses the four-argument form of substr(), which is newish. It was introduced by analogy with the four-argument form of splice(). substr($word, $i, 1, $char) locates the length-1 substring of $word at position $i, just like substr($word, $i, 1), but then replaces this substring with the contents of $char. It is just like >MJD> substr($word, $i, 1) = $char; only faster. The program has just calculated a new word, $word, that is one step removed from some word $orig_word that was in the working set. If this new word is already in the *other* working set, then a complete path has been found: # if word is in other list, we're done success($x ? ($list->[!$x]->{$word}, $node) : ($node, $list->[!$x]->{$word})) if exists $list->[!$x]->{$word}; I would have formatted this differently. I think it's clearer like this: >MJD> success($x ? ($list->[1-$x]->{$word}, $node) >MJD> : ($node, $list->[1-$x]->{$word})) >MJD> if exists $list->[1-$x]->{$word}; The success() function, which we'll see shortly, is responsible for tracing the paths from the common word back to the roots of the two trees, and generating the resulting word ladder. Its arguments are the nodes of the two trees that have the same label, with the node from the top-down tree first. If $x is true (that is, 1) then the current working set is the bottom-up one, so needs to be put second in the argument list of success(). If the program hasn't been succesful, it extends the current tree structure and the new working set: if (exists $dict{$word} and !exists $list->[$x]->{$word}) { my $child = Tree::Simple->new($word); $node->addChild($child); push @next_nodes, $child; $list->[$x]->{$word} = $child; } } } If there were no new words that could be reached from the current node, it is a dead end and is deleted from the tree structure to save memory: prune($node) if $node->isLeaf; } return \@next_nodes; } Here's prune(), which deletes the dead end. After the dead-end node is deleted, prune() checks to see if its parent is now a dead end also: sub prune { my $node = shift; while ($node->isLeaf) { die "No path exists" if $node->isRoot; my $parent = $node->getParent; $parent->removeChild($node); $node = $parent; } } The success() function was called when two nodes were found with the same label, one in each of thee trees. It uses word_chain() to find the word ladders from the common word up to the source word (at $node1) and down to the destination word (at $node2) and appends the two ladders together: sub success { my ($node1, $node2) = @_; print join "\n", (reverse word_chain($node1)), word_chain($node2), ''; exit; } The function avoids listing the common word twice because the common word is never added to the second tree. One of the arguments to success() is the node containing the common word; the other is the node in the other tree that would have been adjacent to the common-word node. Once again, thanks to everyone who participated by sending a solution or adding to the discusion, and thanks also to everyone who participated *without* sending a solution or adding to the discussion. Thanks especially to Ron Isaacson and Daniel Martin. John Trammell is working hard on the writeup of last week's parenthesis-generating quiz; I will send that along when it is ready. I hope to send out the new quiz tonight. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.pm.org/pipermail/kc/attachments/20040909/e8dc3477/attachment-0001.htm From garrett at scriptpro.com Wed Sep 15 13:47:55 2004 From: garrett at scriptpro.com (Garrett Goebel) Date: Wed Sep 15 13:48:03 2004 Subject: [Kc] Perl Quiz of the Week #24 (Turing Machine simulation) Message-ID: From: mjd@plover.com [mailto:mjd@plover.com] On Behalf Of Zed Lopez Sent: Wednesday, September 15, 2004 9:01 AM To: perl-qotw@plover.com Subject: [Retrieved]Perl Quiz of the Week #24 (Turing Machine simulation) IMPORTANT: Please do not post solutions, hints, or other spoilers until at least 60 hours after the date of this message. Thanks. WICHTIG: Bitte schicken Sie keine Lsungen, Tipps oder Hinweise fr diese Aufgabe vor Ablauf von 60 Stunden nach dem Datum dieser Mail. Danke. BELANGRIJK: Stuur aub geen oplossingen, hints of andere tips in de eerste 60 uur na het verzendingstijdstip van dit bericht. Waarvoor dank. VNIMANIE: Pozhalujsta ne shlite reshenija, nameki na reshenija, i voobshe lyubye podskazki v techenie po krajnej mere 60 chasov ot daty etogo soobshenija. Spasibo. UWAGA: Prosimy nie publikowac rozwiazan, dodatkowych badz pomocniczych informacjii przez co najmniej 60 godzin od daty tej wiadomosci. Dziekuje. ---------------------------------------------------------------- When computer scientists want to study what is computable, they need a model of computation that is simpler than real computers are. One model they use is called a "Turing Machine". A Turing Machine has three parts: 1. One state register which can hold a single number, called the state; the state register has a maximum size specified in advance. 2. An infinite tape of memory cells, each of which can hold a single character, and a read-write head that examines a single square at any given time. 3. A finite program, which is just a big table. For any possible number N in the register, and any character in the currently-scanned memory cell, the table says to do three things: It has a number to put into the register, replacing what was there before,; it has a new character to write into the current memory cell, replacing what was there before, and it has an instruction to the read-write head to move one space left or one space right. This may not seem like a very reasonable model of computation, but computer scientists have exhibited Turing machines that can do all the things you usually want computers to be able to do, such as performing arithmetic computations and running interpreter programs that simulate the behavior of other computers. They've also showed that a lot of obvious `improvements' to the Turing machine model, such as adding more memory tapes, random-access memory, more read-write heads, more registers, or whatever, don't actually add any power at all; anything that could be computed by such an extended machine could also have been computed by the original machine, although perhaps more slowly. Finally, a lot of other totally different models for computation turn out to be equivalent in power to the Turing machine model. Each of these models has some feature about it that suggests that it really does correspond well to our intuitive idea of what is computable. For example, the lambda calculus, a simple model of funbction construction and invocation, turns out to be able to compute everything that can be computed by Turing Machines, and nothing more. Random-access machines, which have a random-access addressible memory like an ordinary computer, also turn out to be able to compute everything that can be computed by Turing Machines, and nothing more. So there is a lot of evidence that the Turing Machine, limited though is appears, actually does capture our intuitive notion of what it means for something to be computable. For the Regular Quiz of the Week 24, we'll implement a Turing Machine. Let's say that the tape will only hold Perl "word" characters, A-Z a-z 0-9 _ And let's also say that we can give symbolic names of the form /\w+/ to the values that can be stored in the state register. Then a Turing Machine's program will be a list of instructions that look like this: SomeState 1 OtherState 0 L This means that if the Turing Machine's state register contains "SomeState", and there's a 1 in the tape square under the read/write head, it should replace the 1 with a 0, move the read/write head to the left (by one space -- it can only move one space at a time), and store "OtherState" in the state register. '#' will introduce comments, so this instruction is the same: SomeState 1 OtherState 0 L # flip-flop There is one of these state transition instructions per line. The five required elements in each instruction (old state, old tape symbol, new state, new tape symbol, and read/write head motion) are separated by one or more whitespace characters. States' labels are made of word characters. The current symbol and new symbol can be any word character (as specified in the definition of finite alphabet, above.) Blank lines or lines consisting only of a comment are acceptable, and are ignored. Your program should take two parameters: the filename of a file containing the state transition instructions, and the tape's initial contents. The filename is required. The tape is assumed to be filled with '_' characters forever in both directions on either side of the specified initial value, so an initial value argument of "123_456abc" really means "...______123_456abc______...". If the initial tape argument is omitted, the tape is assumed to be full of "_" symbols. The "_" symbols are called "blanks". If an initial value for the tape is specified, the read/write head begins over the first character of that initial value. In the example above, the read/write head is initially positioned over the "1" symbol. If no tape is specified, then the read/write head begins over one of the blanks (which, conceptually, could be any location on the tape.) Please note that the read/write head _can_ move to the left of its initial position, as the tape extends an arbitrary length in both directions. The Turing Machine's initial state is the first state mentioned in the state transition instructions (i.e. the current state defined on the first instruction line.) If, for a given state and current symbol under the read/write head, the Turing Machine does not have any instructions specified in the state transition table, it halts, and your program should print out the tape from the first non-blank character to the last non-blank character, and exit. Your program should die with an error message if it encounters a badly formatted line in the state transition instruction file. EXAMPLES: If binary_incr.tm contains: s0 1 s0 1 R # Seek right to the end of the numeral s0 0 s0 0 R s0 _ s1 _ L s1 1 s1 0 L # Scan left, changing 1s to 0's s1 0 s2 1 L # Until you find the rightmost 0 s1 _ s2 1 L # or fall off the left end of the numeral s2 1 s2 1 L # Seek left to the left end of the numeral s2 0 s2 0 L s2 _ s3 _ R # ... and then stop and your program is in tm.pl, then the output of tm.pl binary_incr.tm 0011001 should be: 0011010 (This state transition table implements incrementing a binary string by 1.) If helloworld.tm contains: s0 _ s1 h R s1 _ s2 e R s2 _ s3 l R s3 _ s4 1 R s4 _ s5 o R s5 _ s6 _ R s6 _ s7 w R s7 _ s8 o R s8 _ s9 r R s9 _ s10 l R s10 _ s11 d R then tm.pl helloworld.tm should output: hello_world if multiply.tm contains: start 1 move1right W R # mark first bit of 1st argument move1right 1 move1right 1 R # move right til past 1st argument move1right _ mark2start _ R # square between 1st and 2nd arguments found mark2start 1 move2right Y R # mark first bit of 2nd argument move2right 1 move2right 1 R # move right til past 2nd argument move2right _ initialize _ R # square between 2nd argument and answer found initialize _ backup 1 L # put a 1 at start of answer backup _ backup _ L # move back to leftmost unused bit of 1st arg backup 1 backup 1 L # ditto backup Z backup Z L # ditto backup Y backup Y L # ditto backup X nextpass X R # in position to start next pass backup W nextpass W R # ditto nextpass _ finishup _ R # if square is blank we're done. finish up nextpass 1 findarg2 X R # if square is not blank go to work. mark bit findarg2 1 findarg2 1 R # move past 1st argument findarg2 _ findarg2 _ R # square between 1st and 2nd arguments findarg2 Y testarg2 Y R # start of 2nd arg. skip this bit copy rest testarg2 _ cleanup2 _ L # if blank we are done with this pass testarg2 1 findans Z R # if not increment ans. mark bit move there findans 1 findans 1 R # still in 2nd argument findans _ atans _ R # square between 2nd argument and answer atans 1 atans 1 R # move through answer atans _ backarg2 1 L # at end of answer__write a 1 here go back backarg2 1 backarg2 1 L # move left to first unused bit of 2nd arg backarg2 _ backarg2 _ L # ditto backarg2 Z testarg2 Z R # just past it. move right and test it backarg2 Y testarg2 Y R # ditto cleanup2 1 cleanup2 1 L # move back through answer cleanup2 _ cleanup2 _ L # square between 2nd arg and answer cleanup2 Z cleanup2 1 L # restore bits of 2nd argument cleanup2 Y backup Y L # done with that. backup to start next pass finishup Y finishup 1 L # restore first bit of 2nd argument finishup _ finishup _ L # 2nd argument restored move back to 1st finishup X finishup 1 L # restore bits of 1st argument finishup W almostdone 1 L # restore first bit of 1st arg. almost done almostdone _ halt _ R # done with work. position properly and halt then tm.pl multiply.tm 1111_11111 should output: 1111_11111_1111111111111 This program implements multiplication where a quantity n is represented by n+1 1's. So the example above passes it 3 and 4, and the program writes the result, 12, represented as 13 1's, to the end of the tape. REFERENCES Turing Machines were first described by Alan Turing in his 1936 paper, "On Computable Numbers, with an Application to the Entscheidungsproblem [decision-making problem]": http://www.abelard.org/turpap2/tp2-ie.asp -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.pm.org/pipermail/kc/attachments/20040915/e14f31d4/attachment-0001.htm From marsee at oreilly.com Thu Sep 16 20:07:53 2004 From: marsee at oreilly.com (Marsee Henon) Date: Thu Sep 16 20:08:03 2004 Subject: [Kc] Newsletter from O'Reilly UG Program, September 16 Message-ID: ================================================================ O'Reilly UG Program News--Just for User Group Leaders September 16, 2004 ================================================================ -O'Reilly User Group Program in Germany -Want to speak to user groups? -Put Up an O'Reilly Mac OS X Conference Banner, Get a Free Book ---------------------------------------------------------------- Book Info ---------------------------------------------------------------- ***Review books are available Copies of our books are available for your members to review-- send me an email and please include the book's ISBN number on your request. Let me know if you need your book by a certain date. Allow at least four weeks for shipping. ***Please send copies of your book reviews Email me a copy of your newsletters or book reviews. For tips and suggestions on writing book reviews, go to: http://ug.oreilly.com/bookreviews.html ***Discount information Don't forget to remind your members about our 20% discount on O'Reilly, No Starch, Paraglyph, Pragmatic Bookshelf, SitePoint, and Syngress books and O'Reilly conferences. Just use code DSUG. ***Group purchases with better discounts are available Please let me know if you are interested and I can put you in touch with our sales department. ---------------------------------------------------------------- General News ---------------------------------------------------------------- ***O'Reilly User Group Program in Germany We are pleased to announce we now have a User Group program in Germany. German-speaking User Groups can now belong to both our US and German programs. For more information or to sign up, go to: http://www.oreilly.de/ug/ ***Want to speak to user groups? If you or someone you know are looking for groups to speak to make sure you add your name here. You don't have to be affiliated with O'Reilly to be on the list. http://wiki.oreillynet.com/usergroups/mt.cgi?SpeakersLookingforUGs ***Put Up an O'Reilly Mac OS X Conference Banner, Get a Free Book We are looking for user groups to display our conference banner on their web sites. If you send me the link to your user group site with our O'Reilly Mac OS X Conference banner, I will send you the O'Reilly book of your choice. O'Reilly Mac OS X Conference Banners: http://ug.oreilly.com/banners/macosx2004/ ================================================================ O'Reilly News for User Group Members September 16, 2004 ================================================================ ---------------------------------------------------------------- Book News ---------------------------------------------------------------- -iLife: The Missing Manual -The Mezonic Agenda: Hacking the Presidency -sendmail 8.13 Companion -PayPal Hacks -Camera Phone Obsession -Linux iptables Pocket Reference -ASP.NET Cookbook -Building the Perfect PC -NUnit Pocket Reference -Head First Servlets & JSP -Oracle Initialization Parameters Pocket Reference -Oracle Application Server 10g Essentials ---------------------------------------------------------------- Upcoming Events ---------------------------------------------------------------- -Digital Lifestyle Expo, New York, NY--September 25-26 -Richard Thieme Visiting Bookstores in WI and IL--September 27-October 2 -Northern California Independent Bookseller's Association Fall Trade Show --October 1-3 -O'Reilly Authors at Windows Connections 2004--October 24-27 ---------------------------------------------------------------- Conference News ---------------------------------------------------------------- -Early-Bird Deadline Extended -Call for Participation: O'Reilly Emerging Technology Conference ---------------------------------------------------------------- News ---------------------------------------------------------------- -Study Shows Safari Saves Time -A Conversation Between Dan Gillmor and Jay Rosen -Fiddling with Nero 6 Ultra Edition -O'Reilly Launches Digital Media Web Site -Tasteful Food Photography -Machinima: Filmmaking's Destiny -Linux/Unix SysAdmin Certification Special Offer for September -The Best Tips from the Great Linux Desktop Migration Contest -More Inside News on O'Reilly's Mac OS X Conference -Acrobat to a Paperless Office -Mac OS X for the Traveler -Site Surveys--Windows DevCenter & ONDotnet -Lightweight XML Editing in Word 2003 -Site Navigation in ASP.NET 2.0 -IRC Text to Speech with Java -Developing Your First Enterprise Beans, Part 1 ================================================ Book News ================================================ Did you know you can request a free book to review for your group? Ask your group leader for more information. For book review writing tips and suggestions, go to: http://ug.oreilly.com/bookreviews.html Don't forget, you can receive 20% off any O'Reilly, No Starch, Paraglyph, Pragmatic Bookshelf, SitePoint, or Syngress book you purchase directly from O'Reilly. Just use code DSUG when ordering online or by phone 800-998-9938. http://www.oreilly.com/ ***Free ground shipping is available for online orders of at least $29.95 that go to a single U.S. address. This offer applies to U.S. delivery addresses in the 50 states and Puerto Rico. For more details, go to: http://www.oreilly.com/news/freeshipping_0703.html ---------------------------------------------------------------- New Releases ---------------------------------------------------------------- ***iLife: The Missing Manual Publisher: O'Reilly ISBN: 0596006942 "iLife: The Missing Manual" gives you everything you need to unleash your creative genius with iLife '04, Apple's suite of five programs--iTunes 4.6, iPhoto 4, iMovie 4, iDVD 4, and GarageBand--that's revolutionizing the way we work and play. Celebrated author David Pogue makes sure there's nothing standing between you and professional-caliber music, photos, movies, and more. He highlights the newest features and improvements, covers the capabilities and limitations of each program, and delivers countless goodies you won't find anywhere else: undocumented tips, tricks, and secrets for getting the very best performance out of every one of these applications. http://www.oreilly.com/catalog/ilifetmm/ ***The Mezonic Agenda: Hacking the Presidency Publisher: Syngress ISBN: 1931836833 The Mezonic Agenda: Hacking the Presidency is the first cyber-thriller that allows readers to "hack along" with the heroes and villians of this fictional narrative. It tells the tale of criminal hackers attempting to compromise the results of a U.S. presidential election for their own gain. The book deals with some of the most pressing topics in technology and computer security today--reverse engineering, cryptography, buffer overflows, and steganography--and includes a CD that contains real, working versions of all the applications described and exploited in this thriller. http://www.oreilly.com/catalog/1931836833/ Hack along at www.mezonicagenda.com ***sendmail 8.13 Companion Publisher: O'Reilly ISBN: 0596008457 For a simple dot release, V8.13 sendmail has added more features, options, and fundamental changes than any other single dot release to date. An excellent companion to our popular "sendmail, 3rd Edition," this book documents the improvements in V8.13 in parallel with its release. Highlighting important changes in the new version, the book points out not only what is handy or nice to have, but also what's critical in getting the best behavior from sendmail. http://www.oreilly.com/catalog/sendmailcomp/ Chapter 3, "Tune sendmail with Compile-Time Macros," is available online: http://www.oreilly.com/catalog/sendmailcomp/chapter/index.html ***PayPal Hacks Publisher: O'Reilly ISBN: 0596007515 Learn how to make the most of PayPal to get the most out of your online business or transactions. Presented in a clear and logical format, each hack consists of a task to accomplish or a creative solution to a problem. You'll learn everything from how to protect yourself while buying and selling on eBay, to how to handle online subscriptions, affiliations, and donations. This collection of tips and tricks provides the tools and details necessary to make PayPal more profitable, more flexible, and more convenient. http://www.oreilly.com/catalog/payhks/index.html Sample hacks are available online: http://www.oreilly.com/catalog/payhks/chapter/index.html ***Camera Phone Obsession Publisher: Paraglyph Press ISBN: 1932111964 "Camera Phone Obsession" is a unique guide that marries the technology of camera phones with the emerging culture. Author Peter Aitken shows you how to purchase the best camera phones, how to best shoot and print photos, what the best services are for sharing photos, and how to use your camera phones with your PCs. http://www.oreilly.com/catalog/1932111964/ ***Linux iptables Pocket Reference Publisher: O'Reilly ISBN: 0596005695 "Linux iptables Pocket Reference" will help you at those critical moments when you have to open or close a port in a hurry to enable important traffic or block an attack. The book helps you keep the subtle syntax straight and remember all the values you have to enter to be as secure as possible. Listings of all iptables options are organized by suitability for firewalling, accounting, and Network Address Translation (NAT). This unique quick reference format is ideal for Linux administrators who have a firewall in place but need to be prepared for frequent changes in their environment. http://www.oreilly.com/catalog/lnxiptablespr/ ***ASP.NET Cookbook Publisher: O'Reilly ISBN: 0596003781 ASP.NET brings rapid drag-and-drop productivity to web applications and web services. There are many benefits to using ASP.NET, and one major drawback: the time developers must devote to mastering this new web application technology. "ASP.NET Cookbook" provides a wealth of solutions to problems commonly encountered when developing in ASP.NET. Appealing to a wide range of developers, each recipe provides an immediate solution to a pressing problem, followed by discussion so developers can learn to adapt techniques to similar situations. http://www.oreilly.com/catalog/aspnetckbk/ Chapter 12, "Dynamic Images," is available online: http://www.oreilly.com/catalog/aspnetckbk/chapter/index.html ***Building the Perfect PC Publisher: O'Reilly ISBN: 0596006632 For many computer users, a ready-made system is about as satisfying as a frozen microwave dinner: sure, it works, but it's not exactly what you need or want. Don't accept the assortment of components bundled for your price point; build your own PC. With straight-forward language, clear end-to-end instructions, and extensive illustrations, this book covers a variety of complete systems and their components. Regardless of your experience, you can take control and create your ideal machine. Chapter 1, "Fundamentals," is available online: http://www.oreilly.com/catalog/buildpc/chapter/index.html ***NUnit Pocket Reference Publisher: O'Reilly ISBN: 0596007396 "NUnit Pocket Reference" is a complete reference to this popular and practical new open source framework. Filling in the blanks left by existing documentation and online discussion, this little book offers developers everything they need to know to install, configure, and use NUnit and the NUnit user interface. It includes a reference to the NUnit framework classes, and offers practical, real-world "NUnit examples." With NUnit Pocket Reference, IT managers will know what to expect when they implement unit testing in their projects. http://www.oreilly.com/catalog/nunitpr/ A sample excerpt, "Unit Testing with NUnit," is available online: http://www.oreilly.com/catalog/nunitpr/chapter/index.html ***Head First Servlets & JSP Publisher: O'Reilly ISBN: 0596005407 "Head First Servlets & JSP" will help you truly understand the latest version, J2EE 1.4, of Servlets and JSP. You'll learn how to write servlets and JSPs, what makes the Container tick, how to use the new JSP Expression Language (EL), and even some server-side design patterns. Written by the creators of the Sun Certified Web Component Developer (SCWCD) 1.4 exam, this book will help you pass the exam, talk about Struts at dinner parties, and put Servlets and JSP to work right away. http://www.oreilly.com/catalog/headservletsjsp/ ***Oracle Initialization Parameters Pocket Reference Publisher: O'Reilly ISBN: 0596007701 "Oracle Initialization Parameters Pocket Reference" provides the information Oracle DBAs need to keep databases operating at peak performance. The book describes each initialization parameter, including what category it's in--from auditing to multi-threaded server MTS--and whether it can be modified dynamically via the ALTER SESSION or ALTER SYSTEM commands. You'll also find performance tips, such as how the various parameters interact and optimal settings for different configurations. No other reference focuses exclusively on these initialization parameters; this book is an absolute must for anyone working with an Oracle database. http://www.oreilly.com/catalog/oracleippr/ ***Excel 2003 Programming: A Developer's Notebook Publisher: O'Reilly ISBN: 0596007671 Light on theory and heavy on practical application, this guide takes intermediate to advanced Excel VBA programmers directly to Excel 2003's new features. With the help of dozens of practical labs, you'll learn to work with lists and XML data, secure Excel applications, use Visual Studio Tools for Office, consume Web Services, and collect data with Infopath. If you'd like to work with Excel 2003 but don't know where to start, this book is the solution. http://www.oreilly.com/catalog/exceladn/ Chapter 2, "Share Workspaces and Lists," is available online: http://www.oreilly.com/catalog/exceladn/chapter/index.html ***Oracle Application Server 10g Essentials Publisher: O'Reilly ISBN: 0596006217 "Oracle Application Server 10g Essentials" is a tightly focused, all-in-one technical overview for Oracle Application Server users of every level. Divided into three concise sections, the book covers server basics, core components, and server functionality. If you're concerned with using and managing web servers, doing Java development and deployment, using or developing for Oracle Portal, or using and administering business intelligence and mobile or integration software, this guide will provide a foundation for understanding and using OracleAS effectively and efficiently. http://www.oreilly.com/catalog/appserver/ Chapter 2, "Architecture," is available online: http://www.oreilly.com/catalog/appserver/chapter/index.html ================================================ Upcoming Events ================================================ ***For more events, please see: http://events.oreilly.com/ ***Digital Lifestyle Expo, New York, NY--September 25-26 Author and Mac guru David Pogue (Missing Manual Series) is a keynote speaker at this event. Marriott Marquis Hotel New York, NY http://www.dlexpo.com/ ***Richard Thieme Visiting Bookstores in WI and IL--September 27- October 2 Richard is author of "Islands in the Clickstream" (Syngress) and is one of the most visible commentators on technology and society, appearing regularly on CNN, TechTV, and various other national media outlets. Schwartz Bookshops--7pm, September 27 4093 North Oakland Avenue, Shorewood, WI 53211 Transitions Bookplace--7pm, September 28 1000 W. North Avenue Chicago, IL 60622 Bookworld--October 1 & 2 Friday, October 1 from 4-7:30 Saturday, October 2 9AM to noon 320 Watson Street Ripon, WI 54971 For more information on Richard Thieme, go to: http://www.thiemeworks.com/ ***Northern California Independent Bookseller's Association Fall Trade Show--October 1-3 If you're going, be sure to stop by our booth, say "hey," and peruse our wares. Oakland Convention Center Oakland, CA http://www.nciba.com/tradeshow2004.html ***O'Reilly Authors at Windows Connections 2004--October 24-27 Authors Robbie Allen ("DNS on Windows Server 2003" & "Active Directory Cookbook"), Mike Danseglio ("Securing Windows Server 2003"), and Roger Grimes ("Malicious Mobile Code") are featured speakers at this event. Hyatt Grand Cypress Orlando, FL http://www.winconnections.com/devconnections/win/defaultfall2004.asp ================================================ Conference News ================================================ ***Early-Bird Deadline Extended The O'Reilly Mac OS X Conference is October 25-28. This conference brings together what you need to know and what you want to experience. You'll learn how to solve the day in-day out problems of connected computing, leverage the power of scripting, improve the performance of your network, and protect your systems from intrusion. You'll also get up to speed on grid computing, home automation, streaming media, how to build your own TV studio, and much more. User Group members who register before September 20, 2004 get a double discount. Use code DSUG when you register, and receive 20% off the "Early Bird" price. To register, go to: http://conferences.oreillynet.com/cs/macosx2004/create/ord_mac04 O'Reilly Mac OS X Conference October 25-28, 2004 Westin Santa Clara, Santa Clara, CA http://conferences.oreilly.com/macosxcon/ ***Call for Participation: O'Reilly Emerging Technology Conference What alpha geeks do today can radically alter the future of technology for everyone tomorrow. O'Reilly's Emerging Technology Conference (ETech) frames the ideas, projects, and technologies that the alpha geeks are thinking about, hacking on, and inventing right now into a coherent picture that we can build upon. If you've got your eye on nascent technological transformations, send us a proposal (due September 27), and join us in San Diego, California March 14-17 for ETech 2005. http://conferences.oreillynet.com/cs/et2005/create/e_sess O'Reilly Emerging Technology Conference March 14-17, 2005 Westin Horton Plaza, San Diego, California http://conferences.oreilly.com/etech/ ================================================ News From O'Reilly & Beyond ================================================ --------------------- General News --------------------- ***Study Shows Safari Saves Time A recent study by The Ridge Group of Princeton, New Jersey found that Safari Bookshelf delivers savings of about 24 times its cost. The group found that without the use of an Electronic Reference Library (ERL), the typical technology professional spends an average of 31 hours per month looking for answers, researching issues, and helping colleagues do the same. Safari subscribers, however, report an average of 13.5 hours saved per month--nearly half the amount of time lost by people who don't subscribe. Test it out: oreilly.com/go/safari-ug ***A Conversation Between Dan Gillmor and Jay Rosen Jay Rosen talks to Dan Gillmor about the current state of journalism and the impact technology is having on traditional media. For a full expose on the deep shift in how we make and consume the news, see Dan's recently released "We the Media." http://www.oreillynet.com/pub/a/network/2004/09/14/gillmor.html ***Fiddling with Nero 6 Ultra Edition Wallace Wang, author of "The Book of Nero" writes a review of the latest version of Nero for Computing Unplugged. http://www.computingunplugged.com/issues/issue200408/00001349001.html --------------------- Digital Media --------------------- ***O'Reilly Launches Digital Media Web Site To inspire digital media users to new heights of creativity and expertise, we've unveiled our new Digital Media Web Site: http://digitalmedia.oreilly.com/ For more information check out Derrick Story's blog "Doing Digital Media Right": http://www.oreillynet.com/pub/wlg/5487 Or the official Digital Media Web Site press release: http://press.oreilly.com/pub/pr/1221 ***Tasteful Food Photography Food photography traditionally has been the realm of a handful of weathered professionals. So for the casual shooter or even the ambitious amateur, getting great food shots can seem like an intimidating and daunting task at best. But it doesn't have to be that way. http://digitalmedia.oreilly.com/2004/09/15/food_photos.html ***Machinima: Filmmaking's Destiny Machinima is filmmaking redefined--a merging of three creative mediums: filmmaking, animation, and 3D game technology. Think animated filmmaking within a real-time 3D virtual environment. Here's a guided tour from Paul Marion, author of Paraglyph's recently released "3D Game-Based Filmmaking: The Art of Machinima." http://digitalmedia.oreilly.com/2004/09/08/machinima.html --------------------- Open Source --------------------- ***Linux/Unix SysAdmin Certification Special Offer for September Learn how to administer Linux/Unix systems and gain real experience with a root access account. This four-course series from the O'Reilly Learning Lab covers the Unix file system, networking, Unix services, and scripting. Upon completion of the series, you'll get a Certificate for Professional Development from the University of Illinois. And this month, when you enroll in three of the online courses, you get the fourth free. http://oreilly.useractive.com/courses/sysadmin.php3 Find out more about the O'Reilly Learning Lab go to: http://learninglab.oreilly.com ***The Best Tips from the Great Linux Desktop Migration Contest What's the best way to move an organization to a Linux desktop? Here's a collection of the best tips we received from our Great Linux Desktop Migration contest. http://www.linuxdevcenter.com/pub/a/linux/2004/09/10/migrationtips.html --------------------- Mac --------------------- ***More Inside News on O'Reilly's Mac OS X Conference We've added top-level Apple-employed speakers to the conference faculty. And yes, some have been approved to talk about Tiger. Here's the latest inside scoop on the upcoming Mac OS X event. http://www.macdevcenter.com/pub/a/mac/2004/09/16/osx_conf.html ***Acrobat to a Paperless Office Adobe Acrobat is an excellent program for document distribution. Most users are familiar with the freely available Acrobat Reader, allowing anyone to view PDF documents. The full-blown version of Acrobat offers a range of tools to manage document distribution beyond just converting other formats to PDF. Julie Starr shows you how to use these tools to design the paperless office. http://www.macdevcenter.com/pub/a/mac/2004/09/14/pdf.html ***Mac OS X for the Traveler In this ongoing series about traveling safely with your PowerBook or iBook, you'll learn that preparation is one of the keys to peace of mind. F.J. helps you get your equipment in order. Part One: http://www.macdevcenter.com/pub/a/mac/2004/08/31/traveller.html Part Two: http://www.macdevcenter.com/pub/a/mac/2004/09/03/traveller.html Part Three: http://www.macdevcenter.com/pub/a/mac/2004/09/10/traveller.html --------------------- Windows --------------------- ***Site Surveys--Windows DevCenter & ONDotnet We're asking our readers to participate in a couple of online surveys: the Windows DevCenter Survey and the ONDotnet Survey. This is your opportunity to help shape our online editorial direction and influence which book titles we pursue. You'll also have a chance to win some of our most popular Windows or .NET books. Windows DevCenter Survey: http://www.zoomerang.com/recipient/survey-intro.zgi?p=WEB2HMXUEFSE ONDotnet Survey: http://www.zoomerang.com/recipient/survey-intro.zgi?p=WEB2PYHVA5GV ***Lightweight XML Editing in Word 2003 Strictly speaking, you can edit custom XML in Word, but there are limitations that make the process needlessly complex. This article presents a lightweight approach to XML editing in Word that works in all editions of Word 2003. All you need besides Word is an XSLT processor. Evan Lenz, coauthor of Office 2003 XML, shows you how. http://www.windowsdevcenter.com/pub/a/windows/2004/09/07/XMLnword2003.html ***Site Navigation in ASP.NET 2.0 As your web site grows in complexity, it is imperative that you make the effort to make your site much more navigable. A common technique employed by web sites today uses a site map to display a breadcrumb navigational path on the page. ASP.NET 2.0 comes with the SiteMapPath control to help you in site navigation. Wei-Meng Lee shows you how it all works. http://www.ondotnet.com/pub/a/dotnet/2004/09/13/site_nav_aspnet20.html --------------------- Java --------------------- ***IRC Text to Speech with Java Paul Mutton creates a multi-platform IRC bot that uses the FreeTTS Java speech synthesizer library to convert IRC messages into audible speech. Why would you want to use an IRC text-to-speech system? By reading out messages as they arrive, you can keep working, diverting your attention to IRC only when necessary. Paul is the author of "IRC Hacks." http://www.onjava.com/pub/a/onjava/2004/09/08/IRCinJava.html ***Developing Your First Enterprise Beans, Part 1 In this first installment of a two-part series of excerpts from Chapter 4 of Enterprise JavaBeans, 4th Edition, you'll learn how to develop your first entity bean. This segment covers how to define the remote interface, how to create a deployment descriptor, how to deploy, and more. Code examples step you through everything you need to do to create and use your first entity bean. http://www.onjava.com/pub/a/onjava/excerpt/ejb4_chap4/index.html ================================================ O'Reilly User Group Wiki ================================================ Don't forget to check out the O'Reilly UG wiki to see what user groups across the globe are up to: http://wiki.oreillynet.com/usergroups/lpt?HomePage Until next time-- Marsee From jyoung79 at kc.rr.com Thu Sep 16 21:04:30 2004 From: jyoung79 at kc.rr.com (jyoung79@kc.rr.com) Date: Thu Sep 16 21:08:24 2004 Subject: [Kc] List of Lists Message-ID: Hello everyone, I've been researching through my Perl books, etc. and can't figure out how to create a list of lists. Here's what I'm trying to do: I've got a text file that contains data like this: 0000,ABC,1234,X1,20040102,21.15 0025,ABC,1328,X1,20040102,15.97 0001,DEF,1000,X2,20040210,1.89 ... I'd like to create a list of lists of each paragraph from the text file. So it would look something like this: (("0000ABC1234", "X1", "20040102", "21.15"), ("0025ABC1328", "X1", "20040102", "15.97"), ("0001DEF1000", "X2", "20040210", "1.89")) (I'm going to combine the first 3 items from each paragraph into one item (which is the Stock Number) --> (i.e. 0000, ABC, 1234 becomes 0000ABC1234). From everything I've read so far though, it doesn't look like it's possible to make this list of lists. The reason I'm looking into this is because I'm going to have to match the stock numbers from this list with another document. So for example, if my other document has a paragraph that just contains: 0025ABC1328 then I'll want to loop through my list of lists, and if I find a matching stock number then I'll add the appropriate data from it's list to this other document's paragraph that contains the stock number above (separated by tabs though): 0025ABC1328(tab)X1(tab)20040102(tab)15.97 So basically I'm attempting to create a simple automatch process. Please let me know if anyone has any ideas that are more efficient than this, or if you know how to create a list of lists. Thanks very much for looking at my question. Jay From joe at radiojoe.org Fri Sep 17 02:13:06 2004 From: joe at radiojoe.org (Joe Oppegaard) Date: Fri Sep 17 02:12:47 2004 Subject: [Kc] List of Lists In-Reply-To: References: Message-ID: On Thu, 16 Sep 2004 at 9:04pm -0500, jyoung79@kc.rr.com wrote: > Hello everyone, > > I've been researching through my Perl books, etc. and can't figure out > how to create a list of lists. Here's what I'm trying to do: > The key is knowing how anonymous data structures work. If you know the basics you can easily create very complex data structures. For instance, try this: ---------------------- #!/usr/bin/perl -w use strict; use Data::Dumper; my @data = ( [ 0..4 ], [ 5..9 ], { apple => 'red', smurf => 'blue' }, 'scalar', [ [ 10..14 ], [ 15..19 ], ], ); print Dumper(\@lofl); ---------------------- So the first element in the @data array, is an anonymous array holding the value 0 through 4, the second element is another anonymous array holding 5 through 9, the third element in the list is an anonymous hash, and so on and so forth. If you haven't used Data::Dumper before, it can give you a very nice idea of how your data structure is layed out. (Plus the output is valid perl, so it can be handy if you are doing experiments.) <-snip-> > From everything I've read so far though, it doesn't look like it's > possible to make this list of lists. <-snip-> Remember that `perldoc perl` and `perldoc perltoc` both have a nice index of the included perl documentation. In particular, you should read `perldoc perllol`, which specifically deals with lists of lists), and `perldoc perlreftut`, which is a more in depth look at complex data structures. -Joe Oppegaard From garrett at scriptpro.com Thu Sep 23 08:43:11 2004 From: garrett at scriptpro.com (Garrett Goebel) Date: Thu Sep 23 08:43:18 2004 Subject: [Kc] Perl 'Expert' Quiz-of-the-Week #24 (Module dependency evaluation) Message-ID: IMPORTANT: Please do not post solutions, hints, or other spoilers until at least 60 hours after the date of this message. Thanks. IMPORTANTE: Por favor, no enviis soluciones, pistas, o cualquier otra cosa que pueda echar a perder la resolucin del problema hasta que hayan pasado por lo menos 60 horas desde el envo de este mensaje. Gracias. WICHTIG: Bitte schicken Sie keine Lsungen, Tipps oder Hinweise fr diese Aufgabe vor Ablauf von 60 Stunden nach dem Datum dieser Mail. Danke. BELANGRIJK: Stuur aub geen oplossingen, hints of andere tips in de eerste 60 uur na het verzendingstijdstip van dit bericht. Waarvoor dank. Qing3 Zhu4Yi4: Qing3 Ning2 Deng3Dao4 Jie1Dao4 Ben3 Xin4Xi2 Zhi1Hou4 60 Xiao3Shi2, Zai4 Fa1Biao3 Jie3Da2, Ti2Shi4, Huo4 Qi2Ta1 Hui4 Xie4Lou4 Da2An4 De5 Jian4Yi4. Xie4Xie4. ---------------------------------------------------------------- If you've ever written any modules then you are probably familiar with the concept of requirements or prerequisites. These are dependencies that must be met in order for your module to work correctly. For example, if your module uses another module then that module must be present on the user's system in order for your module to function correctly. If you've used MakeMaker then you've probably written something like: use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Your::Module', VERSION_FROM => 'lib/Your/Module.pm', PREREQ_PM => { 'Test::More' => 0, 'File::Spec' => 0.82, }, ); or with Module::Build: use Module::Build; my $build = Module::Build->new( module_name => 'Your::Module', license => 'perl', requires => { 'File::Spec' => 0.82, }, build_requires => { 'Test::More' => 0, ), ); $build->create_build_script; Both of the above say tell their respective build tools that File::Spec version 0.82 or above and any version of Test::More are required. Module::Build is a little more flexible in that it lets you indicate that a module is required only during the build phase (build_requires) or that a module is recommended but not required (recommends). Further, Module::Build lets you be more specific about versions, using comparison operators. For example: requires => { 'Some::Module' => '>= 0.7, != 1.0, < 2.0', } Says that a version of Some::Module of 0.7 or greater, excluding version 1.0 and less than version 2.0 is required. However, even with Module::Build's greater flexibility there are a lot of requirements that are still not possible to describe. And some modules go to great lengths to do this dynamically. The problem with this is that it makes it more difficult for tools like CPAN.pm, CPANPLUS, and some automated tools to take advantage of without running the Makefile.PL or Build.PL file. Ideally, it would be nice to specify complex requirements in the now standard META.yml file, which contains meta data about a distribution in YAML format (http://yaml.org/). Then we could have a standard module that can read those requirements and validate them. This module could be used by Module::Build, ExtUtils::MakeMaker, CPAN.pm, CPANPLUS, and any other tool that needs to validate requirements. The types of things we would like to handle in the requirements specification are boolean expressions && (and), || (or), and ^^ (xor); grouping with parenthesis; and macro definition and expansion. An example of boolean expressions (suggested by a discussion with David Wheeler and Ken Williams on the module-build list) would be: requires => q[ (DBD::Pg && DateTime::Format::Pg) || (DBD::mysql && DateTime::Format::mysql) ] This says that we need any version of either of these two sets of modules. If we need to, we can also include version specifications: requires => q[ ( DBD::Pg > 1.1 && DateTime::Format::Pg ) || ( DBD::mysql <= 1.2 && DateTime::Format::mysql ) ] Note that when a branch of the 'or' expression evaluates to true, it is not neccessary to evaluate the remaining branches - short-circuit evaluation. However, all branches of an 'and' or 'xor' expression must be evaluated for correct error reporting. Of course we also want to remain compatible as much as possible with the old specifications. For the macros, we're mostly interested in the use of predefined macros. For example: requires => q[ ( Term::Readline::Gnu ) || ( {OSNAME} == MSWin32 && Term::Readline::Perl ) ] (A possible extension would be to add a set operator (in) for versions and any other values such as '{OSNAME} in [VMS MSWin32]' or 'Some::Module in [1.0..1.9 !1.7]'.) Other useful macros might be {MULTITHREADED}, {LARGEFILES}, etc. Finally, it can be useful to allow definition of macros to simplify expressions. For Example: requires => q[ def Pg = DBD::Pg && DateTime::Format::Pg; def mysql = DBD::mysql && DateTime::Format::mysql; {Pg} || {mysql} ] Feel free to experiment with different syntax. The only hard requirements are that it supports: boolean expressions, grouping, and predefined macros. For example, my original suggestion to Ken Williams, Module::Build's author, was something of the form: requires => { 'db_driver' => q[ {postgresql} || {mysql} ], '{postgresql}' => { 'DBD::Pg' => 0, 'DateTime::Format::Pg' => 0, }, '{mysql}' => { 'DBD::mysql' => 0, 'DateTime::Format::mysql' => 0, } This syntax makes parsing a little simpler, but otherwise allows the same features. The keys with braces around the names are not evaluated; They are definitions of macros that are only evaluated when they appear in the value of another key. This weeks quiz is to write a module (Prereq::Expr) that can take a specification of the type described above, and evaluate it to determine if the requirements are satisfied. The specification is the value assigned to the 'requires' key in the examples above. (Prereq::Expr->eval( $dist{requires} )). It can be either a hash, string, or array, whichever makes more sense. But, it should be able to handle the old style requirements. In order to determine the version of an installed module, I've extracted the routines from Module::Build and put them in a module at: http://perl.plover.com/qotw/misc/e024/Versions.pm Use it like this: use Versions; my $version = Versions->from_module('File::Spec'); or my $version = Versions->from_file('/path/to/module.pm'); To simplify comparisons, you can assume that versions are real numbers and just compare with perl's built-in numeric comparison operators. For the purpose of this quiz, it's not necessary to worry about alpha versions and all the complications of comparing versions. If you are interested, you might check out John Peacock's version and version::alphabeta modules. One of the more interesting problems with this quiz, I think, is the problem of reporting missing requirements. When you can have arbitrarily large sets of alternative modules, it's not obvious (to me) how best to notify the user in an orderly and comprehensible way. I do, of course, have an ulterior motive in this quiz. This form of complex requirements has been on the Module::Build TODO list for a long time. I'd like to submit the solutions posted, with the permission of their respective authors, to Ken Williams for possible inclusion in some form or another in a future version of Module::Build. If you want to implement this in a language other than perl, you can simply replace Versions.pm with a module/class or whatever that simply contains a list of hardcoded versions or whatever make sense for your language of choice. The important part is the expression parsing and evaluation. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.pm.org/pipermail/kc/attachments/20040923/fd5b21df/attachment.htm From garrett at scriptpro.com Tue Sep 28 08:03:27 2004 From: garrett at scriptpro.com (Garrett Goebel) Date: Tue Sep 28 08:03:42 2004 Subject: [Kc] Solutions and Discussion for Perl Quiz of the Week #12 (Histogram s) Message-ID: Sample solutions and discussion Perl Quiz of The Week #12 (20030212) [ This is a writeup of a very old quiz for which I never posted a report. I hope to be able to fill in the other missing reports in the coming months. Thanks to John J. Trammell for doing it. -MJD ] NAME qotw-r12-summary.pod - summary of "regular" Perl Quiz of the Week #12 SYNOPSIS The following programmers participated in Quiz 12: James Edward Gray II Kurt Hutchinson David Kershaw Brian King Not a Number Riccardo Perotti Marcelo Ramos John Trammell (late) Their code is available from http://perl.plover.com/qotw/misc/r012/ THE QUIZ The quiz text reads: You'll write functions for displaying histograms (bar charts). We'll use these to display the output from next week's quiz. You're build one function, 'histogram()', whose arguments will be a list of numbers. The function should construct a bar chart and then return a list of strings which, if printed, would display the numbers suitably. For example, histogram(1, 4, 2, 8, 5, 7) might return the following list of strings: " *\n", " * *\n", " * *\n", " ***\n", " * ***\n", " * ***\n", " *****\n", "******\n" when printed, these strings look like this: * * * * * *** * *** * *** ***** ****** The behavior of 'histogram' will be controlled by several global variables. $HISTOGRAM_WIDTH and $HISTOGRAM_HEIGHT will specify the width and height of the result. The output should be scaled to fit in a rectangle with $HISTOGRAM_HEIGHT rows and $HISTOGRAM_WIDTH rows. The bars themselves will be made up of the character $HISTOGRAM_CHAR, which must be a string of length 1. If any of the $HISTOGRAM_ variables are undefined, the function should use reasonable defaults. ISSUES Output Scaling and/or Truncation The main issue with this Quiz was discussed in a thread started by Andy Bach, archived at: http://perl.plover.com/~alias/list.cgi?1:mss:1292 The crux of the issue is this text from the Quiz: $HISTOGRAM_WIDTH and $HISTOGRAM_HEIGHT will specify the width and height of the result. The output should be scaled to fit in a rectangle with $HISTOGRAM_HEIGHT rows and $HISTOGRAM_WIDTH rows. Although all were in agreement that output should not exceed the dimensions specified by $HISTOGRAM_WIDTH and $HISTOGRAM_HEIGHT (see below however), there was some disagreement about whether $HISTOGRAM_WIDTH and $HISTOGRAM_HEIGHT were to be the *exact* width and height, or the *maximum* width and height. Also at issue was the correct behavior in the case where the number of arguments in the histogram() function call was greater than $HISTOGRAM_WIDTH. Arguments were made for and against truncating the histogram rather than making the output width greater than $HISTOGRAM_WIDTH. Miscellaneous Issues The following issues were also mentioned but not discussed at length: * how and whether to represent negative values * what to do with fractional inputs * horizontal vs. vertical histogram orientation * other alternate formatting suggestions (truncation, etc.) Little discussion regarding these issues ensued, although the solution offered by Kurt Hutchinson did handle representation of negative numbers. [This puzzles me, since the histograms I was taught in school always represented the "count" of something in a "bin". Certainly there can be bar graphs with negative values on the vertical axis, but I wouldn't call that a histogram. - JJT "Histogram" is from Greek "histos", meaning a beam or a mast. A histogram is therefore a drawing of beams or masts, and is nothing more or less than a bar chart. - MJD ] EXAMPLE An example solution is listed below (with slight modifications), courtesy of Brian King. sub histogram { my @list = @_; my @response = (); my $x_scale = 1; # horizontal scaling factor my $y_scale = 1; # vertical scaling factor my $max_value = 0; # greatest value (tallest bar) in @list $HISTOGRAM_WIDTH ||= 0; $HISTOGRAM_HEIGHT ||= 0; $HISTOGRAM_CHAR ||= 'H'; $HISTOGRAM_CHAR = unpack('a1',$HISTOGRAM_CHAR); # must be 1 char long. # determine y scaling factor. Increase $HISTOGRAM_HEIGHT # if what we got is too big to fit. foreach( @list ){ if( $_ > $max_value ){ $max_value = $_; } } if($max_value > $HISTOGRAM_HEIGHT){ $HISTOGRAM_HEIGHT = $max_value; } $y_scale = int($HISTOGRAM_HEIGHT / $max_value); # determine x scaling factor. Increase $HISTOGRAM_WIDTH # if we got too many values to fit. Can't just omit some... if( $HISTOGRAM_WIDTH < $#list ){ $HISTOGRAM_WIDTH = $#list; } $x_scale = int($HISTOGRAM_WIDTH / $#list); # build @response, based on @list and scaling factors. # iterate over @list $HISTOGRAM_HEIGHT times. # for each element in @list, if ($_ * scaling factor) is > # current position in the histogram (one less than the y-value of the graph), # then append $x_scale number of $HISTOGRAM_CHAR to the current element # of @response. Otherwise, append $x_scale number of spaces. for( my $i=0; $i<$HISTOGRAM_HEIGHT; $i++ ){ foreach(@list){ if( $_ * $y_scale > $i ){ $response[$i] .= $HISTOGRAM_CHAR x $x_scale; } else{ $response[$i] .= ' ' x $x_scale; } } $response[$i] .= "\n"; } return reverse @response; } Comments on this solution: * $HISTOGRAM_HEIGHT is increased, rather than truncating data * $HISTOGRAM_WIDTH is increased, rather than truncating data * vertical scaling only occurs if $HISTOGRAM_HEIGHT is at least twice as large as the largest input value * horizontal scaling only occurs if $HISTOGRAM_WIDTH is at least twice the number of input values * the histogram is constructed by looping over horizontal histogram slices from bottom to top. Vertical scaling is accomplished by comparing the vertical histogram position $i to a rescaled input value ($_ * $y_scale), and setting the output "pixel" accordingly. Horizontal scaling is accomplished by scaling this pixel by the calculated value $x_scale. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.pm.org/archives/kc/attachments/20040928/f4801a12/attachment.htm From garrett at scriptpro.com Wed Sep 29 08:16:00 2004 From: garrett at scriptpro.com (Garrett Goebel) Date: Wed Sep 29 08:16:04 2004 Subject: [Kc] Perl Quiz of the Week #25 (RPN calculator) Message-ID: IMPORTANT: Please do not post solutions, hints, or other spoilers until at least 60 hours after the date of this message. Thanks. IMPORTANTE: Por favor, no enviis soluciones, pistas, o cualquier otra cosa que pueda echar a perder la resolucin del problema hasta que hayan pasado por lo menos 60 horas desde el envo de este mensaje. Gracias. IMPORTANT: S'il vous plat, attendez au minimum 60 heures aprs la date de ce message avant de poster solutions, indices ou autres rvlations. Merci. WICHTIG: Bitte schicken Sie keine Lsungen, Tipps oder Hinweise fr diese Aufgabe vor Ablauf von 60 Stunden nach dem Datum dieser Mail. Danke. VNIMANIE: Pozhalujsta ne shlite reshenija, nameki na reshenija, i voobshe lyubye podskazki v techenie po krajnej mere 60 chasov ot daty etogo soobshenija. Spasibo. Qing3 Zhu4Yi4: Qing3 Ning2 Deng3Dao4 Jie1Dao4 Ben3 Xin4Xi2 Zhi1Hou4 60 Xiao3Shi2, Zai4 Fa1Biao3 Jie3Da2, Ti2Shi4, Huo4 Qi2Ta1 Hui4 Xie4Lou4 Da2An4 De5 Jian4Yi4. Xie4Xie4. UWAGA: Prosimy nie publikowac rozwiazan, dodatkowych badz pomocniczych informacjii przez co najmniej 60 godzin od daty tej wiadomosci. Dziekuje. ---------------------------------------------------------------- We're used to seeing arithmetic expressions written in "infix notation," where an operator appears between its two operands: "3 + 5". Traditional calculators use an entry method based on this notation, where the first number is entered, followed by the operator, then the second number, and finally a key to tell the calculator to produce the result: "3", "+", "5", "=". The display of an infix calculator typically shows the last number entered, or the result of the last calculation. In the 1970's, Hewlett-Packard introduced a pocket calculator using Reverse Polish Notation (RPN), also known as postfix notation. In postfix notation, the operator appears after its operands: "3 5 +". This expression would be keyed into an RPN calculator as follows: "3", "Enter", "5", "Enter", "+". The calculator stores the values on a stack as they are entered; when the operator is keyed, the values are popped from the stack, the operation is performed, and the result is pushed back onto the stack. The display of an RPN calculator typically shows the top few levels of the stack for easy manipulation of multiple values. RPN calculators are particularly useful for evaluating expressions with multiple parts, such as "(3 + 5) * 2 / (2 + 3)". With a typical infix calculator, the results of one part would have to be remembered or written down so the calculator can be cleared to calculate the other part, then finally combined with the first part. (Most infix calculators provide a "memory" feature that stores one value for later recall.) With an RPN calculator, the expression could be keyed as it would be written in postfix notation: "3 5 + 2 * 2 3 + /". For this quiz, we'll implement an interactive RPN calculator. The calculator will accept lines of input on standard input. Each line will contain zero or more terms separated by spaces. A term may be a number or an operator. Each term will be evaluated in order, from left to right. If the term is a number, the value will be pushed onto the stack. If the term is an operator, the operation will be performed. After a line of input has been processed, the stack will be printed to standard output in reverse order, with the top of the stack appearing last. The following example shows lines of user input after the "> " prompt. Stack printouts use numbered lines, with 0 representing the top of the stack. The number 3 is entered, pushing it onto an empty stack: > 3 0: 3 The number 5 is entered, resulting in a stack of two values: > 5 1: 3 0: 5 The plus operator takes the top two elements off of the stack, adds them together, and puts the result onto the stack: > + 0: 8 A number and an operator both appear on the same line. The number is pushed onto the stack, and the operator is performed, in this case 8 * 2. > 2 * 0: 16 Two numbers are pushed, followed by two operators. The first operator, "+", pops the 3 and the 2, adds them together, then pushes the result (5) onto the stack. The second operator, "/", pops the 5 that was just pushed and the 16 that was already on the stack, and performs the division. (In infix notation, this division would be written as "16 / 5".) > 2 3 + / 0: 3.2 Operators that require one value ("unary operators") take the topmost element off the stack, perform their function on the value, and push the result back onto the stack. Operators that require two values ("binary operators") take the top two elements off the stack and perform their function using the "earliest" value as the first term and the "latest" value as the second. For example, "20 5 /" pushes 20, pushes 5 (resulting in the stack 1: 25, 0: 5), then pops 5, pops 20, divides 20 by 5, then pushes the result (4) back onto the stack. If there are not enough elements on the stack to perform an operation, the calculator should report an error and stop processing the line. The calculator should support at least the following operators, whose functions are similar to those in Perl: + - * / % ** The calculator should support the following stack manipulation commands: drop pops the top element and discards it. swap swaps the 0th (top) and 1st elements in the stack. clear removes all values from the stack. dup duplicate the top element, push it onto the stack This specification lends itself easily to extension. Feel free to add features you think might make the calculator more useful. A few ideas: * Support for additional Perl builtin operations: & | ~ abs int cos sin exp log sqrt atan2 * Accept numbers entered in hexadecimal beginning in "0x", binary beginning in "0b", or octal beginning in "0". * Support different display modes for how the stack is printed, with commands to switch modes. "dec", "bin", "oct" and "hex" would switch the display to decimal, binary, octal or hexadecimal, respectively. (These commands do not affect the contents of the stack.) * An "N roll" command, which moves the Nth element in the stack to the 0th position, pushing the other elements up (where N is a value popped from the top of the stack). It is an error if there are not N elements in the stack. For example: > 10 20 30 40 50 4: 10 3: 20 2: 30 1: 40 0: 50 > 2 roll 4: 10 3: 20 2: 40 1: 50 0: 30 Similarly, "N rolld" would move the 0th element in the stack to the Nth position, dropping the other elements down. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.pm.org/archives/kc/attachments/20040929/befdc16d/attachment.htm From davidnicol at gmail.com Thu Sep 30 00:46:26 2004 From: davidnicol at gmail.com (David Nicol) Date: Thu Sep 30 00:46:28 2004 Subject: [Kc] Perl Quiz of the Week #25 (RPN calculator) In-Reply-To: References: Message-ID: <934f64a204092922461fcbb3d2@mail.gmail.com> like in FORTH. Do we need a whole FORTH, or just a RPN calculator? I think a RPN calculator in perl sounds like a good golf hole perl -nle 'if(/\d/){ unshift @S, $_ }else{ $S[0] = eval "$S[0] $_ $S[1]"}; print ++$count,": ",$S[0]' -- David L Nicol getting even worse at mindreading as I get older