Reputation: 1
I was wondering if there is any method to display the highest and the smallest number of items stored in array/linkedlist.
public Checkout()
{
tillQueue = new LinkedList<String>();
currentLen = 0;
lengthList = new ArrayList <Integer>();
mean = 0;
r = new Random();
}
public void simulation()
{
System.out.println("Time" + "\t" + "Rnd" + "\t" + "Queue Status");
for (int t=2; t<10; t++) //number of time-steps in the simulation.
{
rndNumber = r.nextInt(6) +1; // generates random number between 1 and 6.
if (rndNumber==4 || rndNumber==2 || rndNumber==6)
{
// if rndNumber is 4, t is added to a queue.
tillQueue.add(String.valueOf(t));
currentLen++;
}
else if ((rndNumber==1 || rndNumber==3) && !tillQueue.isEmpty())
{
tillQueue.remove();
currentLen--;
//if rndNumber is either 1 or 3, person is removed from the queue
}
and that's the outcome:
Queue number 1
Queue
[2]
[2, 3]
[2, 3, 4]
[3, 4]
[3, 4]
[4]
Queue is empty
Queue is empty
Mean length of queue 1= 1.375
Max length of queue 1= 0.0
Min length of queue 1= 0.0
As you can see from the output the highest number of people is 3 (2,3,4) and lowest 0 (empty) How can I calculate those values?
Upvotes: 0
Views: 307
Reputation: 777
If you are intending to use lengthList,
Before the loop or business logic,
lengthList.add(tillQueue.size())
During the loop or any business logic, after any add or remove operations,
lengthList.add(tillQueue.size())
After your implementation is complete, as Sergio suggested,
Integer max_number = Collections.max(lengthList);
Integer min_number = Collections.min(lengthList);
Upvotes: 0
Reputation: 463
If your intent is to track the length of the list as it changes, you will need to calculate the number of members at each step. So, outside of the for loop, int count = 0;
then, at the end of the loop add an conditional statement that updates if the current length is greater than the current max
public void simulation()
{
System.out.println("Time" + "\t" + "Rnd" + "\t" + "Queue Status");
int count = 0;
for (int t=2; t<10; t++) //number of time-steps in the simulation.
{
//do all your stuff...
if (count > tillQueue.size())
{
count = tillQueue.size();
}
}
The same principle would apply to the least value, though I think in this case it is always 0?
Upvotes: 0
Reputation: 3754
You could use the Collections class.
Integer max_number = Collections.max(arrayList);
Integer min_number = Collections.min(arrayList);
See: http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
Upvotes: 5