Pick random element: Difference between revisions
Content added Content deleted
(Added Hare) |
|||
Line 1,088: | Line 1,088: | ||
<lang php>$arr = array('foo', 'bar', 'baz'); |
<lang php>$arr = array('foo', 'bar', 'baz'); |
||
$x = $arr[array_rand($arr)];</lang> |
$x = $arr[array_rand($arr)];</lang> |
||
=={{header|Picat}}== |
|||
<lang Picat>go => |
|||
% single element |
|||
println(choice=choice(10)), % single element |
|||
% From a list of numbers |
|||
L = 1..10, |
|||
println([choice(L) : _ in 1..10]), |
|||
% From a string |
|||
S = "pickrandomelement", |
|||
println([choice(S) : _ in 1..10]), |
|||
nl. |
|||
% Pick a random number from 1..N |
|||
choice(N) = random(1,N), integer(N) => true. |
|||
% Pick a random element from a list L. |
|||
choice(List) = List[choice(List.length)], list(List) => true.</lang> |
|||
{{out}} |
|||
<pre>choice = 4 |
|||
[7,8,6,4,6,7,3,10,2,3] |
|||
ekcealmnei</pre> |
|||
This is a more structured output. |
|||
{{trans|Ada}} |
|||
<lang Picat>go2 => |
|||
_ = random2(), |
|||
Vowels = "aeiou", |
|||
Consonants = "tnshrdl", |
|||
Specials = ",.?!", |
|||
RandWords = [( [[Consonants.choice()] ++ [Vowels.choice()] : _ in 1..10] |
|||
++ [Specials.choice()] |
|||
).flatten() |
|||
: _ in 1..3] , |
|||
println(RandWords), |
|||
nl.</lang> |
|||
{{out}} |
|||
<pre>[dodidosisahuhiretesi,,loledohusoluhusululu?,tunuridunoheditonudu!]</pre> |
|||
Get the random elements from a frequency table (converted to a "Roulette wheel"). |
|||
<lang Picat>% Pick according to a frequency table |
|||
go3 => |
|||
_ = random2(), |
|||
Max = 17, |
|||
S = letter_freq_wheel(), |
|||
foreach(_ in 1..10) |
|||
println([choice(S) : _ in 1..1+choice(Max)]) |
|||
end, |
|||
nl. |
|||
% Frequencies of letters converted to a "roulette wheel". |
|||
letter_freq_wheel = 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.</lang> |
|||
{{out}} |
|||
<pre>ihvuotpswieecanrv |
|||
gnelhlutnopytoss |
|||
aentkttnenb |
|||
cnyawephc |
|||
nsioetohasedd |
|||
yapaeofyt |
|||
setmtoorwloiar |
|||
nsssrkcfgnpadtifln |
|||
rrlwree |
|||
nawmtnie</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |