/* Color switches in Picat. https://brainstellar.com/puzzles/probability/1020 """ You are given an urn with 100 balls (50 black and 50 white). You pick balls from urn one by one without replacements until all the balls are out. A black followed by a white or a white followed by a black is "a colour change". Calculate the expected number of colour-changes if the balls are being picked randomly from the urn. Answer: 50 """ With N black and N white balls, the estimated number of colour-changes is N. Cf my Gamble model gamble_colored_switches.rkt This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import ppl_distributions, ppl_utils. import util. main => go. /* n = 5 var : num color switches Probabilities: 5: 0.2925000000000000 4: 0.1895000000000000 6: 0.1868000000000000 7: 0.1274000000000000 3: 0.1240000000000000 8: 0.0327000000000000 2: 0.0307000000000000 1: 0.0084000000000000 9: 0.0080000000000000 mean = 5.0085 n = 10 var : num color switches Probabilities (truncated): 10: 0.1690000000000000 11: 0.1686000000000000 9: 0.1644000000000000 8: 0.1172000000000000 ......... 3: 0.0008000000000000 2: 0.0003000000000000 19: 0.0001000000000000 18: 0.0001000000000000 mean = 10.0229 n = 50 var : num color switches Probabilities (truncated): 51: 0.0812000000000000 50: 0.0803000000000000 52: 0.0772000000000000 49: 0.0747000000000000 ......... 34: 0.0004000000000000 68: 0.0003000000000000 33: 0.0002000000000000 32: 0.0001000000000000 mean = 50.0048 n = 100 var : num color switches Probabilities (truncated): 100: 0.0573000000000000 101: 0.0570000000000000 99: 0.0559000000000000 103: 0.0547000000000000 ......... 128: 0.0001000000000000 125: 0.0001000000000000 75: 0.0001000000000000 73: 0.0001000000000000 mean = 100.013 */ go ?=> member(N,[5,10,50,100]), println(n=N), reset_store, run_model(10_000,$model(N),[show_probs_trunc,mean]), nl, % show_store_lengths,nl, fail, nl. go => true. model(N) => Balls = ones(N,black) ++ ones(N,white), BallsShuffled = draw_without_replacement(Balls), NumColorSwitches = [cond(BallsShuffled[I-1] != BallsShuffled[I],1,0) : I in 2..Balls.len].sum, add("num color switches",NumColorSwitches).