# Thread: [Beginner] Programming Challenge: 5

1. Banned
Join Date
Apr 2007
Beans
14,781

## [Beginner] Programming Challenge: 5

After a bigger gap, we are resuming.

Here is the last challenge: http://ubuntuforums.org/showthread.php?t=889710

From now on, there will be no final grading (actually, it has been like that before). Anyone can comment whenever they wish on submissions. This is for learning and getting/giving advice.

The Challenge:
We will focus on a small "game" and Structured Programming.

In addition to the small task, you should pay careful attention to the code itself.

You will have to do the following:

• Write a program that will emulate a common guessing game.
• The game should randomly set a number which the user will have to guess and will get "higher" or "lower" hints as it goes. Only integers will be used for the target number.
• The target number should be 1 to 100 (although this "game" is harldy a game. Anybody will get it in 7-8 tries without even "guessing", by using logic)
• The game will end with a note of the win when the correct number is guessed.
• The program should tell the number of guesses it took to get it as well.

In addition, these are also part of the challenge:

• The code should be well formatted.
• The code layout should be structured and logical.
• The use of logical design is a big part of this, so keep a consistant format, and use logical variable and function names.

Rules:
Do not copy code, but you can obviously read it

Try to comment on other submissions if you are not a beginner. If you are not a beginner, don't post solutions for commenting, although you can show off skills as the thread progresses if you want to showcase something you are learning.

Hints:
• Most languages contain standard library functions (or even inbuilt) for getting random numbers.
• This is a good time to learn about the modulus operator if you haven't done so already

How it will be judged:
• It has to do what it is specified.
• It has to be structured.

As before, try to follow the following:
• Clean code. Readable code is a must for being a programmer who wishes to possibly interact with others. Some languages can be more readable than others, so it will be judged on the effort of writing clean code, not which language is easier to read by design.
• Logical code. Be a programmer, not a code monkey
• Commented code. If something is possibly unclear (like an obscure use of math), let the readers know. Do not over comment, and let the code speak for itself whenever you can. Have logical variable names and function names. (Excessive commenting is a minus factor)
• Working code. It has to work as it is posted. The codw will be read on the forum, so remember to use this guide to paste code if you don't know how: http://ubuntuforums.org/showthread.php?t=606009
Last edited by LaRoza; August 29th, 2008 at 03:55 AM.

2. ## Re: [Beginner] Programming Challenge: 5

I'm currently learning Haskell, so I'm pretty sure that makes me a valid beginner. To run it save the script and mark it executable, provided you have ghc and libghc6-regex-posix-dev it should work like any other script.

Code:
```#!/usr/bin/env runhaskell
module Main where
import System.Random
import Text.Regex.Posix

main :: IO Int
main = getStdRandom (randomR (0,100)) >>=
(\r -> guessGame r >> return r)

-- Get a number from the player, making sure it is between 1 and 100
getGuess :: IO Int
getGuess = do
guessStr <- getLine
if guessStr =~ "^([1-9][0-9]?|100)\$"
else putStrLn "That's not a number between 1 and 100" >>
getGuess

checkNumber :: Int -> Int -> String
checkNumber guess n
| guess > n = "Too high!"
| guess < n = "Too low!"
| otherwise = "Correct!"

guessGame :: Int -> IO ()
guessGame r = do
putStrLn "Guess a number between 0 and 100"
guess <- getGuess
let result = checkNumber guess r
if result == "Correct!"
then putStrLn result
else putStrLn result >> guessGame r```
Last edited by Alasdair; August 29th, 2008 at 12:04 AM.

3. ## Re: [Beginner] Programming Challenge: 5

PHP Code:
``` <?php#we execute this bit the first time onlyif(!isset(\$_POST['target']))    {    \$target = (int)rand(0,100);    echo "<p>OK, sucker, guess the number I am thinking of.</p>";    the_form(\$target);    }#and this bit every other timeelse    {    \$target = \$_POST['target'];    \$myguess = \$_POST['myguess'];    if (the_test(\$myguess) == false)        {        echo "<p>Listen Stupid - you have to enter a whole number between 0 and 100!</p>";        the_form(\$target);        }    else        {        if (\$myguess == \$target)            {            echo "<p>Yes - my number was ".\$target."</p>";            }        if (\$myguess > \$target)            {            echo "<p>".\$myguess." is too high.</p>";            the_form(\$target);            }        if (\$myguess < \$target)            {            echo "<p>".\$myguess." is too low.</p>";            the_form(\$target);            }        }    }    function the_form(\$target) {    echo "<p>Go on - have a guess!</p>";        echo "<form action=\"game.php\" method=\"POST\">";    echo "<input type=\"text\" name=\"myguess\" />";    #we use a hidden input to pass the value of \$target to the next iteration    echo "<input type=\"hidden\" name=\"target\" value=\"".\$target."\" />";    echo "<input type=\"submit\" value=\"Guess!\" />";        echo "</form>";}function the_test(\$input) {    #test that the input is a whole number between 0 and 100    if ((ereg("^[0-9]{1,3}\$",\$input)) && (\$input >=0) && (\$input <=100))    {    return true;    }    else     {    return false;    }}    ?> ```
Last edited by cpetercarter; August 29th, 2008 at 07:21 AM. Reason: Argh! Forgot to close some HTML tags! go to the bottom of the class!

4. ## Re: [Beginner] Programming Challenge: 5

I don't know PHP, but wouldn't the following the_test function work just as well as the one you have? The if statement seems superfluous, if the expression is true you return true, if the expression is false you return false, so why not return just the result of the expression?

PHP Code:
``` function the_test(\$input) {    #test that the input is a whole number between 0 and 100    return ((ereg("^[0-9]{1,3}\$",\$input)) && (\$input >=0) && (\$input <=100));}  ```

5. ## Re: [Beginner] Programming Challenge: 5

Vala:

Code:
```public class Game
{
int target;
int guess;

construct
{
target = Random.int_range (0, 100);
}

private void get_guess ()
{
do
{
stdout.printf ("Guess a number between 0 and 100 ");
stdin.scanf ("%d", out guess);
} while (guess < 0 || guess > 100);
}

public void run ()
{
get_guess ();

if (guess < target)
{
stdout.printf ("Too low\n");
run ();
}
else if (guess > target)
{
stdout.printf ("Too high\n");
run ();
}
else
stdout.printf ("Correct\n");
}

static void main (string[] args)
{
var game = new Game ();
game.run ();
}
}```
Use valac game.vala to compile. You may need to add using GLib; at the top, depending on which version of valac you are using.
Last edited by bruce89; August 29th, 2008 at 01:44 AM.

6. ## Re: [Beginner] Programming Challenge: 5

Code:
```sudo apt-get install 4digits

4digits```
joking...

heres mine...it includes the ability for you to adjust the range of the random integer it generates

PHP Code:
``` //headers needed #include <iostream> #include "string" #include <cstdlib> using namespace std; int random(int Range) //method for generating random ints {     int random_integer = (rand()%Range)+1;           return random_integer; } int main(int argc, char** argv)//main program {         //varialbes     int target_num;     int guess;     int range;          cout << "what is the highest possible number you would like the answer to be?" << endl;          cin >> range;              //generate random number     target_num = random(range);          while (1) //game loop     {     cout << "please enter a guess" << endl;          cin >> guess;              //output depending on answer     if (guess > target_num)     {         cout << "guess is too high" << endl;     }          else if (guess < target_num)     {         cout << "guess too low" << endl;     }          else     {         bool answered = false;                  while (answered == false)         {                          string answer;             cout << "you got it! \n play again [y/n]" << endl;             cin >> answer;                          if (answer == "y")             {                 target_num = random(range);                 answered = true;             }                          else if (answer == "n")             {                 return 0;             }                          else             {                 cout << "invalid input";             }         }              }          }     return 0; }  ```

7. ## Re: [Beginner] Programming Challenge: 5

This is C. It should therefore be very readable.

PHP Code:
``` char*m[]={"small","big"};t,g;main(int i){i?srand(time(0))+(t=rand()%100):1;printf("What is your guess? ");return scanf("%i",&g)+g-2==t?puts("You win!")&0:(i-=printf("Too %s.\n",m[g>t]))&0||main(0);}  ```
I think this breaks most of the rules, but it plays correctly. At least, it did before I noticed the rules were a little different from what I thought they were... I fixed it, but possibly not correctly. It should still work...

Expect several compilation warnings.

EDIT: It didn't work. It does now.
Last edited by snova; August 29th, 2008 at 08:33 PM. Reason: bugfix

8. A Carafe of Ubuntu
Join Date
Jul 2008
Location
cairo,egypt
Beans
107

## Re: [Beginner] Programming Challenge: 5

one question..i dont get this..if the program should set a random integer for the user to guess then howcome the target integer should be 100...can someone explain what does that mean??

9. ## Re: [Beginner] Programming Challenge: 5

Originally Posted by snova
(snip!)
I think this breaks most of the rules(snip!)
What exactly ARE the rules??? I read the "structured programming" link, but that left me confused... Do we just make a number guessing program, or do we have to do it a special way?

mosty friedman asked my other question...

10. Tall Cafè Ubuntu
Join Date
Jul 2008
Beans
1,491

## Re: [Beginner] Programming Challenge: 5

Originally Posted by Alasdair
I'm currently learning Haskell, so I'm pretty sure that makes me a valid beginner. To run it save the script and mark it executable, provided you have ghc and libghc6-regex-posix-dev it should work like any other script.

Code:
```#!/usr/bin/env runhaskell
module Main where
import System.Random
import Text.Regex.Posix

main :: IO Int
main = getStdRandom (randomR (0,100)) >>=
(\r -> guessGame r >> return r)

-- Get a number from the player, making sure it is between 1 and 100
getGuess :: IO Int
getGuess = do
guessStr <- getLine
if guessStr =~ "^([1-9][0-9]?|100)\$"
else putStrLn "That's not a number between 1 and 100" >>
getGuess

checkNumber :: Int -> Int -> String
checkNumber guess n
| guess > n = "Too high!"
| guess < n = "Too low!"
| otherwise = "Correct!"

guessGame :: Int -> IO ()
guessGame r = do
putStrLn "Guess a number between 0 and 100"
guess <- getGuess
let result = checkNumber guess r
if result == "Correct!"
then putStrLn result
else putStrLn result >> guessGame r```
Have you tested that code? In proper Haskell main has to be of type main :: IO () !

Also your code never returns the number of guesses it took to get the random number correct. (It just returns the random number you 'feed' to your game.)

So you may want to rewrite those 2 functions:
Code:
```main :: IO ()
main = getStdRandom (randomR (0,100)) >>=
(\r -> putStrLn ("It took you " ++ (guessGame r 0) ++ " tries to guess it."))

guessGame :: Int -> Int -> IO Int
guessGame r k= do
putStrLn "Guess a number between 0 and 100"
guess <- getGuess
let result = checkNumber guess r
if result == "Correct!"
then putStrLn result >> return k
else putStrLn result >> guessGame r (k+1)```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•