Changing a variable changes the previously assigned variable as well - java

I'm having what I'm sure is a basic logic error but I can't seem to fix it. I'm sorting a GenericSimpleArrayList before creating a tree using both the unsorted (postorder) and sorted (inorder) lists. When I sort one of the lists it sorts them both? I'm not sure why.
public static <AnyType extends Comparable<? super AnyType>> BinaryNode<AnyType>constructBST ( GenericSimpleArrayList<AnyType> postorder ){
GenericSimpleArrayList <AnyType> g = postorder;
quicksort(postorder, new SortFunctor()); //this is where i sort the list.
GenericSimpleArrayList <AnyType> inorder = postorder;
return constructTree(inorder, g);
}
Can anyone help me fix this? Why does it sort both g and postorder when I only sort postorder? Thanks.
Edit: Added constructTree.
public static <AnyType> BinaryNode<AnyType> constructTree(GenericSimpleArrayList<AnyType> inorder, GenericSimpleArrayList<AnyType> postorder) {
int nodes = postorder.size();
AnyType root = postorder.get(nodes-1);
BinaryNode<AnyType> left = null;
BinaryNode<AnyType> right = null;
if (nodes > 1) {
int rootPos = 0;
for (int loop = 0; loop <= nodes-1; loop++) {
if (inorder.get(loop).equals(root)) {
rootPos = loop;
//System.out.println(loop);
} else {
//System.out.println("Not found at pos: " + loop);
}
}
if (rootPos != 0) {
GenericSimpleArrayList <AnyType> leftInorder = new GenericSimpleArrayList();//(AnyType) new Object[rootPos];
GenericSimpleArrayList <AnyType> leftPostorder = new GenericSimpleArrayList();//(AnyType[]) new Object[rootPos];
for (int loop = 0; loop < rootPos; loop++) {
leftInorder.add(inorder.get(loop));
leftPostorder.add(postorder.get(loop));
}
left = constructTree(leftInorder, leftPostorder );
}
if (rootPos < nodes-1){
GenericSimpleArrayList <AnyType> rightInorder = new GenericSimpleArrayList();//(AnyType[]) new Object[nodes - rootPos - 1];
GenericSimpleArrayList <AnyType> rightPostorder = new GenericSimpleArrayList();//(AnyType[]) new Object[rightInorder.length];
for (int loop = 0; loop < nodes-rootPos-1; loop++){
rightInorder.add(inorder.get(rootPos + loop + 1));
rightPostorder.add(postorder.get(rootPos + loop));
}
right = constructTree(rightInorder, rightPostorder);
}
}
return new BinaryNode<AnyType>(root, left, right);
}

Why does it sort both g and postorder when I only sort postorder?
GenericSimpleArrayList <AnyType> g = postorder;
postorder is a reference to an object. When you copy this reference you now have two references to an object. However there is still only one object.
I don't know the API to your custom ArrayList but I assume you can do
GenericSimpleArrayList<AnyType> g = new GenericSimpleArrayList<AnyType>(postorder);
or
GenericSimpleArrayList<AnyType> g = new GenericSimpleArrayList<AnyType>();
for(AnyType at: postorder)
g.add(at);
Most likely your sorting utility sorts the collection in place. This is very common for sort functions to alter the original list.
If you want to preserve both the original order and sort the list, I suggest first taking a copy of the list.
An alternetive is to use a different structures like a TreeMap to record the String in sorted order and the index of the original position.

GenericSimpleArrayList <AnyType> g = postorder;
GenericSimpleArrayList <AnyType> inorder = postorder;
In these two statements, all the three variable will be referring to the same reference hold by postorder initially. Because you are doing reference assignment and update in one object state will reflect into all the reference variable.
constructTree(inorder, g);
So when you make the above call then you are passing the same same reference.

In this line:
GenericSimpleArrayList <AnyType> g = postorder;
you only define a new name g for the same object. If you want g to be a different List, you need to create it newly (that is really call the constructor) and copy postorder's contents into it.

Related

MEX from root node to every other node in a tree

Given a rooted tree having N nodes. Root node is node 1. Each ith node has some value , val[i] associated with it.
For each node i (1<=i<=N) we want to know MEX of the path values from root node to node i.
MEX of an array is smallest positive integer not present in the array, for instance MEX of {1,2,4} is 3
Example : Say we are given tree with 4 nodes. Value of nodes are [1,3,2,8] and we also have parent of each node i (other than node 1 as it is the root node). Parent array is defined as [1,2,2] for this example. It means parent of node 2 is node 1, parent of node 3 is node 2 and parent of node 4 is also node 2.
Node 1 : MEX(1) = 2
Node 2 : MEX(1,3) = 2
Node 3 : MEX(1,3,2) = 4
Node 4 : MEX(1,3,8) = 2
Hence answer is [2,2,4,2]
In worst case total number of Nodes can be upto 10^6 and value of each node can go upto 10^9.
Attempt :
Approach 1 : As we know MEX of N elements will be always be between 1 to N+1. I was trying to use this understanding with this tree problem, but then in this case N will keep on changing dynamically as one proceed towards leaf nodes.
Approach 2 : Another thought was to create an array with N+1 empty values and then try to fill them as we go along from root node. But then challenge I faced was on to keep track of first non filled value in this array.
public class TestClass {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter wr = new PrintWriter(System.out);
int T = Integer.parseInt(br.readLine().trim());
for(int t_i = 0; t_i < T; t_i++)
{
int N = Integer.parseInt(br.readLine().trim());
String[] arr_val = br.readLine().split(" ");
int[] val = new int[N];
for(int i_val = 0; i_val < arr_val.length; i_val++)
{
val[i_val] = Integer.parseInt(arr_val[i_val]);
}
String[] arr_parent = br.readLine().split(" ");
int[] parent = new int[N-1];
for(int i_parent = 0; i_parent < arr_parent.length; i_parent++)
{
parent[i_parent] = Integer.parseInt(arr_parent[i_parent]);
}
int[] out_ = solve(N, val, parent);
System.out.print(out_[0]);
for(int i_out_ = 1; i_out_ < out_.length; i_out_++)
{
System.out.print(" " + out_[i_out_]);
}
System.out.println();
}
wr.close();
br.close();
}
static int[] solve(int N, int[] val, int[] parent){
// Write your code here
int[] result = new int[val.length];
ArrayList<ArrayList<Integer>> temp = new ArrayList<>();
ArrayList<Integer> curr = new ArrayList<>();
if(val[0]==1)
curr.add(2);
else{
curr.add(1);
curr.add(val[0]);
}
result[0]=curr.get(0);
temp.add(new ArrayList<>(curr));
for(int i=1;i<val.length;i++){
int parentIndex = parent[i-1]-1;
curr = new ArrayList<>(temp.get(parentIndex));
int nodeValue = val[i];
boolean enter = false;
while(curr.size()>0 && nodeValue == curr.get(0)){
curr.remove(0);
nodeValue++;
enter=true;
}
if(curr.isEmpty())
curr.add(nodeValue);
else if(!curr.isEmpty() && curr.contains(nodeValue) ==false && (enter|| curr.get(0)<nodeValue))
curr.add(nodeValue);
Collections.sort(curr);
temp.add(new ArrayList<>(curr));
result[i]=curr.get(0);
}
return result;
}
}
This can be done in time O(n log n) using augmented BSTs.
Imagine you have a data structure that supports the following operations:
insert(x), which adds a copy of the number x.
remove(x), which removes a copy of the number x.
mex(), which returns the MEX of the collection.
With something like this available, you can easily solve the problem by doing a recursive tree walk, inserting items when you start visiting a node and removing those items when you leave a node. That will make n calls to each of these functions, so the goal will be to minimize their costs.
We can do this using augmented BSTs. For now, imagine that all the numbers in the original tree are distinct; we’ll address the case when there are duplicates later. Start off with Your BST of Choice and augment it by having each node store the number of nodes in its left subtree. This can be done without changing the asymptotic cost of an insertion or deletion (if you haven’t seen this before, check out the order statistic tree data structure). You can then find the MEX as follows. Starting at the root, look at its value and the number of nodes in its left subtree. One of the following will happen:
The node’s value k is exactly one plus the number of nodes in the left subtree. That means that all the values 1, 2, 3, …, k are in the tree, so the MEX will be the smallest value missing from the right subtree. Recursively find the MEX of the right subtree. As you do, remember that you’ve already seen the values from 1 to k by subtracting k off of all the values you find there as you encounter them.
The node’s value k is at least two more than the number of nodes in the left subtree. That means that the there’s a gap somewhere in the node’s in the left subtree plus the root. Recursively find the MEX of the left subtree.
Once you step off the tree, you can look at the last node where you went right and add one to it to get the MEX. (If you never went right, the MEX is 1).
This is a top-down pass on a balanced tree that does O(1) work per node, so it takes a total of O(log n) work.
The only complication is what happens if a value in the original tree (not the augmented BST) is duplicated on a path. But that’s easy to fix: just add a count field to each BST node tracking how many times it’s there, incrementing it when an insert happens and decrementing it when a remove happens. Then, only remove the node from the BST in the case where the frequency drops to zero.
Overall, each operation on such a tree takes time O(log n), so this gives an O(n log n)-time algorithm for your original problem.
public class PathMex {
static void dfs(int node, int mexVal, int[] res, int[] values, ArrayList<ArrayList<Integer>> adj, HashMap<Integer, Integer> map) {
if (!map.containsKey(values[node])) {
map.put(values[node], 1);
}
else {
map.put(values[node], map.get(values[node]) + 1);
}
while(map.containsKey(mexVal)) mexVal++;
res[node] = mexVal;
ArrayList<Integer> children = adj.get(node);
for (Integer child : children) {
dfs(child, mexVal, res, values, adj, map);
}
if (map.containsKey(values[node])) {
if (map.get(values[node]) == 1) {
map.remove(values[node]);
}
else {
map.put(values[node], map.get(values[node]) - 1);
}
}
}
static int[] findPathMex(int nodes, int[] values, int[] parent) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>(nodes);
HashMap<Integer, Integer> map = new HashMap<>();
int[] res = new int[nodes];
for (int i = 0; i < nodes; i++) {
adj.add(new ArrayList<Integer>());
}
for (int i = 0; i < nodes - 1; i++) {
adj.get(parent[i] - 1).add(i + 1);
}
dfs(0, 1, res, values, adj, map);
return res;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int nodes = sc.nextInt();
int[] values = new int[nodes];
int[] parent = new int[nodes - 1];
for (int i = 0; i < nodes; i++) {
values[i] = sc.nextInt();
}
for (int i = 0; i < nodes - 1; i++) {
parent[i] = sc.nextInt();
}
int[] res = findPathMex(nodes, values, parent);
for (int i = 0; i < nodes; i++) {
System.out.print(res[i] + " ");
}
}
}

Merge communities and find a size of the largest one

I'm struggling with this problem on HackerRank.
https://www.hackerrank.com/challenges/friend-circle-queries/problem
I tried solving it using a custom linked list - NodeList. It has three fields - Node first, Node current, int size. 'add' is an overloaded method. It can add a value or another NodeList.
I have put code for NodeList in comments because it doesn't matter much.
Fields :-
static HashMap<Integer, Integer> personToIndex = new HashMap<>();
static int largestCircleSize = 0;
static ArrayList<NodeList> groups = new ArrayList<>();
This is my business logic method.
When only one person is part of a friend circle, I add the other person in the circle. When both the people who are shaking hands are already part of other circles, I merge the circles.
static void updateFriendCircles(int friend1, int friend2) {
int friend1Index, friend2Index;
NodeList toUpdate;
friend1Index = personToIndex.getOrDefault(friend1, -1);
friend2Index = personToIndex.getOrDefault(friend2, -1);
if (friend1Index != -1) {
NodeList list = groups.get(friend1Index);
if (friend2Index != -1) {
NodeList list2 = groups.get(friend2Index);
if (list.first == groups.get(friend2Index).first)
return;
toUpdate = list.add(list2);
groups.set(friend2Index, list);
}
else {
toUpdate = list.add(friend2);
personToIndex.put(friend2, friend1Index);
}
}
else if (friend2Index != -1) {
toUpdate = groups.get(friend2Index).add(friend1);
personToIndex.put(friend1, friend2Index);
}
else {
int index = groups.size();
personToIndex.put(friend1, index);
personToIndex.put(friend2, index);
toUpdate = new NodeList(friend1).add(friend2);
groups.add(toUpdate);
}
if (toUpdate.size > largestCircleSize)
largestCircleSize = toUpdate.size;
}
I have also tried using HashSet but it also has same problem so I think problem is not in data structure.
As it's not clear what is wrong with the solution exactly (it's not specified by the OP) - wrong answers or timeout for some test cases I'll explain how to solve it.
We can use a disjoint set data structure to represent sets of friend circles.
The basic idea is that in each circle we assign a member that is used to represent a given circle. We can call it a root. Finding a number of members in the circle is always delegated to the root that stores its size.
Each non-root member points to his root member or to a member through whom he can get to the root. In the future, the current root may also lose his root status for the community but then it will point to the new root and so it's always possible to get to it through chained calls.
When 2 circles merge then a new root member is chosen among 2 previous ones. The new size can be set into it because previous roots already contain sizes for both circles. But how is the new root chosen? If the size of circle 1 is not smaller than that of circle 2 then it's picked as a new root.
So, for this problem, first we should define placeholders for circles and sizes:
Map<Integer, Integer> people;
Map<Integer, Integer> sizes;
For non-root members in people, key is a person ID and value is a friend he follows (root or parent that can get him to the root). Root members won't have an entry in the map.
Then, we need a method that will get us to the root for any member:
int findCommunityRoot(int x) {
if (people.containsKey(x)) {
return findCommunityRoot(people.get(x));
}
return x;
}
Finally, we need a method to build a community for 2 given friends:
int mergeCommunities(int x, int y) {
//find a root of x
x = findCommunityRoot(x);
//find a root of y
y = findCommunityRoot(y);
// one-man circle has a size of 1
if (!sizes.containsKey(x)) {
sizes.put(x, 1);
}
// one-man circle has a size of 1
if (!sizes.containsKey(y)) {
sizes.put(y, 1);
}
// friends in the same circle so just return its size
if (x == y) {
return sizes.get(x);
}
sizeX = sizes.get(x);
sizeY = sizes.get(y);
if (sizeX >= sizeY) {
people.put(y, x);
sizes.put(x, sizeY + sizeX);
return sizes.get(x);
} else {
people.put(x, y);
sizes.put(y, sizeY + sizeX);
return sizes.get(y);
}
}
So, we have everything we need to save a size of the largest circle at each iteration:
List<Integer> maxCircle(int[][] queries) {
List<Integer> maxCircles = new ArrayList<>();
int maxSize = 1;
for (int i = 0; i < queries.length; i++) {
int size = mergeCommunities(queries[i][0], queries[i][1]);
maxSize = Math.max(maxSize, size);
maxCircles.add(maxSize);
}
return maxCircles;
}

How to pass the objects of two arraylists to one another at a specified index

So, I am trying to print out my arraylists in order of the objects area. I cannot however seem to figure out how to pass the values of objects to one another at an index. (I must do it recursively).
Here is my code thusfar
private static void recursionSort(ArrayList<GeometricObject> data)
{
if(data.size() <= 1) return; // Base case: just 1 elt
ArrayList<GeometricObject> a = new ArrayList<GeometricObject>(data.size() / 2);
ArrayList<GeometricObject> b = new ArrayList<GeometricObject>(data.size() - a.size()); // Split array into two
// halves, a and b
for(int i = 0; i < data.size(); i++)
{
if(i < a.size())
a.indexOf(i) = data.get(i);
else
b.get(i - a.size()) = data.get(i);
}
recursionSort(a); // Recursively sort first
recursionSort(b); // and second half.
int ai = 0; // Merge halves: ai, bi
int bi = 0; // track position in
while(ai + bi < data.size()) { // in each half.
if(bi >= b.size() || (ai < a.size() && a.get(ai).getArea() < b.get(bi).getArea())) {
data.get(ai + bi) = a.get(ai); // (copy element of first array over)
ai++;
} else {
data.get(ai + bi) = b.get(bi); // (copy element of second array over)
bi++;
}
}
}
My issue is with the lines
a.indexOf(i) = data.get(i);
b.get(i - a.size()) = data.get(i);
data.get(ai + bi) = a.get(ai);
data.get(ai + bi) = b.get(bi);
For example I can't figure out how to get say the index of a at 0 to equal my list's (data) index of 0. If these were arrrays, i would know what to do, so let me use that as an example to show you what I'm trying to accomplish just via arraylists
a[i] = data[i]; // First line in block above
data[ai + bi] = b[bi]; // Last line in block above
Any help would be greatly appreciated. I've went through almsot every method found in my book's list of ArrayList Class methods and none have the desired effect I'm looking for. Thanks!
The List interface defines the set(int index, E element) (E = GeometricObject in the present case). Therefore, the four lines you're having trouble with should be rewritten as follows:
a.set(i, data.get(i));
b.set(i - a.size(), data.get(i));
data.set(ai + bi, a.get(ai));
data.set(ai + bi, b.get(bi));
Hope this helps...
Jeff
You don't have to implement sort method to sort an Arraylist with your custom objects. You can make use of Collections.sort(arraylist) to do the same.
To make use of the same you need to either use Comparator or Comparable interface as per your need.
If you use Comparable interface, you code will look like :
public class GeometricObject implements Comparable<GeometricObject>
{
// member variables
// other methods
#Override
public int compareTo(GeometricObject comparesToObject)
{
// wil sort in ascending order.
return this.getArea()-comparesToObject.getArea();
// Use the commented line for descending order
// return comparesToObject.getArea() - this.getArea();
// Use return Float.compare(area1, area2) if area is of type float.
}
}
// This will now sort your data Arraylist.
Collections.sort(data);

Dijkstra Algorithm method returning empty path

I have attempted to implement Dijkstra's algorithm from the Pseudocode on the Wikipedia page. I have set a condition after the Queue is polled that tests if the current node is the target node, b. If so, then the Algorithm is to break and return the path from a to b.
This condition will always be satisfied as I know that all nodes within the range of the Adjacency Matrix do indeed exist. The program is to model the connections of the London Underground map.
Anyway, I have been trying to figure this out for a while now, and thus far it eludes me. Maybe somebody can spot the issue. Oh, adj is just the adjacency matrix for my graph.
/**
Implementation of Dijkstra's Algorithm taken from "Introduction to
Algorithms" by Cormen, Leiserson, Rivest and Stein. Third edition.
d = Array of all distances.
pi = Previous vertices.
S = Set of vertices whose final shortest path weights have been
determined.
Q = Priority queue of vertices.
**/
public ArrayList<Integer> dijkstra(Integer a, Integer b){
final double[] d = new double[adj.length];
int[] pi = new int[adj.length];
HashSet<Integer> S = new HashSet<Integer>();
PriorityQueue<Integer> Q = new PriorityQueue<Integer>(d.length, new Comparator<Integer>(){
public int compare(Integer a, Integer b){
Double dblA = d[a-1];
Double dblB = d[b-1];
return dblA.compareTo(dblB);
}
});
for(int i=0; i<d.length; i++){
d[i] = Double.POSITIVE_INFINITY;
}
d[a] = 0f;
for(int i=0; i<d.length; i++){
Q.add(i+1);
}
while(Q.size() > 0){
int u = Q.poll();
if(u == b){
System.out.println("jjd");
ArrayList<Integer> path = new ArrayList<Integer>();
for(int i=pi.length-1; i>=0; i--){
path.add(pi[i]);
}
return path;
}
S.add(u);
if(d[u] == Double.POSITIVE_INFINITY){
break;
}
for(int v=0; v<adj.length; v++){
double tmp = d[u] + adj[u][v];
if(tmp < d[v]){
d[v] = tmp;
pi[v] = u;
}
}
}
return new ArrayList<Integer>();
}
}
EDIT:- After doing some debugging, it seems that the body of the while loop is being executed only once.
if(d[u] == Double.POSITIVE_INFINITY){
break;
}
for(int v=0; v<adj.length; v++){
double tmp = d[u] + adj[u][v];
if(tmp < d[v]){
d[v] = tmp;
pi[v] = u;
}
}
The changing of the d values in the loop body doesn't rearrange the priority queue, so unless the element that happened to be at the top of the queue after popping the initial node is one of its neighbours, you will have d[u] == Double.POSITIVE_INFINITY in the next iteration and break then.
In Dijkstra's algorithm, it is important that the queue be updated when the distance of a node changes. java.util.PriorityQueue<E> doesn't offer that functionality, so using that is non-trivial, I see no way to use it other than removing and re-adding the updated nodes on every update. That is of course not very efficient, since removal is O(size).
The inefficiency can be mitigated by not having all nodes in the queue. Star with adding only the initial node, and in the loop, insert only the neighbours not yet seen, remove and reinsert the neighbours that already are in the queue. That keeps the queue shorter, and makes removal cheaper on average.
For an efficient implementation, you would need a custom priority queue that allows faster (O(log size)?) update of priorities.
If you get 'jjd' outputted in the console when you run the program from your System.out.println your problem should be this:
if(u == b){
System.out.println("jjd");
ArrayList<Integer> path = new ArrayList<Integer>();
for(int i=pi.length-1; i>=0; i--){
path.add(pi[i]);
}
return path;
When you are calling the 'return path;' you actually break the whole method and return 'path'.

Java Recursion, calling it with Objects - How To Copy The Objects?

The old value/reference things. Im getting ConcurrentModificationException
for this adaptation of the Bron-Kerbosch.
public int[] bk(ArrayList<Integer> R, ArrayList<Integer> P, ArrayList<Integer> X) {
int count[] = new int[n];
int u=0, c = 0;
ArrayList<Integer> tempPX = new ArrayList<Integer>();
ArrayList<Integer> newP = P;
ArrayList<Integer> newX = X;
ArrayList<Integer> newR = R;
if (P.isEmpty() && X.isEmpty()) {
count[R.size()]++;
} else {
u = 0; c = 0; // find vertex with largest degree
tempPX.addAll(P); tempPX.addAll(X); // P ⋃ X
for (Integer v : tempPX) {
if (neighbours[v].size() > neighbours[u].size()) {
u = c;
}
c++;
}
P.removeAll(neighbours[u]); // P \ neighbours[u]
for (Integer v : newP) {
newR.add(v); // R ⋃ v
newP.retainAll(neighbours[v]); // P â‹‚ neighbours[v]
newX.retainAll(neighbours[v]); // X â‹‚ neighbours[v]
bk(newR, newP, newX);
P.remove(v); // removing object
X.add(v); // X ⋃ v
}
}
return count;
}
The exception occurs at line for (Integer v : newP), and the recursive call in there.
I need to P.removeAll(neighbours[u]); then loop over that resulting list, inside doing the things in the comments, AND PASS COPIES in the recursive call so it wont complain and work not pass the references and keep modifying the same object P/X/R. So how and WHEN do i copy them?? Those first lines.. I'm making copies of the references aren't i...
(yes i know i "modify" newP then loop over the old P, they just point to the same object it seems)
--- new code after reading the replies -
public int[] bk(List<Integer> r, List<Integer> p, List<Integer> x) {
int count[] = new int[n];
int u = 1;
List<Integer> tempPX = new ArrayList<Integer>();
List<Integer> newR, newP, newX;
if (p.isEmpty() && x.isEmpty()) {
count[r.size()]++;
} else {
// find vertex with largest degree in P U X
tempPX.addAll(p);
tempPX.addAll(x);
for (Integer v : tempPX) {
if (neighbours[v].size() > neighbours[u].size()) {
u = v;
}
}
p.removeAll(neighbours[u]); // P \ neighbours[u]
newP = new ArrayList<Integer>(p);
for (Integer v : newP) {
r.add(v); // R U v
newR = new ArrayList<Integer>(r);
p.retainAll(neighbours[v]); // P /\ neighbours[v]
newP = new ArrayList<Integer>(p);
x.retainAll(neighbours[v]); // X /\ neighbours[v]
newX = new ArrayList<Integer>(x);
bk(newR, newP, newX);
p.remove(v); // removing object
x.add(v); // X U v
}
}
return count;
}
As you've identified, you're copying the reference, not the list. You need to instantiate a new ArrayList object with the entries in the old list.
e.g.
List<Integer> newList = new ArrayList<Integer>(oldList);
So this explicitly creates a new object containing references to the same elements.
Note as an aside that I pass around a reference to the interface List rather than the implementation - generally good practise since you're not exposing implementation throughout the codebase.
ArrayList newP = P;
This only creates a second reference to the same ArrayList. To copy the arraylist use
ArrayList newP = new ArrayList(P);
Your first && check is redundant, originally the check was with the X argument?
Also, your for loop at the start of the else block doesn't make any sense, what are you trying to do there? The thing is that you are both using a counter (c) and the contents of the tempPX list (v). You use v to do the check but c as the assignment. The result is totally dependent on data ordering and doesn't produce anything meaningful.
Normally you'd use one or the other and use it both in the check and the assignment.
if (p.isEmpty() && p.isEmpty()) {
count[r.size()]++;
} else {
u = 0; c = 0; // find vertex with largest degree
tempPX.addAll(p); tempPX.addAll(x); // P U X
for (Integer v : tempPX) {
if (neighbours[v].size() > neighbours[u].size()) {
u = c;
}
c++;
}
Either your goal is to find the index in the temppx list with the largest amount of neighbours (drop the c variable and the c++ line, use v in the assignment) OR to just find the index with the largest amount of neighbours without any restriction on the index, in that case you would use a for loop like this:
for (int c = 0; c < neighbours.size(); ++c)
and drop any mention of the temppx list. My guess is your trying to do the first case.

Categories

Resources