/* Pick random element (Rosetta code) in Picat. http://rosettacode.org/wiki/Pick_random_element """ Demonstrate how to pick a random element from a list. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ main => go. go => L = 1..10, println(choice=choice(L)), println([choice(L) : _ in 1..10]), S = "pickrandomelement", println([choice(S) : _ in 1..10]), nl. % Inspired by Ada's entry go2 => Vowels = "aeiou", Consonants = "tnshrdl", Specials = ",.?!", % [] is needed since the elements are characters, not strings RandWords = [( [[Consonants.choice()] ++ [Vowels.choice()] : _ in 1..10] ++ [Specials.choice()] ).flatten() : _ in 1..3] , println(RandWords), nl. % % choice2/1 % go3 => L = 1..10, println(choice=choice2(L)), println([choice2(L) : _ in 1..10]), S = "pickrandomelement", println([choice2(S) : _ in 1..10]), nl. go4 => Max = 10, S = letter_freq(), foreach(_ in 1..30) println([choice(S) : _ in 1..1+choice(Max)]) end, nl. % % pick a random number from 1..N % % Note: random2/0 is semi-indeterministic % (random/0 is deterministic, starts with same seed everytime) % choice(N) = 1 + random2() mod N, integer(N) => true. % % pick a random element from a list % choice(List) = List[choice(List.length)], list(List) => true. % % using nth/3 % choice2(List) = RandElement => nth(choice(List.length),List,RandElement). letter_freq = Chars => Freq = [ [e,12.02], [t,9.10], [a,8.12], [o,7.68], [i,7.31], [n,6.95], [s,6.28], [r,6.02], [h,5.92], [d,4.32], [l,3.98], [u,2.88], [c,2.71], [m,2.61], [f,2.30], [y,2.11], [w,2.09], [g,2.03], [p,1.82], [b,1.49], [v,1.11], [k,0.69], [x,0.17], [q,0.11], [j,0.10], [z,0.07] ], Chars = [], foreach([C,F] in Freq) Chars := Chars ++ [C : _ in 1..ceiling(10*F)] end, nl.