java - Combine elements from ArrayLists -


i know answers have been provided similar questions, none of them seemed suitable issue. i'm making program generate images granny squares, or squares have different color rings on inside.

the user able select how many rings there are, , therefore number of colors necessary change. therefore, cannot use nested loops go through each color number of loops have change. there way can create combinations these colors?

for example, if used colors white, blue, , green, following combinations white, white, white; white, white, blue; white, white, green; white, blue, white; etc. there way accomplish without nested loops?

here algorithm achieves using recursion.

public static void combine(list<character> colors, list<character> combination) {     if (combination.size() == colors.size()) {         system.out.println(combination);     } else {         (char color : colors) {             combination.add(color);             combine(colors, combination);             combination.remove(combination.size() - 1);         }     } }  public static void main(string[] args) {     list<character> colors = new arraylist<>();     colors.add('w');     colors.add('b');     colors.add('g');      combine(colors, new linkedlist<character>()); } 

colors original list of colors (w, b, g)

combinations list continually modified throughout recursion hold current combination.

here happens combination until first hits base case

[w] // add w, call recursively  [w, w] // add w, call recursively  [w, w, w] // add w, call recursively  

the base case met, , prints [w, w, w]. removes last color put in list, w, , adds next color in colors combination, gives [w, w, b]. base case met again prints out.

it continues until combinations have been printed.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -