Petals Around The Rose

December 18, 2012

We begin with the code to roll five dice:

(define (roll)
  (let loop ((n 5) (xs (list)))
      (if (zero? n) xs
        (loop (- n 1) (cons (randint 1 7) xs)))))

Next is the code to compute the score. You must promise never to reveal the secret.

(define (score xs)
  (let loop ((xs xs) (s 0))
    (cond ((null? xs) s)
          ((odd? (car xs))
            (loop (cdr xs) (+ s (car xs) -1)))
          (else (loop (cdr xs) s)))))

All that’s left is to play the game:

(define (petals-around-the-rose)
  (display "Let's play 'Petals Around The Rose.'") (newline)
  (display "The name of the game is significant.") (newline)
  (display "At each turn I will roll five dice,") (newline)
  (display "then ask you for the score, which") (newline)
  (display "will always be zero or an even number.") (newline)
  (display "After you guess the score, I will tell") (newline)
  (display "you if you are right, or tell you the") (newline)
  (display "correct score if you are wrong. The game") (newline)
  (display "ends when you prove that you know the") (newline)
  (display "secret by guessing the score correctly") (newline)
  (display "six times in a row.") (newline)
  (let loop ((xs (roll)) (streak 0))
    (cond ((= streak 6) (newline)
            (display "Congratulations! You are now a member") (newline)
            (display "of the Fraternity of the Petals Around") (newline)
            (display "The Rose. You must pledge never to") (newline)
            (display "reveal the secret to anyone.") (newline))
    (else (newline) (display "The five dice are:")
          (for-each (lambda (x) (display " ") (display x)) xs)
          (display ".") (newline) (display "What is the score? ")
          (cond ((equal? (read) (score xs))
                  (display "Correct") (newline)
  (loop (roll) (+ streak 1)))
          (else (display "The correct score is ")
                (display (score xs)) (display ".") (newline)
                (loop (roll) 0)))))))

We used randint from the Standard Prelude. You can run the program at http://programmingpraxis.codepad.org/vzDlGhJA.

About these ads

Pages: 1 2

