Pick random element: Difference between revisions

Content added Content deleted
Line 7: Line 7:


<lang 11l>print(random:choice([‘foo’, ‘bar’, ‘baz’]))</lang>
<lang 11l>print(random:choice([‘foo’, ‘bar’, ‘baz’]))</lang>

=={{header|8086 Assembly}}==
The easiest way to pick a random element from a list is to use a random number generator's output as an index into an array. Care must be taken not to index out of bounds. If the array's size is a power of 2, then <code>RNG output & (array size - 1)</code> will ensure that the array is not indexed out of bounds while maintaining the randomness of the selection. Otherwise, you will have to manually check the RNG output against the array's size and roll again if the RNG output is larger.

For brevity's sake, the implementations of the RNG and printing routines were left out; they can be provided if requested.
<lang asm> .model small
.stack 1024

.data
TestList byte 00h,05h,10h,15h,20h,25h,30h,35h

.code
start:
mov ax,@data
mov ds,ax
mov ax,@code
mov es,ax

call seedXorshift32 ;seeds the xorshift rng using the computer's date and time
call doXorshift32
mov ax,word ptr [ds:xorshift32_state_lo] ;retrieve the rng output
and al,00000111b ;constrain the rng to values 0-7
mov bx,offset TestList
XLAT ;translate AL according to [DS:BX]
call PrintHex ;display AL to the terminal

mov ax,4C00h
int 21h ;exit program and return to MS-DOS
end start</lang>

{{out}} (After four runs of the program)
<pre>
05
20
15
30
</pre>


=={{header|ACL2}}==
=={{header|ACL2}}==