Copyright 2020 - BV TallVision IT

Where test data is concerned, having a few dice can be a very handy feature. Throw them to determine which choice a simulated end user would have done. Or use them to decide whether the next record of test data you are creating is red, green or blue. Random numbers - as test system tooling.

The following example was set up to support a series of automated choices to compose a list of unique employee names. A first name, prefix and lastname which is composed from shortlists of such names. In coding the outcome of a condition is based on the outcome of throwing a dice. Consider this example local class: lcl_random. To use this class, all you need is a choice to make, e.g. whether a prefix is needed for a name: 

if lcl_random=>roll_dice( ) < 2.
* In 1/3rd of the cases, this logic is executed.
endif.

If the dice mindset doesn't work for you, use a 1 to 10 range, or 1 to 100, or involve a dartboard, roulette table or whatever does work for you. Is 1 to 6 a too large subset? Use the same trick twice:

if lcl_random=>roll_dice( ) = 3 and lcl_random=>roll_dice( ) >= 4.
* chance: 1/6 * 3/6 so 1 in 12 times
endif.

For this setup to work, you'll need a small class (put it anywhere in your coding, light preference to "earlier that use", or also set CLASS lcl_random DEFINITION DEFERRED.

CLASS lcl_random DEFINITION. 
  PUBLIC SECTION. 
    CLASS-METHODS:
      roll_dice
        IMPORTING eye_count type DATATYPE-INTEGER2 default 6
        RETURNING VALUE(eyes) TYPE datatype-integer2.
ENDCLASS. 
CLASS lcl_random IMPLEMENTATION. 
  METHOD roll_dice.
    CALL FUNCTION 'RANDOM_I2'
      EXPORTING
        RND_MIN = 1
        RND_MAX = eye_count
      IMPORTING
        rnd_value = eyes.
  ENDMETHOD.
ENDCLASS. 

Select random entry from internal table

To select a random entry from an internal table, the length of the table is determined and with this length a random entry is selected and read:

  METHOD random_table_focus.
    data: lv_randomtabix TYPE datatype-integer4.
      describe table tbl lines lv_randomtabix.
      CALL FUNCTION 'RANDOM_I4'
        EXPORTING
          rnd_min   = 1
          rnd_max   = lv_randomtabix
        IMPORTING
          rnd_value = lv_randomtabix.
      READ TABLE tbl INDEX lv_randomtabix
        INTO tableline.
  ENDMETHOD.

Function modules for random numbers

There are quite a few function modules starting with RANDOM_, of give the GENERATE_SEC_RANDOM a try: it returns a random code with a length you can specify..