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:
- a
- b
- c
- d
- e
- ab
- ac
- ad
- ...
- abcde
- ....
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;
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
The "head-on" option. A string of length k is taken, where k is the number of characters used.
- The 1st character is placed in the k-th position, then the 2nd, and so on.
- 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.
- 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'