Tuesday, September 20, 2011

Random element from a table in ABAP

One function I find myself using a lot in python is random.choice that gives me a random element from a list. Quick example in python:


>>> import random
>>> for i in range(20):
... print random.choice(['A','B','C','D']),
...
C A D C C D A D C B B B B C B C A C D B


It turns out it is not that difficult to do the same in ABAP.


class lcl_random definition.
public section.
class-methods choice importing it_table type standard table
exporting es_row type any.
endclass.

class lcl_random implementation.
method choice.
data: l_size type i,
l_index type i.

describe table it_table lines l_size.

call function 'QF05_RANDOM_INTEGER'
exporting
ran_int_max = l_size
ran_int_min = 1
importing
ran_int = l_index
exceptions
invalid_input = 1
others = 2.

if sy-subrc = 0.
read table it_table into es_row index l_index.
endif.
endmethod.
endclass.

form test.
data: lt_test type table of char1,
l_test type char1.

l_test = 'A'.
append l_test to lt_test.
l_test = 'B'.
append l_test to lt_test.
l_test = 'C'.
append l_test to lt_test.
l_test = 'D'.
append l_test to lt_test.

do 20 times.
lcl_random=>choice( exporting it_table = lt_test importing es_row = l_test ).
write: l_test.
enddo.
endform.

Labels:

4 Comments:

Blogger Rui Dantas said...

By checking the behaviour of some standard transactions it was obvious that "random" was possible in abap.... ;)

12:16 PM  
Blogger pvl said...

eheheh, yes I agree, we can trust that random is well tested :-)

10:40 PM  
Anonymous Frank said...

And the same in a bit more modern ABAP:
(unfortunately formatting is not allowed in comments)

CLASS lcl_random DEFINITION.
PUBLIC SECTION.
CLASS-METHODS: choice IMPORTING it_table TYPE STANDARD TABLE
EXPORTING es_row TYPE any,
test.
ENDCLASS.

CLASS lcl_random IMPLEMENTATION.
METHOD choice.
DATA: lo_random_i TYPE REF TO cl_abap_random_int.

lo_random_i = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( )
min = 1
max = lines( it_table )
).

READ TABLE it_table INTO es_row
INDEX lo_random_i->get_next( ).

ENDMETHOD.

METHOD test.
DATA: lt_test TYPE STANDARD TABLE OF char1,
l_test TYPE char1.

APPEND 'A' TO lt_test.
APPEND 'B' TO lt_test.
APPEND 'C' TO lt_test.
APPEND 'D' TO lt_test.

DO 20 TIMES.
lcl_random=>choice( EXPORTING it_table = lt_test IMPORTING es_row = l_test ).
WRITE: l_test.
ENDDO.
ENDMETHOD.
ENDCLASS.

10:43 AM  
Blogger pvl said...

Thanks Frank, the use of cl_abap_random_int is a good improvement.

2:23 PM  

Post a Comment

<< Home