Re: mentor question 2.
Posted by
Richard O'Keefe on
Apr 29, 2020; 1:22am
URL: https://forum.world.st/mentor-question-2-tp5115643p5115768.html
String>>
isValidBinary
^self allSatisfy: [:each | each = $0 or: [each = $1]]
binaryToDecimal
"The caller should ensure that self isValidBinary before calling this."
^self inject: 0 into: [:acc :each |
acc*2 + (each codePoint - $0 codePoint)]
On Mon, 27 Apr 2020 at 06:05, Roelof Wobben via Pharo-users
<
[hidden email]> wrote:
>
> Hello,
>
> I have to make some code that convert a binary to a decimal and im not
> allowed to use the convert methods that Pharo has.
>
> So I have written this :
>
>
> decimalFromBinary: aString
> | result isValid |
> isValid = self isValidBinary: aString.
> isValid
> ifTrue: [ result := 0.
> aString reverse
> withIndexDo:
> [ :digit :index | result := result + (digit
> digitValue * (2 raisedTo: index - 1)) ].
> ^ result ]
> ifFalse: [ ^ nil ]
>
> isValidBinary: aString
> ^ aString allSatisfy: [ :c | c = 0 or: [ c = 1 ] ]
>
>
> but on the first method I see a message that the temp variables are read
> before written.
> and the second one I see a message that I use a or instead of searching
> literals.
>
> Where did I think wrong here ?
>
> Roelof
>
>