Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 29 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
29
Dung lượng
168,95 KB
Nội dung
QUIZ 22. LEARNING TIC-TAC-TOE 52 Quiz 22 Answer on pag e 225 Learning Tic-Tac-Toe This Ruby Quiz is to implement some AI for playing tic-tac-toe, with a catch: you’re not allowed to embed any knowledge of the game into your creation beyond making legal moves and recognizing that it has won or lost. Your program is expected to “learn” from the games it plays, until it masters the game and can play flawlessly. Tic-tac-toe is a very easy game played on a 3×3 board like this: | | + + | | + + | | Two players take turns filling a single open square with their symbol. The first person to play uses X s, and the other player uses Os. The first player to get a run of three symbols across, down, or diagonally wins. If the board fills wi thout a run, the game is a draw. Here’s what a game won by the X player might end up looking like: | | X + + | X | + + X | O | O Submissions can have any inter face but should be able to play against humans interactively. However, I also suggest making it easy to play against another AI player so you can “teach” the program faster. Being able to monitor the learning progression and know when a pro- gram has mastered the game would be very interesting, if you can find a way to incorporate it into your solution. Report erratum QUIZ 23. COUNTDOWN 53 Quiz 23 Answer on pag e 239 Countdown Posed by Brian Ca ndler One of the longest-running quiz shows on British television is called Countdown. That show has a “numbers round.” Some cards are laid face down in front of th e host. The top row contains large numbers (from the set 25, 50, 75, and 100), and the rest are small (1 to 10). Numbers are duplicated in the cards. Six cards are picked and dis- played: the choice is made by one of the contestants, who typically will ask for one large number and five small ones. Next, a machine called Cecil picks a target number from 100 to 999 at random. The contestants then have 30 seconds to find a way of combining the source numbers using the normal arithmetic operators (+, -, *, and /) to make the target number or to get as close as possible. Each source card can be used just once. The same applies to any intermediate results (although of course you don’t have to explicitly show the in termediate results). For example, if the target number is 522 and the source cards are 100, 5, 5, 2, 6, and 8, a possible solution is as follows: 100 * 5 = 500 5 + 6 = 11 11 * 2 = 22 500 + 22 = 522 or more succinctly, (5 * 100) + ((5 + 6) * 2) = 522. Another solution is (100 + 6) * 5 - 8 = 522. Normal arithmetic rules apply. Each step of th e calculation must result in an integer value. Report erratum QUIZ 23. COUNTDOWN 54 The quiz is to write a program that will accept one t arget number and a list of source numbers and g enerate a solution that calculates the target or a number as close to the target as possible. Report erratum QUIZ 24. SOLVING TACTICS 55 Quiz 24 Answer on pag e 249 Solving Tactics Posed by Bob Sidebotham There i s a pencil and paper game, Tactics, played on a 4×4 grid. The play starts with an empty grid. On each turn, a player can fill in from one to four adjacent squares, either horizontally or vertically. The player who fills in the last square loses. Here’s a sample game to help clarify the previous rules. The board position at the end of each play is shown: First player Second player X X X X X X X X (Turn 1) _ _ _ _ _ _ _ _ _ _ _ _ _ _ X _ _ _ _ _ _ _ X _ X X X X X X X X (Turn 2) X X _ _ X X _ X _ _ X _ _ _ X X _ _ X _ _ _ X _ X X X X X X X X (Turn 3) X X _ X X X X X _ _ X X _ _ X X _ _ X X _ _ X X X X X X X X X X (Turn 4) X X X X X X X X X X X X X X X X _ _ X X X _ X X X X X X (Turn 5 X X X X Second X X X X player X X X X wins!) Report erratum QUIZ 24. SOLVING TACTICS 56 Your task is to write a Ruby program that, given only t hese rules, deter- mines wheth er the first or second player is bound to be the winner, assuming perfect play. It should do this in a “reasonable” amount of time and memory—it should definitely take less than a minute on any processor less than five years old. You get bonus points if you can make the case that your program actually g ets the right answer for the right reason! Report erratum QUIZ 25. CRYPTOGRAMS 57 Quiz 25 Answer on pag e 259 Cryptograms Posed by Glenn P. Parker Given a cryptogram and a dictionary of known words, find t he best possible solution(s) to the cryptogr am. You get extra points for speed. Coding a brute-force solution is relatively easy, but there are many opportunities for the clever optimizer. A cryptogram is piece of text that has been passed through a simple cipher that maps all instances of one letter to a different letter. The familiar rot13 19 encoding is a trivial example. A solution to a cryptogram is a one-to-one mapping between two sets of (up to) 26 letters, such that applying the map to the cryptogram yields the greatest possible number of words in the dictionary. Both the dictionary and the cryptogram are presented as a set of words, one per line. The script should output one or more solutions and the full or part i al mapping f or each solution. A cryptogram might be as follows: gebo tev e cwaack cegn gsatkb ussyk Its solution could be as follows: mary had 19 An encoding where the first 13 letters of the alphabet are swapped with the last 13, and vice versa. In Ruby that’s just some_string.tr("A-Za-z", "N-ZA-Mn-za-m"). Report erratum QUIZ 25. CRYPTOGRAMS 58 a little lamb mother goose This is solved using the following mapping: in: abcdefghijklmnopqrstuvwxyz out: trl.a.m e by ohgdi.s. (The dots in the “out” side of the mapping indicate unused input letters.) Three unsolved cryptograms are given. Each cryptogram uses a differ- ent mapping. The cryptograms may contain a few w ords that are not in the dictionary (for example, an author’s name is commonly appended to quoted text in cryptograms). Many published cryptograms also con- tain punctuation in plain text as a clue to the solver. The following cryptograms contain no punctuation, since it just confuses dictionary- based searches: cryptograms/crypto1.t xt zfsbhd bd lsf xfe ofsr bsdxbejrbls sbsfra sbsf xfe ofsr xfedxbejrbls rqlujd jvwj fpbdls cryptograms/crypto2.t xt mkr ideerqruhr nrmsrru mkr ozgcym qdakm scqi oui mkr qdakm scqi dy mkr Report erratum QUIZ 25. CRYPTOGRAMS 59 ideerqruhr nrmsrru mkr zdakmudua nja oui mkr zdakmudua goqb msodu cryptograms/crypto3.t xt ftyw uwmb yw ilwwv qvb bjtvi fupxiu t dqvi tv yj huqtvd mtrw fuw dwq bjmqv fupyqd The dictionary I used was2of4brif.txt, available as part of the 12Dicts package at http://prdownloads.sourceforge.net/wordlist/12dicts-4.0.zip. Report erratum Part II Answers and Discussion ANSWER 1. MAD LIBS 61 Answer 1 From page 6 Mad Libs These are a fun little distraction, eh? Actually, I was surprised to discover (when writing the quiz) how practical this challenge is. Mad Libs are really just a templating problem, and t hat comes up in many aspects of programming. Have a look at the “views” in Ruby on Rails 20 for a strong real-world example. Looking at the problem that way got me to thin king, doesn’t Ruby ship with a templating engine? Yes, it does. Ruby includes a standard library called ERB. 21 ERB allows you to embed Ruby code into any text document. When that text is run through the library, the embedded code is run. This can be used to dynamically build up document content. For this example, we need only one feature of ERB. When we run ERB on a file, any Ruby code inside of the funny-looking <%= %> tags will be executed, and the value retur ned by that execution code will be inser ted into the document. Think of this as delayed interpolation (like Ruby’s #{ }, but it happens when triggered instead of when a String is built). 22 Let’s put ERB to work: madlibs/erb_madlib.rb #!/usr/local/bin/ruby -w # use Ruby' s standard template engine require "erb" 20 Ruby on Rails, or just Rails to those who know it well, is a popular web application framework written in Ruby. You can learn more at http://www.rubyonrails.org/. 21 ERB is eRuby’s pure-Ruby cousin. eRuby is written in C and stands for “embedded Ruby.” 22 You can learn about ERB’s other features from the online documentation at http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/index.html. Report erratum [...]... built instead of building up the whole number, if it doesn’t already 2 Extend Florian Groß’s solution to add the hexadecimal digits A through F Report erratum 75 A NSWER 3 GEDCOM P ARSER Answer From page 9 3 GEDCOM Parser Let’s jump right into a solution submitted by Hans Fugal: gedcom_parser/simple.rb #! /usr/bin /ruby require ' rexml/document ' doc = REXML::Document.new "" stack = [doc. root]... + 3) if num.size > 0 num [ 1, 3, 0, 3, 1 ], "1" => [ 0, 1, 0, 1, 0 ], "2" => [ 1, 1, 1, 2, 1 ], "3" => [ 1, 1, 1, 1, 1 ], "4" => [ 0, 3, 1, 1, 0 ], "5" => [ 1, 2, 1, 1, 1 ], "6" => [ 1, 2, 1, 3, 1 ], "7" => [ 1, 1, 0, 1, 0 ], "8" => [ 1, 3, 1, 3, 1 ], "9" => [ 1, 3, 1, 1, 1 ] } Report erratum A NSWER 2 LCD N UMBERS LCD_STATES = [ "HORIZONTAL", "VERTICAL", "HORIZONTAL", "VERTICAL",... Jump back to the beginning of the program now The Hash uses a default value block to conjure key-value 23 Golf is a sport programmers sometimes engage in to code a solution in a minimal amount of keystrokes They will often use surprising code constructs, as long as it shaves off a few characters Because of this, the resulting program can be difficult to read Report erratum 66 A NSWER 1 M AD L IBS pairs... this case, generating) XML documents The usage here is very basic First a document is created, and then elements are added to it as they are built At the end, the completed document is written to $stdout The previous starts by creating a REXML document and a stack for managing parent/child relationships The stack is just an Array, which is quite versatile in Ruby With setup out of the way, the code reads... line required of given size # # The VERTICAL state produces either a single right side line, # a single left side line or both lines # # 0 - skip, no line necessary, just space fill # 1 - single right side line # 2 - single left side line # 3 - both lines # # The DONE state terminates the state machine This is not needed # as part of the data array LCD_DISPLAY_DATA = { "0" => [ 1, 3, 0, 3, 1 ], "1" =>... multiline data that are applicable to many areas of computer programming Using Templates I’ve seen three main strategies used for solving the problem Some use a template approach, where you have some kind of text representation of your number at a scale of one Two might look like this, for example: [ " - ", " |", " - ", "| ", " - " ] Scaling that to any size is a twofold process First, you need to stretch... LEVEL drops) This is pretty efficient Let’s take a look at a solution from Jamis Buck that used that technique: gedcom_parser/efficient.rb #!/usr/bin/env ruby 24 You can read the online documentation for REXML at http://www.germane-software.com/software/rexml/docs/tutorial.html 25 If you aren’t going to use a great library like REXML to generate XML output, remember to handle your own escaping! This was a... NSWER 3 GEDCOM P ARSER GEDCOM Specifics Obviously, Hans’s solution doesn’t do any special handling of the GEDCOM format It’s a simple parse and print solution Some solutions may want to interpret more from the GEDCOM file as opposed to simple translation For example, a solution could build a single entity out of GEDCOM’s CONC and CONT fields Those fields represent a continuation of long data elements Of course,... handed off to the standard constructor for a Struct Report erratum 79 A NSWER 3 GEDCOM P ARSER Next, GED2XML defines a couple of helper methods The indent( ) method is just a tool for keeping the XML output pretty by printing an indent for the current level of the hierarchy The safe( ) method is needed because we won’t be able to count on REXML to handle escaping this time around It returns a copy of the . incorporate it into your solution. Report erratum QUIZ 23. COUNTDOWN 53 Quiz 23 Answer on pag e 239 Countdown Posed by Brian Ca ndler One of the longest-running quiz shows on British television is called Countdown at http://www.rubyonrails.org/. 21 ERB is eRuby’s pure -Ruby cousin. eRuby is written in C and stands for “embedded Ruby. ” 22 You can learn about ERB’s other features from the online documentation. where the first 13 letters of the alphabet are swapped with the last 13, and vice versa. In Ruby that’s just some_string.tr("A-Za-z", "N-ZA-Mn-za-m"). Report erratum QUIZ 25. CRYPTOGRAMS