Logic problem with lists C#
i wanted to make gameobject list or array with all possible combination of enemies for example i have 3 enemies a, b and c and list should look like this: a, b, c, a+b, a+c, c+b, a+b+c, I tried to make this by list of custom class or multidimensional array but it doesn't work (I don't know how many enemies are there)
Answer by dpoly · May 02, 2017 at 02:10 AM
What you are describing is a 'combination'
"Alice, Bob and Charlie is the same as Charlie, Bob and Alice. Permutations are for lists (order matters) and combinations are for groups (order doesn't matter). A joke: A "combination lock" should really be called a "permutation lock". The order you put the numbers in matters."
There are specific algorithms to create a list that is a combination of a set of elements (web search it). You can't do it with a simple loop; essentially you either need to loop over an array of indexes into a list or a recursive function. Challenging stuff, if you're not an expert.
Answer by UnityCoach · May 01, 2017 at 08:59 PM
List of Lists would work, and multi-dimension arrays would work too.
GameObject [][] referencesArray;
referencesArray[0][0] = obj;
for (int i = 0 ; i < referencesArray.Length ; i++)
for (int g = 0 ; g < referencesArray[i].Length ; g++)
Debug.Log (g.name);
List<List<GameObject>> referencesList = new List<List<GameObject>>();
referencesList.Add (new List<GameObject>());
referencesList[0].Add (obj);
foreach (List l in referencesList)
foreach (GameObject g in l)
Debug.Log (g.name);
When you say it doesn't work, do you mean you can't assign them in the editor?
i mean that multi-dimensional array can't have 1 variable in first line and 3 in second(am i right?) and the only solutions i figured out with list of lists is to put them in foreach loop like this
GameObject[] enemylist;
List<List<GameObject>> listoflists;
List<GameObject> oneoflists;
public void $$anonymous$$akeListOfLists()
{
foreach (GameObject enemy in enemylist)
{
oneoflists.Clear();
oneoflists.Add(enemy);
listoflists.Add(oneoflists);
}
if (enemylist.Length > 1) {
foreach (GameObject enemy1 in enemylist)
{
foreach (GameObject enemy2 in enemylist)
{
if (enemy1 != enemy2)
{
oneoflists.Clear();
oneoflists.Add(enemy1);
oneoflists.Add(enemy2);
listoflists.Add(oneoflists);
}
} } } } }
but it don't make sense because if there gonna be more enemies i'll must add and add loops
You are correct, that is exactly the problem. And the solution is as per my answer. You can write an iterative solution using an array of loop indexes or a recursive solution using variable depth, but you cannot do it as above. Do you understand this, or is it just too hard?
i think i don't but i'll try to make research thx :P