I read objects(Movies) from a file and i compare based on their likes. I want to get the median after every Movie insertion in the queue. In the code below there are :
I'm creating both priority queues for higher and less objects than median, but i don't know how to dynamically calculate it. Every movie element is created with id, title, likes in this order.
public int compareTo(Movie m) {
if (this.likes == m.likes) {
return -this.title.compareTo(m.title);
} else if (this.likes > m.likes) {
return 1;
} else {
return -1;
}
}
public class PQ {
private Movie[] pq;
private int size;
public PQ(int capacity) {
if (capacity < 1) {
throw new IllegalArgumentException();
}
this.pq = new Movie[capacity + 1];
this.size = 0;
}
public void insert(Movie movie) {
if (this.size == this.pq.length - 1) {
throw new IllegalArgumentException();
}
if (movie == null) {
throw new IllegalArgumentException();
}
this.size++;
this.pq[this.size] = movie;
swim(this.size);
}
public void swim(int i) {
while (i > 1) {
int p = i / 2;
int result = this.pq[p].compareTo(this.pq[i]);
if (result <= 0)
return;
swap(i, p);
i = p;
}
}
public Movie Max() {
if (this.size == 0)
throw new IllegalArgumentException();
return this.pq[1];
}
public Movie getMax() {
if (this.size == 0)
throw new IllegalArgumentException();
Movie m = this.pq[1];
if (this.size > 1)
this.pq[1] = this.pq[this.size];
this.pq[this.size--] = null;
sink(1);
return m;
}
private void sink(int i) {
int left = 2 * i;
int right = left + 1;
int max = left;
while (left <= this.size) {
if (right <= this.size) {
max = this.pq[right].compareTo(this.pq[left]) < 0 ? right
: left;
}
if (this.pq[max].compareTo(this.pq[i]) >= 0)
return;
swap(i, max);
i = max;
left = 2 * i;
right = left + 1;
max = left;
}
}
private void swap(int i, int j) {
Movie tmp = pq[i];
pq[i] = pq[j];
pq[j] = tmp;
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Dynamic_Median {
public static void main(String[] args) {
BufferedReader br = null;
PQ higher_median = new PQ(4);
PQ less_median = new PQ(4);
Movie median = null;
try { // try to read the file
br = new BufferedReader(new FileReader("movies.txt"));
String line;
String title = "";
int id = 0;
int likes = 0;
while ((line = br.readLine()) != null) {
line = line.trim();
line = line.replaceAll("/t", "");
String[] tokens = line.split(" "); // store every token in an
// String array
id = Integer.parseInt(tokens[0]);
likes = Integer.parseInt(tokens[tokens.length - 1]);
for (int i = 1; i < tokens.length - 1; i++) {
title = title + " " + tokens[i];
}
title = "";
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ki esy re kopela mou teleftaia mera ths prothesmias thymithikes na rwthseis? :P
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.