Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.*;
- public class PriorityStack {
- ArrayList <Job> stack = new ArrayList <Job>();
- // Methods
- public int size() {
- return stack.size();
- }
- public boolean empty() {
- if(stack.size() == 0) {
- return true;
- }
- else {
- return false;
- }
- }
- public double getMedianPriority() {
- //double[] priorities = new double[stack.size()];
- ArrayList <Double> priorities = new ArrayList <Double>();
- if(stack.size() %2 != 0) {
- for(int i=0; i<stack.size(); i++) {
- priorities.add(i, stack.get(i).priority);
- Collections.sort(priorities);
- int index = (stack.size() + 1) / 2;
- return priorities.get(index);
- }
- }
- else {
- for(int i=0; i<stack.size(); i++) {
- priorities.add(i, stack.get(i).priority);
- Collections.sort(priorities);
- int index1 = stack.size() / 2;
- int index2 = index1 + 1;
- double averagePriority = 0.5 * (priorities.get(index1) + priorities.get(index2));
- return averagePriority;
- }
- }
- }
- public boolean increasePriority(int p) {
- if(p > 0){
- if(size() != 0) {
- for(int i=0; i<stack.size(); i++) {
- stack.get(i).setPriority(stack.get(i).priority + p);
- }
- }
- return true;
- }
- else {
- return false;
- }
- }
- public void push(Job j) {
- stack.add(j);
- }
- public Job pop() {
- ArrayList <Double> priorities = new ArrayList <Double>();
- for(int i=0; i<stack.size(); i++) {
- priorities.add(i, stack.get(i).priority);
- }
- Collections.sort(priorities);
- // I find the maxPriority
- int index = priorities.size() - 1;
- double maxPriority = priorities.get(index);
- // 3 cases
- if(priorities.size() == 0) {
- System.out.println("Error! ArrayList stack is empty!");
- return new Job(-1000, "Error");
- }
- else if(priorities.size() == 1) {
- Job temp = stack.get(0);
- stack.remove(stack.get(0));
- return temp;
- }
- // Now, I check if there is another priority = maxPriority
- else {
- ArrayList <Job> sameMaxPriority = new ArrayList <Job>();
- for(int i=0; i<stack.size(); i++) {
- if(stack.get(i).priority == maxPriority) {
- sameMaxPriority.add(stack.get(i));
- }
- }
- Job temp = sameMaxPriority.get(sameMaxPriority.size() - 1);
- stack.remove(temp);
- return temp;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement