Thursday, September 22, 2011

onsap.com update

I'm again using onsap.com to record questions and answers. Now the site allows users to subscribe to email updates of individual questions or tags so it is more useful as a way to follow some topic. I still think it can be a good tool for SAP people. I will keep using it to record my questions (and perhaps later update it with answers) and to learn a bit more from trying to answer other questions.

You can follow my activity here and you're very welcome to join.

Labels:

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: