PROG4.MOD 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. MODULE prog4;
  2. (* This program displays the permutations of a string
  3. in alphabetic order *)
  4. IMPORT IO,Str;
  5. TYPE StringType = ARRAY [0..9] OF CHAR;
  6. PROCEDURE NextPerm(n:CARDINAL;
  7. VAR s:StringType;
  8. VAR wrap:BOOLEAN);
  9. (* This procedure updates s to the next permutation of the
  10. first n characters of s. The sequence of permutations
  11. generated by successive calls is in 'dictionary' order.
  12. If s is the last string in the sequence, the first is
  13. returned. The boolean result wrap is used to indicate
  14. this event *)
  15. VAR
  16. i:CARDINAL; (* s[i-1] is the most significant char changed *)
  17. j:CARDINAL; (* s[j] is the char to be swapped with s[i-1] *)
  18. tmp:CHAR;
  19. BEGIN
  20. IF n = 0 THEN
  21. wrap := TRUE;
  22. RETURN;
  23. END;
  24. i := n - 1;
  25. LOOP
  26. IF i = 0 THEN
  27. wrap := TRUE;
  28. EXIT;
  29. END;
  30. IF s[i-1] < s[i] THEN
  31. j := n - 1;
  32. WHILE s[j] <= s[i-1] DO
  33. j := j - 1;
  34. END;
  35. tmp := s[j]; s[j] := s[i-1]; s[i-1] := tmp; (* swap *)
  36. wrap := FALSE;
  37. EXIT;
  38. END;
  39. i := i - 1;
  40. END;
  41. (* s[i]..s[n-1] are in reverse order, reversing them
  42. yields the minimum permutation we require *)
  43. j := n - 1;
  44. WHILE i < j DO
  45. tmp := s[j]; s[j] := s[i]; s[i] := tmp;
  46. i := i + 1;
  47. j := j - 1;
  48. END;
  49. END NextPerm;
  50. VAR InputString:StringType;
  51. wrap:BOOLEAN;
  52. online:CARDINAL; (* number of strings in output line *)
  53. len:CARDINAL;
  54. BEGIN
  55. IO.WrStr('Enter string : ');
  56. IO.RdStr(InputString);
  57. len := Str.Length(InputString);
  58. REPEAT
  59. NextPerm(len,InputString,wrap);
  60. UNTIL wrap;
  61. online := 0;
  62. REPEAT
  63. IO.WrStr(InputString);
  64. IO.WrStr(' ');
  65. online := online + 1;
  66. IF online = 6 THEN
  67. IO.WrLn;
  68. online := 0;
  69. END;
  70. NextPerm(len,InputString,wrap);
  71. UNTIL wrap;
  72. END prog4.
  73.