Page 1 of 7 123 ... LastLast
Results 1 to 10 of 65

Thread: Beginner programming challange #1

  1. #1
    Join Date
    Dec 2007
    Location
    Behind you!!
    Beans
    978
    Distro
    Ubuntu 10.04 Lucid Lynx

    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)



    Please refrain from uploading obfuscated code, as im likely to dismiss it. The code should be readable by a beginner programmer.

    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.

    So, without further ado, Begin.

    Oh, and have fun!

    Thanks,

    Bodsda
    Last edited by Bodsda; September 10th, 2009 at 10:44 PM.
    computer-howto
    Linux is not windows
    Fluxbox & Flux menu how to
    Programming is an art. Learn it, Live it, Love it!


  2. #2
    Join Date
    Oct 2007
    Location
    $HOME
    Beans
    631

    Re: Beginner programming challange #1

    here's a quick python solution

    PHP Code:
    #!/usr/bin/env python

    import random

    num 
    random.randint(0,100)
    while 
    1:
        try:
            
    input=int(raw_input("Guess a number within 0-100 :: "))
            if 
    input<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. #3
    Join Date
    Dec 2007
    Location
    Behind you!!
    Beans
    978
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Beginner programming challange #1

    An addition to the Extra credit section has been added:

    Allow the use of an external text file for higher lower prompts.
    computer-howto
    Linux is not windows
    Fluxbox & Flux menu how to
    Programming is an art. Learn it, Live it, Love it!


  4. #4
    Join Date
    Dec 2006
    Location
    Perth Amboy, NJ
    Beans
    141
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    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.
    Welcome to the world of Open Source!!!
    Linux User #471120 Ubuntu User #21997
    Jaunty Jackalope 9.04

  5. #5
    Join Date
    Dec 2007
    Location
    Behind you!!
    Beans
    978
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Beginner programming challange #1

    Quote Originally Posted by run1206 View Post
    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.
    computer-howto
    Linux is not windows
    Fluxbox & Flux menu how to
    Programming is an art. Learn it, Live it, Love it!


  6. #6

    Re: Beginner programming challange #1

    Common Lisp:

    Code:
    ; Function to prompt the user and return the entered value
    (defun prompt-read (prompt)
      (format *query-io* "~a : " prompt)
      (force-output *query-io*)
      (read-line *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
            (prompt-read prompt) :junk-allowed t))
          (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.~%")
      (let ((rndnum nil)(answer nil))
        (setf rndnum (random 100))
        (loop
          (setf answer (get-number "number > "))
          (if (= answer rndnum)
            (correct)
            (format t "~%Your answer is wrong.~%")))))
    
    (game)
    I am not new to porgramming, but I am new to Lisp .
    im dyslexic, please don't comment on my spelling
    blender 3d artist, visit my portfolio
    Quad-Ren, Open source, resolution independent 2D graphics engine
    Screen space is a precious resource, don't waste it

  7. #7
    Join Date
    Dec 2007
    Beans
    75

    Re: Beginner programming challange #1

    Quote Originally Posted by Bodsda View Post
    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<StringIntegerpostnumbers;
        private 
    HashMap<StringIntegernumbers;
        private 
    HashMap<StringIntegerteenpre;
        private 
    HashMap<StringIntegerpre;

        private 
    String ten "teen";
        private 
    String decade "ty";

        {
            
    postnumbers = new HashMap<StringInteger>();
            
    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<StringInteger>();
            
    numbers.putAll(postnumbers);
            
    numbers.put("ten"10);
            
    numbers.put("eleven"11);
            
    numbers.put("twelve"12);
            
    numbers.put("hundred"100);

            
    teenpre = new HashMap<StringInteger>();
            
    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<StringInteger>();
            
    pre.put("twen"2);
            
    pre.putAll(teenpre);
        }

        public 
    int convert(String strthrows NumberFormatException {
            
    str str.toLowerCase();
            
    int indexD str.indexOf(decade);
            
    int indexT str.indexOf(ten);
            
    String subpost;
            try {
                if ( 
    indexT != -1) { //String contains "teen"
                    
    sub str.substring(0indexT);
                    if (
    ten.equals(str.substring(indexT))) {
                        return 
    teenpre.get(sub) + 10;
                    }
                } else if ( 
    indexD != -1) { //String contains ty
                    
    sub str.substring(0indexD);
                    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. #8
    Join Date
    Dec 2006
    Location
    Perth Amboy, NJ
    Beans
    141
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Beginner programming challange #1

    thanks much
    i'm trying to learn Python and script languages, kinda broaden my horizons on programming languages.
    Welcome to the world of Open Source!!!
    Linux User #471120 Ubuntu User #21997
    Jaunty Jackalope 9.04

  9. #9
    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. #10
    Join Date
    Oct 2008
    Location
    London, England
    Beans
    47
    Distro
    Ubuntu 8.10 Intrepid Ibex

    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'

Page 1 of 7 123 ... LastLast

Bookmarks

Posting Permissions

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