Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Behold! The power of recursion.

by pg (Canon)
on Oct 18, 2004 at 03:04 UTC ( #400040=note: print w/ replies, xml ) Need Help??


in reply to Behold! The power of recursion.

Just for fun, imagine those two functions are actually two guys talking: (Still recursion, but two functions involved, they call each other)

use strict; use warnings; use constant HIGH => 1024; my $the_number = int(rand HIGH) + 1; print "The number is $the_number\n"; my $high; my $low; my $answer; my $guess; ask_question(); sub ask_question { sleep(1); if (!$answer) { $high = HIGH; $low = 1; } elsif ($answer == 0) { return; } elsif ($answer == 1) { $low = $guess + 1; } elsif ($answer == -1) { $high = $guess - 1; } $guess = int(($low + $high) / 2); print "Is your number $guess? "; answer(); } sub answer { if ($guess < $the_number) { print "Go higher ...\n"; $answer = 1; ask_question(); } elsif ($guess == $the_number) { print "You got it!\n"; $answer = 0; } else { print "Go lower ...\n"; $answer = -1; ask_question(); } }

Result from one run:

The number is 1001 Is your number 512? Go higher ... Is your number 768? Go higher ... Is your number 896? Go higher ... Is your number 960? Go higher ... Is your number 992? Go higher ... Is your number 1008? Go lower ... Is your number 1000? Go higher ... Is your number 1004? Go lower ... Is your number 1002? Go lower ... Is your number 1001? You got it!


Comment on Re: Behold! The power of recursion.
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://400040]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2014-12-22 01:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (110 votes), past polls