Due Thursday, July 15th, at the start of class.
Write a Perl script that guesses a number that the user has in mind.
This should be a fairly straightforward exercise that uses basic Perl syntax: loops, conditionals, variables, etc.
The user will run the script, think of a number between 1 and 100, and then the script will repeatedly guess what the number is. For each guess, the user indicates whether it is correct, too high, or too low. A typical interaction might look like this:
% homework-02-script Welcome to the number-guessing game! Think of a number between 1 and 100. I guess 50. Is this (c)orrect, (h)igh, or (l)ow? h Too high, I'll guess lower. I guess 25. Is this (c)orrect, (h)igh, or (l)ow? l Too low, I'll guess higher. I guess 42. Is this (c)orrect, (h)igh, or (l)ow? c I got it! %
While a binary search is clearly the optimimal strategy here, it does not really matter what strategy your script implements as long as it is guaranteed to find the answer eventually. Depending on the particular strategy you use, there are some simple Perl expressions that we have not discussed in class but that may be helpful. For example, you can get the integer portion of a floating-point number like this:
my $x = int(23 / 5);
And if you want a random floating point number in the range [0, n), you can do this:
my $x = rand($n);
The two expressions above can, of course, be combined to get a random integer between 0 and ($n-1):
my $x = int(rand($n));
Start your script the right way! Here is a suggestion:
#!/usr/bin/perl # Homework for CS 368-1 # Assigned on Day 02, 2010-07-13 # Written by [Your Name Here] use strict; use warnings;
Do the work yourself, consulting reasonable reference materials as needed; any reference material that gives you a complete or nearly complete solution to this problem or a similar one is not OK to use. Asking the instructors for help is OK, asking other students for help is not.
A printout of your output on a single sheet of paper. Be sure to put your own name in the “[Your Name Here]” part of the code. Identifying your work is important, or you may not receive appropriate credit.