Skip to content

Instantly share code, notes, and snippets.

@octavian-nita
Created August 6, 2014 08:59
Show Gist options
  • Select an option

  • Save octavian-nita/e3bbe595b1ea9b157074 to your computer and use it in GitHub Desktop.

Select an option

Save octavian-nita/e3bbe595b1ea9b157074 to your computer and use it in GitHub Desktop.
The Fisher-Yates shuffle in PL/SQL
DECLARE
TYPE tab_t IS TABLE OF VARCHAR2(20);
tab tab_t
:= tab_t('11',
'22',
'33',
'44',
'55');
cnt NUMBER;
idx NUMBER;
tmp VARCHAR2(20);
BEGIN
DBMS_RANDOM.seed(TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
cnt := CEIL(DBMS_RANDOM.VALUE(0, tab.COUNT));
FOR i IN tab.FIRST .. cnt LOOP
idx := CEIL(DBMS_RANDOM.VALUE(i, tab.COUNT));
tmp := tab(idx);
tab(idx) := tab(i);
tab(i) := tmp;
DBMS_OUTPUT.put(tab(i) || ' ');
END LOOP;
DBMS_OUTPUT.new_line;
DBMS_RANDOM.terminate;
END;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment