Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flip-coin scheme procedure

I tried solving this problem Flip-coin takes no arguements and returns the symbol heads or tails at random with equal probability. This is what I got, but I do not understand why it is giving me the "impossible" can this be stopped?

(define flip-coin
    (lambda ( )
        (cond
            [ (= (random 2 ) 1 ) "heads" ]
            [ (= (random 2 ) 0 ) "tails" ]
            [else "impossible" ]
        )
    )
)
like image 702
Jeremiah Avatar asked Feb 20 '23 04:02

Jeremiah


2 Answers

You have two different calls to random in your cond statement. Both of these are independent and can give you different results. So it's possible that the first (random 2) evaluates to 0 and the second one evaluates to 1, making both of those cases fail and giving you "impossible".

The solution would be to put the result of (random 2) in a local variable with a let-statement, making sure to only call random once.

like image 78
Tikhon Jelvis Avatar answered Feb 26 '23 23:02

Tikhon Jelvis


The flip-coin procedure returns only one of two possible values, it can be simplified a bit more, also noticing that random should be called only once - and there's no need to save its value in a variable, because the result is used immediately:

(define (flip-coin)
  (if (zero? (random 2))
      "tails"
      "heads"))
like image 44
Óscar López Avatar answered Feb 26 '23 23:02

Óscar López