Algorithm for generating variations based on different sets containing different values

StackOverflow https://stackoverflow.com/questions/16966243

  •  31-05-2022
  •  | 
  •  

Question

In short I am looking for a way in Java/C# for generation of all possible variations based on different sets containing different values. For example: Lets say we have set of names:

 -Max, Jack, Roger

Second set of verbs

-Loves, hates, knows

And third set of programming languages just as an example but we may have 10 sets

-Java, C#, Python, Visual Basic, C++

What I want is a way to generate all possible variations containing ALL attributes and having all values for example an output should be :

Max loves Java
Jack loves Java
Roger loves Java
Max hates Java
Jack hates Java
Roger hates Java
Max knows Java
Jack knows Java
Roger knows Java
Max loves C#
Jack loves C# 
Roger loves C#
and so on... this will generate 45 variations if I am not wrong at the end

Can anyone help ? I believe a similar easier example will be if you want to generate a variations of products in some clothing shop which have different sizes, colors and materials for example and you want all variations.

Was it helpful?

Solution

String[] names={"Max", "Jack", "Roger"};
String[] verbs={"Loves", "hates", "knows"};
String[] languages={"Java", "C#", "Python", "Visual Basic", "C++"};
for(String name:names)
   for(String verb:verbs)
      for(String language:languages)
         System.out.println(name+" "+verb+" "+language);

EDIT:

Oh ,i see . I misunderstood the question . You can just use the magic of recursion to solve this. This is what you want:

public static void main(String[] args) {
    String[][] sets={
            {"Max", "Jack", "Roger"},
            {"Loves", "hates", "knows"},
            {"Java", "C#", "Python", "Visual Basic", "C++"},
    };
    combine(sets,0,"");
}

public static void combine(String[][] list,int index,String upperText)
{
    if(index==list.length)return;
    for(String i:list[index]){
        combine(list,index+1,upperText+i);
        if(index==list.length-1){
            System.out.println(upperText+i);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top