# Thread: Beginner programming challange #1

1. ## Beginner programming challange #1

Challenge #2

Hi,

I have decided to bring back the beginner programming challenges, since many of the non-beginner ones are way to over my head i thought maybe other people may feel the same way, and when the old beginners challenges were about, i really enjoyed them (even though i never submitted anything). So these challenges should be simple enough for someone with a few months programming behind them. The submitted entries will be judged next weekend. All languages are allowed, but if its something obscure or not majorly used please provide a link to a tutorial on how to get it runnning, thanks Enjoy

Challenge
Write a guess the number game.

You must use a random number generator to obtain the number.

The number must be between 1 and 100

The game should not crash if an invalid entry is made, e.g. if i enter the string "OMG give me the answer!!" the program should catch the error and tell me that only integers are valid entries.

Extra credit
Allow the use of words for the values, e.g. "Twenty six" should be recognized as 26 and no error should be raised.

Allow the use of an external text file for higher lower prompts.

(I realise i have just said dont allow words, then allow them, but you know what i mean)

NOTE: To experienced programmers. Whilst your entries will be accepted, they will not be judged, instead I encourage you to help newer programmers with this challenge (obviously not giving them the answer) and any help you do give will be greatly appreciated im sure.

Oh, and have fun!

Thanks,

Bodsda
Last edited by Bodsda; September 10th, 2009 at 10:44 PM.

2. ## Re: Beginner programming challange #1

here's a quick python solution

PHP Code:
``` #!/usr/bin/env pythonimport randomnum = random.randint(0,100)while 1:    try:        input=int(raw_input("Guess a number within 0-100 :: "))        if input<0 or input>100:            raise ValueError        elif input == num:            print "you guessed it right :)"            break        elif input < num:            print "guess higher next time ...\n"        else:            print "guess lower next time ...\n"    except ValueError:        print "only integers within 0-100 are accepted\nplease try again ...\n"  ```
Last edited by sujoy; March 15th, 2009 at 10:57 PM.

3. ## Re: Beginner programming challange #1

Allow the use of an external text file for higher lower prompts.

4. ## Re: Beginner programming challange #1

i made my program in c++
Code:
```#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

int main()
{
//initialize random seed
srand ( time(NULL) );

int randomNumber = 0;
randomNumber = (rand()%100)+1;	//create a random number b/w 1 & 100
int numGuess = 0;
cout << "Guess a number between 1 and 100." << endl;

cin >> numGuess;

while (numGuess != randomNumber)
{

cout << "Wrong number. Try again." << endl;	//signify wrong number
cin >> numGuess;				//guess again...
}

cout << "You guessed the correct number!! Great Job!" << endl;	//signify right number
cout << "Program Terminated." << endl;			//end random number game

return 0;
}//end main```
in the following code, i put the random number in the output to try to verify that it's (somewhat) random.
edit: found out what my problem was, i forgot to include the initializer itself!

Code:
```run1206@run1206-laptop:~\$ g++ -o randomNumber randomNumber.cpp
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
83
83
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
64
64
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
58
58
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
83
83
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
99
99
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
70
78
Wrong number. Try again.
70
You guessed the correct number!! Great Job!
Program Terminated.```
i'll try with words as numbers as well...
Last edited by run1206; March 16th, 2009 at 03:03 AM.

5. ## Re: Beginner programming challange #1

Originally Posted by run1206
i made my program in c++
Code:
```#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

int main()
{
//initialize random seed
srand ( time(NULL) );

int randomNumber = 0;
randomNumber = (rand()%100)+1;	//create a random number b/w 1 & 100
int numGuess = 0;
cout << "Guess a number between 1 and 100." << endl;

cin >> numGuess;

while (numGuess != randomNumber)
{

cout << "Wrong number. Try again." << endl;	//signify wrong number
cin >> numGuess;				//guess again...
}

cout << "You guessed the correct number!! Great Job!" << endl;	//signify right number
cout << "Program Terminated." << endl;			//end random number game

return 0;
}//end main```
in the following code, i put the random number in the output to try to verify that it's (somewhat) random.
edit: found out what my problem was, i forgot to include the initializer itself!

Code:
```run1206@run1206-laptop:~\$ g++ -o randomNumber randomNumber.cpp
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
83
83
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
64
64
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
58
58
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
83
83
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
99
99
You guessed the correct number!! Great Job!
Program Terminated.
run1206@run1206-laptop:~\$ ./randomNumber
Guess a number between 1 and 100.
70
78
Wrong number. Try again.
70
You guessed the correct number!! Great Job!
Program Terminated.```
i'll try with words as numbers as well...
Good job, nice to see an entry other then python I remember in the old beginners challenges 90% of the entries were python.

