Re: [Pharo-users] mentor question 4
See below. On Thu, Apr 30, 2020 at 10:58 AM Roelof Wobben via Pharo-users < pharo-users@lists.pharo.org> wrote:
and also not with this one :
cardNumber := '4539 1488 0343 6467'. oddSum := 0. evenSum := 0. nextIsOdd := false. cardNumber reverseDo: [:digit | digit = Character space ifFalse: [ nextIsOdd ifFalse: [oddSum := oddSum + (digit asString asInteger ) ] ifTrue: [(((digit asString asInteger) * 2) > 9) ifTrue: [evenSum := evenSum + ((digit asString asInteger) * 2) - 9 ] ifFalse: [ evenSum := evenSum + (digit asString asInteger) * 2 ]]. nextIsOdd := nextIsOdd not]]. ^ evenSum
Op 30-4-2020 om 18:30 schreef Roelof Wobben:
Op 30-4-2020 om 16:16 schreef Roelof Wobben:
nextIsOdd := true. aString reverseDo: [:digit | digit = Character space ifFalse: [ nextIsOdd ifTrue: [oddSum := ...] ifFalse: [evenSum := ...]. nextIsOdd := nextIsOdd not]].
hmm,
Still no luck with this code :
cardNumber := '4539 1488 0343 6467'. oddSum := 0. evenSum := 0. nextIsOdd := true. cardNumber reverseDo: [:digit | digit = Character space ifFalse: [ nextIsOdd ifTrue: [oddSum := oddSum + digit asInteger ] ifFalse: [evenSum := ((digit asInteger * 2) > 9) ifTrue: [evenSum + ((digit asInteger * 2) - 9) ] ifFalse: [ evenSum + (digit asInteger * 2) ]]. nextIsOdd := nextIsOdd not]]. ^ oddSum + evenSum
With the one change to use #digitValue instead of #asInteger (which answers the code point), the above example works. | evenSum oddSum | cardNumber := '4539 1488 0343 6467'. oddSum := evenSum := 0. nextIsOdd := true. cardNumber reverseDo: [:digit | digit = Character space ifFalse: [ nextIsOdd ifTrue: [oddSum := oddSum + digit digitValue ] ifFalse: [evenSum := ((digit digitValue * 2) > 9) ifTrue: [evenSum + ((digit digitValue * 2) - 9) ] ifFalse: [ evenSum + (digit digitValue * 2) ]]. nextIsOdd := nextIsOdd not]]. ^ oddSum + evenSum gives me 80 for the answer. A few (mostly) minor points: - I don't see why "reverse" is necessary. Of course if you use #do:, nextIsOdd needs to start with true. - repeating the "digit digitValue" or other variations adds clutter and reduces clarity - ((digit digitValue * 2) - 9) is not unreasonable, but could be simplified. What is the largest integer X such that 2xX<=9?
the answer schould be 57 where I get 1157
So some debugging to do
participants (2)
-
Richard Sargent -
Roelof Wobben