On Fri, 2009-07-10 at 13:42 +0100, Dermot wrote:
> Why is $E getting assigned the value from $k? 

my $E = binary($k);

I said $E will be assigned the string that represents $k, not it's
value.

> $E is initialised and
> then assigned the return value of the binary(18) during the first
> invocation (0). Does the subroutine continue and concatenate $b to $E
> and then return (1) ? or does it wait until binary exhausts $n?

It "waits" until: $n == 0 || $n == 1;

> 
> In my own groping/nonscientific sort of way, what I see emerging is a
> pattern where my result (10100) is nearly the reverse of the correct
> answer (100101) minus the leading 1. If that is correct I don't know
> why the string is reversed,

Here's a breakdown of what's happening in binary(37).  Note that I'm
mixing arithmetic and string manipulations here.

37
= int(37/2)*2 + 37%2
= (18)*2 + 1
= ( int(18/2)*2 + 18%2 )*2 + 1
= ( (9)*2 + 0 ) + 1
= ( ( int(9/2)*2 + 9%2 )*2 + 0 )*2 + 1
= ( ( (4)*2 + 1 )*2 + 0 )*2 + 1
= ( ( ( int(4/2)*2 + 4%2 )*2 + 1 )*2 + 0 )*2 + 1
= ( ( ( (2)*2 + 0 )*2 + 1 )*2 + 0 )*2 + 1
= ( ( ( ( int(2/2)*2 + 2%2 )*2 + 0 )*2 + 1 )*2 + 0 )*2 + 1
= ( ( ( ( (1)*2 + 0 )*2 + 0 )*2 + 1 )*2 + 0 )*2 + 1
= ( ( ( ( "1" . "0" ) . "0" ) . "1" ) . "0" ) . "1"
= ( ( ( ( "10" ) . "0" ) . "1" ) . "0" ) . "1"
= ( ( ( "100" ) . "1" ) . "0" ) . "1"
= ( ( "1001" ) . "0" ) . "1"
= ( "10010" ) . "1"
= "100101"

In the first part:
$n = int($n/2)* + $n%2
but $k = int($n/2)
and $b = $n%2
so $n = int($n/2)*2 + $n%2 = $k*2 + $b

Addition is commutative, so this could be written as: $n = $b + $k*2
but string concatenation is not.  The return string must be $E, the
string representing $k; multiplied by 2 by concatenating "0" at it's
end; and then that "0" being replaced by "$b".

In decimal, to multiply a number by 10, add an zero to it's end.  (It's
true.  Ask anyone on the streets.  When asked, "How do you multiply a
number by ten?" they'll reply, "Stick a zero at its end.")

In binary, to multiply a number by two, stick an zero on its end.  If $e
is the string representing $k, to reconstruct $n, we have to first
multiply $E by 2:

my $return_string = $E . "0";

Now we have to add $b to this by replacing the last character in the
return string with "$b":

$return_string = substr( $return_string, 0, -1 ) . $b;

It's just simpler to do it all in one step:

my $return_string = $E . $b;


-- 
Just my 0.00000002 million dollars worth,
  Shawn

Programming is as much about organization and communication
as it is about coding.



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to