6. ## Re: Beginner programming challange #1

Common Lisp:

Code:
```; Function to prompt the user and return the entered value
(format *query-io* "~a : " prompt)
(force-output *query-io*)

;Function to repeatedly prompt the user until a valid
;number is entered
(defun get-number (prompt)
(let ((val 0))
(loop
(setf val (parse-integer
(if val
(return val)
(format t "Only integers are allowed.~%")))))

(defun correct()
(format t "~%You guessed correctly.~%")
(bye))

;Main game function
(defun game ()
(format t "Guess the number game.~%")
(setf rndnum (random 100))
(loop
(setf answer (get-number "number > "))
(correct)

(game)```
I am not new to porgramming, but I am new to Lisp .

7. Just Give Me the Beans!
Join Date
Dec 2007
Beans
75

## Re: Beginner programming challange #1

Originally Posted by Bodsda
Extra credit
Allow the use of words for the values, e.g. "Twenty six" should be recognized as 26 and no error should be raised.
I'll just go for the extra credit part in java.

Edit: Caters for "twentysix" and "twenty six" but not "twenty-six";

PHP Code:
``` import java.util.HashMap;public class StrToNum {    private HashMap<String, Integer> postnumbers;    private HashMap<String, Integer> numbers;    private HashMap<String, Integer> teenpre;    private HashMap<String, Integer> pre;    private String ten = "teen";    private String decade = "ty";    {        postnumbers = new HashMap<String, Integer>();        postnumbers.put("one", 1);        postnumbers.put("two", 2);        postnumbers.put("three", 3);        postnumbers.put("four", 4);        postnumbers.put("five", 5);        postnumbers.put("six", 6);        postnumbers.put("seven", 7);        postnumbers.put("eight", 8);        postnumbers.put("nine", 9);        numbers = new HashMap<String, Integer>();        numbers.putAll(postnumbers);        numbers.put("ten", 10);        numbers.put("eleven", 11);        numbers.put("twelve", 12);        numbers.put("hundred", 100);        teenpre = new HashMap<String, Integer>();        teenpre.put("thir", 3);        teenpre.put("four", 4);        teenpre.put("fif", 5);        teenpre.put("six", 6);        teenpre.put("seven", 7);        teenpre.put("eigh", 8);        teenpre.put("nine", 9);        pre = new HashMap<String, Integer>();        pre.put("twen", 2);        pre.putAll(teenpre);    }    public int convert(String str) throws NumberFormatException {        str = str.toLowerCase();        int indexD = str.indexOf(decade);        int indexT = str.indexOf(ten);        String sub, post;        try {            if ( indexT != -1) { //String contains "teen"                sub = str.substring(0, indexT);                if (ten.equals(str.substring(indexT))) {                    return teenpre.get(sub) + 10;                }            } else if ( indexD != -1) { //String contains ty                sub = str.substring(0, indexD);                if (decade.equals(str.substring(indexD))) { //Dividable by 10                    return pre.get(sub) * 10;                } else {                    post = str.substring(indexD + decade.length()).trim();                    return (pre.get(sub) * 10) + postnumbers.get(post);                }            } else {                return numbers.get(str);            }            throw new Exception();        } catch (Exception e) {            throw new NumberFormatException(str + " is not a valid number");         }    }}  ```
Last edited by ufis; March 16th, 2009 at 03:00 PM.

8. ## Re: Beginner programming challange #1

thanks much
i'm trying to learn Python and script languages, kinda broaden my horizons on programming languages.

9. Tea Glorious Tea!
Join Date
Feb 2008
Beans
367

## Re: Beginner programming challange #1

I might throw something together in Ruby. (which I currently know NOTHING about, it could be fun.)

10. ## Re: Beginner programming challange #1

Could anyone tell me why this doesn't work?
Code:
```#!/usr/bin/env python
import random

guess = raw_input("Please enter a number between 1 and 100: ")
guess = int(guess)
try:
if guess == random.randint(1,100):
print "You guessed correct!"
else:
print "Incorrect number."
except ValueError:
print "Please enter an integer (whole number)."```
I get this output:
Code:
```taidgh@ephedra:~/Desktop\$ python guess.py
Please enter a number between 1 and 100: notanint
Traceback (most recent call last):
File "guess.py", line 5, in <module>
guess = int(guess)
ValueError: invalid literal for int() with base 10: 'notanint'```

#### Posting Permissions

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