www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Build all combinations of strings

reply Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
Is there a Phobos function to turn this:

string[] words = "foo bar doo".split();

into:

string[] res = ["foo bar doo",
                "foo doo bar",
                "bar foo doo",
                "bar doo foo",
                "doo foo bar",
                "doo bar foo"];

So basically all combinations of some number of strings into a string
array. I suppose there's some generic way to do this too.
Jun 11 2012
next sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 06/11/2012 10:41 AM, Andrej Mitrovic wrote:
 Is there a Phobos function to turn this:

 string[] words = "foo bar doo".split();

 into:

 string[] res = ["foo bar doo",
                  "foo doo bar",
                  "bar foo doo",
                  "bar doo foo",
                  "doo foo bar",
                  "doo bar foo"];

 So basically all combinations of some number of strings into a string
 array. I suppose there's some generic way to do this too.

I think "permutation" is a more accurate word in this case. This has been discussed before: http://forum.dlang.org/thread/ivd4ug$1rmh$1 digitalmars.com Ali -- D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html
Jun 11 2012
prev sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Andrej Mitrovic:

 string[] words = "foo bar doo".split();

 into:

 string[] res = ["foo bar doo",
                 "foo doo bar",
                 "bar foo doo",
                 "bar doo foo",
                 "doo foo bar",
                 "doo bar foo"];

http://rosettacode.org/wiki/Permutations#Faster_Lazy_Version Using that the code is: import std.string, std.stdio, std.array; void main() { auto words = "foo bar doo".split(); auto res = permutations!false(words).map!(p => p.join(" "))().array(); writeln(res); } The output is your desired one: ["foo bar doo", "foo doo bar", "bar foo doo", "bar doo foo", "doo foo bar", "doo bar foo"] Bye, bearophile
Jun 11 2012