Petals Around The Rose

December 18, 2012

Today’s exercise is our 400th, and our tradition on these anniversaries is to play a game. Today we choose Petals Around The Rose. Here’s a sample game:

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.

The five dice are: 4 2 5 5 4.
What is the score? 6
The correct score is 8.

The five dice are: 2 5 1 3 3.
What is the score? 8
Correct

The five dice are: 2 5 2 5 6.
What is the score? 8
Correct

The five dice are: 6 2 5 3 2.
What is the score? 8
The correct score is 6.

The five dice are: 4 2 1 1 2.
What is the score? 6
The correct score is 0.

The five dice are: 5 6 3 6 6.
What is the score? 6
Correct

The five dice are: 2 6 2 2 4.
What is the score? 6
The correct score is 0.

The five dice are: 3 2 4 2 1.
What is the score? 0
The correct score is 2.

The five dice are: 4 4 2 6 3.
What is the score? 2
Correct

The five dice are: 2 1 5 1 5.
What is the score? 8
Correct

The five dice are: 1 5 5 2 4.
What is the score? 8
Correct

The five dice are: 5 2 4 6 3.
What is the score? 6
Correct

The five dice are: 1 6 1 5 3.
What is the score? 6
Correct

The five dice are: 1 4 3 2 6.
What is the score? 2
Correct

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.

You can play Petals Around The Rose on the internet, or read about Bill Gates’ encounter with the game.

Your task is to figure out the secret, then write a program to play Petals Around The Rose. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisement

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: