2

I have an agent class that does things:

public class Agent {


private Context<Object> context;
    private Geography<Object> geography;
    public int id;
    boolean female;

public Agent(Context<Object> context, Geography<Object> geography, int id, boolean female) {
    this.id = id;
    this.context = context;
    this.geography = geography;
    this.female = female;
}  

... setters getters
... do things methods

}

In the context builder class, where my agents are added into the context (geographic space composed of latitude and longitude coordinates), I want to make a random percentage of my Agents female (female = true).

for (int i = 0; i < 100; i++) {
        Agent agent = new Agent(context, geography, i, false);
        int id = i++;
        if(id > 50) {
            boolean female = true;  
        }
        context.add(agent);
        //specifies where to add the agent
        Coordinate coord = new Coordinate(-79.6976, 43.4763);
        Point geom = fac.createPoint(coord);
        geography.move(agent, geom);
    }

I believe the code above constructs the last 50 agents as female. How can I make it so they are randomly created as female? I change the number of agents created quite a bit.

Taylor Marie
  • 357
  • 1
  • 15

3 Answers3

2

with your code, you ALWAYS create an agent that is MALE.

try to evaluate if it's female before creating an instance of Agent:

Agent agent = null;
boolean isFemale = false;
for (int i = 0; i < 100; i++) {
        int id = i++;
        if(id > 50) {
            isFemale = true;
        }
        agent = new Agent(context, geography, i, isFemale);
        context.add(agent);
        //specifies where to add the agent
        Coordinate coord = new Coordinate(-79.6976, 43.4763);
        Point geom = fac.createPoint(coord);
        geography.move(agent, geom);
    }

if you want it random, try using Random utility:

        Random random = new Random();
        agent = new Agent(context, geography, i, random.nextBoolean());

hope this helps

jmcg
  • 1,547
  • 17
  • 22
  • 1
    `agent = new Agent(context, geography, i, isFemale);` can be moved outside of the if and else statements. – user253751 Feb 25 '15 at 02:41
  • and then you can remove isFemale altogether by doing: agent = new Agent(context, geography, i, id>50); – thang Feb 25 '15 at 02:46
  • I'm good with that. That's based on the OP's code anyway. the OP can optimize it further =) – jmcg Feb 25 '15 at 02:47
  • and chances are that you can move coord = ... and geom = ... outside of the loop. – thang Feb 25 '15 at 02:48
0

You can create a single instance of Random outside your for loop and use random.nextBoolean() as a parameter for your boolean female attribute of agent().

happyHelper
  • 119
  • 8
-1
        Random random = new Random();

        for (int i=0; i < 100; i++)
        {
            boolean isFemale = (random.Next(2) % 2 == 1);
            ...
        }
khablander
  • 159
  • 1
  • 5