Flip coin procedure

I tried to solve this problem. The flip coin takes no arguments and evenly returns the heads or tails of characters with equal probability. This is what I got, but I don’t understand why it gives me the “impossible”, can it be stopped?

(define flip-coin (lambda ( ) (cond [ (= (random 2 ) 1 ) "heads" ] [ (= (random 2 ) 0 ) "tails" ] [else "impossible" ] ) ) ) 
+4
source share
2 answers

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

 (define (flip-coin) (if (zero? (random 2)) "tails" "heads")) 
+3
source

You have two different random calls in your cond statement. Both are independent and may give you different results. Thus, it is possible that the first (random 2) evaluates to 0 , and the second evaluates to 1 , which causes both of these cases to fail and gives you "impossible" .

The solution is to put the result (random 2) in a local variable with let-statement, making sure that random is called only once.

+5
source

Source: https://habr.com/ru/post/1433697/


All Articles