How do I iterate through and output all possible combinations from the given characters?

I write in Delphi. Need a little help with the algorithm, or a sample code.

There is a set of characters (for example, 5 pieces, but in fact there will be more than a hundred), a, b, c,d, e. You need to make a list of all possible combinations of these characters. For example:

  1. a
  2. b
  3. c
  4. d
  5. e
  6. ab
  7. ac
  8. ad
  9. ...
  10. abcde
  11. ....

But with the condition that each character must repeat in combination, only once. And the character sets "ab" and "ba" are considered different combinations.

-----UPDATED--- - -

procedure Generate(list, comb: TStringList; idx: integer);
var
  temp :  TStringList;
  i, k : integer;
begin
  temp              := TStringList.Create;
  temp.Duplicates   := dupIgnore;
  temp.Sorted       := false;


  if idx >  list.Count-1 then begin
    if  comb.Count-1 > 0 then
      Form1.Memo1.Lines.Add(comb.Text);
    Exit;
  end;

  for k := 0 to comb.Count-1 do begin
    temp.Assign(comb);      // заменил строку присвоения на Assign
    temp.Insert(k, list[idx]);
    Generate(list, temp, idx + 1);
  end;
  Generate(list, comb, idx + 1);

comb.Free;
end;
Author: Gubert, 2019-04-30

2 answers

The number of such combinations grows exponentially, so it is impossible to get everything for large sets.

There are quite a few possibilities for generating combinations from reasonably sized sets.

For example, you can generate combinations recursively. At the K-th level of recursion, one K-th character is used. It is inserted in all possible places of the available combinations, and the option without this symbol is also used. For example, the combinations", 'a', 'b', 'ab', 'ba'come to level 3. For the last one, 'ba' ('c' is not used), 'cba', 'bca', 'bac'are passed to the next level

procedure Generate(s, comb: string; idx: Integer);
var
  i, k: Integer;
  temp: string;
begin
  if idx > Length(s) then begin
    if Length(comb) > 0 then
      Writeln(comb);
    Exit;
  end;

  for k := 1 to Length(comb) + 1 do begin
    temp := comb;
    Insert(s[idx], temp, k);
    Generate(s, temp, idx + 1);
  end;
  Generate(s, comb, idx + 1);
end;

begin
  Generate('abc', '', 1);
  Readln;
end.

You can also list all non-zero subsets of the input set - there will be 2^n-1, and for each (size k) generate all k! permutations

 0
Author: MBo, 2019-05-01 10:03:01

The "head-on" option. A string of length k is taken, where k is the number of characters used.

  1. The 1st character is placed in the k-th position, then the 2nd, and so on.
  2. When the characters are finished, the 1st character is placed in the (k-1) position, then step 1 is repeated, only now the "leading" characters are skipped.
  3. The actions are repeated by analogy until there are no options left.

Example. abc characters

1. '__a'
2. '__b'
3. '__c'
4. '_ab'
5. '_ac'
6. 'abc'
7. 'bac'
8. 'cab'
9. 'cba'
 0
Author: Old Skull, 2019-05-02 16:51:06