Search code examples
anylogic

How to select agents using (randomWhere) from Main


What I want is to randomly select agents based on their parameters from Main. So, rather than selecting an agent by its index - agent.get(i) - I want to randomly select an agent by its properties.

I would love it if something like this is possible:

agent.get(randomWhere(agent, a -> a.age > 50 && a.health == "good" && ...));

I am aware that the randomWhere function will return the agent but, not its index. so is there a function that would do this directly?

The workaround I thought of is:

1- list all the agents using the filter function:

List agentslist = filter( agent, p -> p.p_gender == false && ...);

which would return something like :

[root.agent[1]( p_gender = false,...),root.agent[5]( p_gender = false,...),root.agent[17]( p_gender = false,...)]

2- I loop though the agentslist using Regex to get the index of each agent from what is between the [ ] in a new list. Based on this example this new list will have these values [1,5,17] .

3- Finally, I choose randomly from the new list and input its value in the agent.get(i) directly.

Is there a better way to do this?

Thanks in advance,


Solution

  • to get the index just use the getIndex() function.

    int index=randomWhere(yourAgents,a->a.age>50 && a.health.equals("good")).getIndex();
    agent.get(index);
    

    Remember to use equals() when you compare strings... "==" is only used effectively for primitives.