Reputation: 2871
I'm building a railway simulator including the classes Passenger and Station (among others). The Passenger class has an attribute endLoc, which will be the desired end location for each passenger (i.e. a station object). I'm generating a random number of passengers at each station on my network into an ArrayList, and would like their attribute of endLoc to be randomly generated as well (out of a list of all the station objects), but I can't work out how to make the attribute be a random one from a list each time.
ArrayList<Passenger> passengers = new ArrayList<Passenger>();
for (int i = 0; i<p; i++){
passengers.add(new Passenger(statA));
i.e. Once I have my random number, and have it mapped to which station I want, what do I put in the code instead of statA, to mean the station that applies to my random number?
Can anyone tell me how to do this, or at least point me in the right direction? Thanks.
Upvotes: 0
Views: 1787
Reputation: 34387
Write something like this:
List<String> stations = new ArrayList<String>();
//add stations..in the list
int numStations = stations.size();
int maxPassengersAtStation = 100;//assgin you number
for(int sCount=0; sCount<numStations; sCount++){
int passangersAtStation = (int)(Math.random() * maxPassengersAtStation);
for(int j=0; j<passangersAtStation; j++){
int passengerDestination = sCount + (int)(
Math.random() * ((numStations - sCount) + 1));
passengers.add(new Passenger(stations.get(passengerDestination)));
}
}
Upvotes: 1
Reputation: 5045
Generate a random int x and then do x = x % allStations.size(); The x would be your random index of the list with all stations.
Upvotes: 0
Reputation: 859
Well, some random ideea would be to generate a number from 1 to your_list.length and then take that object from the list and assing it to your endLoc.
Upvotes: 0