Queue Removals

	public static class Pair {
		int index;
		int value;

		public Pair(int index, int value) {
			super();
			this.index = index;
			this.value = value;
		}

		public int getIndex() {
			return index;
		}

		public void setIndex(int index) {
			this.index = index;
		}

		public int getValue() {
			return value;
		}

		public void setValue(int value) {
			this.value = value;
		}

	}

	public static int[] findPositions(int[] arr, int x) {
		Queue<Pair> q = new LinkedList<Pair>();
		for (int i = 0; i < arr.length; i++)
			q.add(new Pair(i + 1, arr[i]));
		ArrayList<Integer> removed = new ArrayList<Integer>();
		for (int i = x; i >= 1; i--) {
			int pops = x;
			PriorityQueue<Pair> maxHeap = new PriorityQueue<Pair>(new Comparator<Pair>() {
				@Override
				public int compare(Pair o1, Pair o2) {
					if (o1.getValue() == o2.getValue())
						return Integer.compare(o1.getIndex(), o2.getIndex());
					return -Integer.compare(o1.getValue(), o2.getValue());
				}
			});
			Queue<Pair> temp = new LinkedList<Pair>();
			while (pops != 0 && !q.isEmpty()) {
				Pair c = q.poll();
				maxHeap.add(c);
				temp.add(c);
				pops--;
			}
			Pair ToRemove = maxHeap.remove();
			int ToRemoveIndex = ToRemove.getIndex();
			removed.add(ToRemoveIndex);
			while (!temp.isEmpty()) {
				Pair a = temp.poll();
				if (a.getIndex() != ToRemoveIndex) {
					q.add((a.getValue() > 0) ? new Pair(a.getIndex(), a.getValue() - 1) : a);
				}
			}
		}
		int[] out = new int[removed.size()];
		for (int i = 0; i < out.length; i++)
			out[i] = removed.get(i);
		return out;
	}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s