14 Responses to “Petals Around The Rose”

  1. [...] today’s Programming Praxis exercise, our goal is to implement the well-known “Petals Around the [...]

  2. My Haskell solution (see http://bonsaicode.wordpress.com/2012/12/18/programming-praxis-petals-around-the-rose/ for a version with comments):

    import Control.Monad
    import System.Random
    import Text.Printf
    
    showIntro :: IO ()
    showIntro = putStrLn
      "Let's play 'Petals Around The Rose.'\n\
      \The name of the game is significant.\n\
      \At each turn I will roll five dice,\n\
      \then ask you for the score, which\n\
      \will always be zero or an even number.\n\
      \After you guess the score, I will tell\n\
      \you if you are right, or tell you the\n\
      \correct score if you are wrong. The game\n\
      \ends when you prove that you know the\n\
      \secret by guessing the score correctly\n\
      \six times in a row.\n"
    
    play :: Int -> IO ()
    play 6      = putStrLn "Congratulations! You are now a member\n\
                           \of the Fraternity of the Petals Around\n\
                           \The Rose. You must pledge never to\n\
                           \reveal the secret to anyone."
    play streak = do
        dice <- replicateM 5 $ randomRIO (1,6)
        putStrLn $ "The five dice are: " ++ unwords (map show dice)
        putStr "What is the score? "
        guess <- readLn
        if guess == score dice
        then putStrLn "Correct\n" >> play (streak + 1)
        else printf "The correct answer is %d.\n\n" (score dice) >> play 0
    
    score :: [Int] -> Int
    score = sum . map ([0,0,0,2,0,4,0] !!)
    
    main :: IO ()
    main = showIntro >> play 0
    
  3. Johan said

    Python:

    def petals():
        import random
        def roll():
            dices = [random.randrange(1,7) for _ in xrange(5)]
            answer = sum(d-1 for d in dices if d % 2)
            return dices, answer
        info = ["Let's play 'Petals Around The Rose.'",
                "The name of the game is significant.",
                "At each turn I will roll five dice,",
                "then ask you for the score, which",
                "will always be zero or an even number.",
                "After you guess the score, I will tell",
                "you if you are right, or tell you the",
                "correct score if you are wrong. The game",
                "ends when you prove that you know the",
                "secret by guessing the score correctly",
                "six times in a row.\n"]
        note = ["Congratulations! You are now a member",
                "of the Fraternity of the Petals Around",
                "The Rose. You must pledge never to",
                "reveal the secret to anyone."]
        state, what = "The five dice are: %s.", "What is the score? "
        yes, no = "Correct.\n", "The correct score is %d.\n"
        c = 0
        print('\n'.join(info))
        while c < 6:
            turn, ans = roll()
            print(state % ' '.join(str(d) for d in turn))
            if int(raw_input(what)) == ans:
                print(yes)
                c += 1
            else:
                print(no % ans)
        print('\n'.join(note))
    
    
  4. hamidj said

    My Java solution here.

  5. [...] This question is from Programmingpraxis: [...]

  6. Brian said

    Fun stuff.

    from random import randint
    
    def petals():
        print "Let's play 'Petals Around The Rose.'  The name of the game is significant.  At each turn I will roll five dice,  then ask you for the score, which will always be zero or an even number.  After you guess the score, I will tell you if you are right, or tell you the correct score if you are wrong. The game ends when you prove that you know the secret by guessing the score correctly six times in a row."
        i=0
        while i<6:
            n=[randint(1,6) for x in range(0,5)]
            score=(n.count(3)+2*n.count(5))*2
            print "The Five Dice are:"+' '.join(str(s) for s in n)+"."
            guess=input("What is the score? ")
            if int(guess)==score:
                print 'Right on.'
                i=i+1
            else:
                print "The correct score is "+str(score)+"."
                i=0
        print "Congratulations! You are now a member of the Fraternity of the Petals Around The Rose. You must pledge never to reveal the secret to anyone."
        
    petals()
    
  7. Brian said

    Johan, your script won’t reset the count back to zero if the user guesses wrong ;)

  8. andrew said

    jQuery/JavaScript


    var correct = 0;

    function init () {
    roll = this.roll = [];
    var i = 0;

    for (i; i 5) {
    $results.html('Congratulations! You are now a member of the Fraternity of the Petals Around The Rose. You must pledge never to reveal the secret to anyone.');
    } else {
    $results.html('Correct.');
    init();
    }
    } else {
    correct = 0;
    $results.html('The correct score was '+score+'. Start over.');
    init();
    }
    }

    // http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area/841121#841121
    $.fn.selectRange = function(start, end) {
    return this.each(function() {
    if (this.setSelectionRange) {
    this.focus();
    this.setSelectionRange(start, end);
    } else if (this.createTextRange) {
    var range = this.createTextRange();
    range.collapse(true);
    range.moveEnd('character', end);
    range.moveStart('character', start);
    range.select();
    }
    });
    };

    $(document).ready(function () {

    $roll = $('');

    $prompt = $('', {
    type : 'text',
    placeholder : 'What is the score?'
    });

    $submit = $('', {
    type : 'submit',
    value : 'Press To Play.',
    onclick : 'play()'
    });

    $results = $('');

    $('body').append($roll);
    $('body').append($prompt);
    $('body').append($submit);
    $('body').append($results);

    init();
    });

  9. andrew said

    For some reason it cut out half my code…take #2


    var correct = 0;

    function init () {
    roll = this.roll = [];
    var i = 0;

    for (i; i 5) {
    $results.html('Congratulations! You are now a member of the Fraternity of the Petals Around The Rose. You must pledge never to reveal the secret to anyone.');
    } else {
    $results.html('Correct.');
    init();
    }
    } else {
    correct = 0;
    $results.html('The correct score was '+score+'. Start over.');
    init();
    }
    }

    // http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area/841121#841121
    $.fn.selectRange = function(start, end) {
    return this.each(function() {
    if (this.setSelectionRange) {
    this.focus();
    this.setSelectionRange(start, end);
    } else if (this.createTextRange) {
    var range = this.createTextRange();
    range.collapse(true);
    range.moveEnd('character', end);
    range.moveStart('character', start);
    range.select();
    }
    });
    };

    $(document).ready(function () {

    $roll = $('');

    $prompt = $('', {
    type : 'text',
    placeholder : 'What is the score?'
    });

    $submit = $('', {
    type : 'submit',
    value : 'Press To Play.',
    onclick : 'play()'
    });

    $results = $('');

    $('body').append($roll);
    $('body').append($prompt);
    $('body').append($submit);
    $('body').append($results);

    init();
    });

  10. andrew said

    ok screw it…pastebin\’d

  11. jaysonsoi said

    c#:
    namespace PetalsAroundTheRose
    {
    class Program
    {
    const int _dice3 = 3;
    const int _dice5 =5;
    static void Main(string[] args)
    {
    Random r = new Random();
    int[] _arrInt = new int[5] { r.Next(1, 6), r.Next(1, 6), r.Next(1, 6), r.Next(1, 6), r.Next(1, 6) };
    Console.Write(“The five dice are: “);
    for (int i = 0; i < _arrInt.Length; i++)
    {
    Console.Write(_arrInt[i] + " ");
    }
    Console.Write("\nYou're guess is? ");
    int _guess = Convert.ToInt32(Console.ReadLine());
    if (_guess == GetResult(_arrInt))
    {
    Console.WriteLine("\nYou're CORRECT the answer is " + GetResult(_arrInt));
    }
    else
    {
    Console.WriteLine("\nYou're WRONG the answer is " + GetResult(_arrInt));
    }
    Console.ReadLine();
    }
    //Methods
    public static int GetResult(int[] _arrInt )
    {
    int _result = 0;
    for (int i = 0; i < _arrInt.Length; i++)
    {
    if (_arrInt[i] ==_dice3)
    {
    _result += _dice3-1;
    }
    else if (_arrInt[i] == _dice5)
    {
    _result += _dice5-1;
    }
    }
    return _result;
    }

    }
    }

  12. Alcriss said

    int _count = 0;

    Console.Write(“\n Petals Around the Rose”);
    Console.Write(“\n Get five consecutive correct answers to win!”);
    Console.Write(“\n *score will always be zero or an even number \n”);

    Generate:
    Random _dice = new Random();
    int _dice1 = _dice.Next(1, 7);
    int _dice2 = _dice.Next(1, 7);
    int _dice3 = _dice.Next(1, 7);
    int _dice4 = _dice.Next(1, 7);
    int _dice5 = _dice.Next(1, 7);
    bool _check = false;
    string _message = string.Empty;

    Console.Write(“\n The five dice: ” + _dice1 + ” ” + _dice2 + ” ” + _dice3 + ” ” + _dice4 + ” ” + _dice5);
    Console.Write(“\n What is the score? “);
    int score = Convert.ToInt32(Console.ReadLine());

    _message = Score(_dice1, _dice2, _dice3, _dice4, _dice5, score);
    _check = Terminator(_message);
    if (_check == false) { _count = 0; }
    else { _count = _count + 1; }

    if (_count == 5)
    {
    Console.Write(“\n Congratulations! You are now a member of \n the Fraternity of the Petals Around The Rose. \n You must pledge never to reveal the secret to anyone.”);
    Console.ReadLine();
    Environment.Exit(0);
    }
    Console.Write(_message);
    goto Generate;
    }

    //METHODS

    public static int Change(int entry)
    {
    int _new = 0;
    if (entry == 3)
    {
    _new = 2;
    return _new;
    }
    else if (entry ==5)
    {
    _new = 4;
    return _new;
    }
    else
    {
    _new = 0;
    }
    return _new;
    }

    public static string Score(int dice1, int dice2, int dice3, int dice4, int dice5, int entry)
    {
    int sum = 0;
    sum = Change(dice1) + Change(dice2) + Change(dice3) + Change(dice4) + Change(dice5);
    if (entry == sum)
    {
    return ” Correct! \n”;
    }
    return “The correct answer is ” + sum + “\n”;
    }

    public static bool Terminator(string entry)
    {
    if (entry == ” Correct! \n”)
    {
    return true;
    }
    return false;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 598 other followers

%d bloggers like this: