Can't get code to complie - java

I'm trying to learn Prim's algorithm and I'm using this website to do so, but I'm having trouble making the code part of it run. I'm confused with what goes in public static int Prims(Vector<Vector<node>> adjList) and how to get the code to compile and run. (New to java so excuse me if its a silly question).
edit: This is the code I'm trying to run:
class node implements Comparable<node> {
int weight, index;
public node(int weight, int index) {
this.weight = weight;
this.index = index;
}
public int compareTo(node e) {
return weight - e.weight;
}
}public static int Prims(Vector<Vector<node>> adjList) {
// Current cost of MST.
int cost = 0;
int n = adjList.size();
PriorityQueue<node> pq = new PriorityQueue<node>();
// Keep track if each node is visited.
boolean visited[] = new boolean[n];
for (int i = 0; i < n; i++) {
visited[i] = false;
}
// Number of nodes visited.
int inTree = 1;
// Mark starting node as visited.
visited[0] = true;
// Add all edges of starting node.
for (int i = 0; i < adjList.get(0).size(); i++) {
pq.add(adjList.get(0).get(i));
}
// Keep going until all nodes visited.
while (!pq.isEmpty() && inTree < n) {
// Get the edge with the smallest weight.
node cur = pq.poll();
// Skip if node already used.
if (visited[cur.index]) {
continue;
}
inTree++;
visited[cur.index] = true;
cost += cur.weight;
// Add all the edges of the new node to the priority queue.
for (int i = 0; i < adjList.get(cur.index).size(); i++) {
pq.add(adjList.get(cur.index).get(i));
}
}
// Graph not connected if number of nodes used is less than total nodes.
if (inTree < n) {
return -1;
}
return cost;
}

Your method public static int Prims(Vector<Vector<node>> adjList) does not appear to be a member of a class. It needs to be. The leading } on the line
}public static int Prims(Vector<Vector<node>> adjList) {
should probable be moved to the end of the file.

If you do not use an IDE to compile and run a code you need to issue the following commands:
javac MyCode.java
java MyCode
where I suppose your code resides in a file named MyCode.java and there is no package defined.

Related

Connectivity of a graph in java

I've implemented a BFS algorithm from my textbook and I am trying to modify it to throw an exception when it discovers a non-connected graph. My BFS using an array of boolean to store if a node has been reached or not. After running the BFS from the root node I thought I could iterate through the array and check if each node was reached. My code throws an exception every time and I cannot figure out why. Any guidance would be appreciated thanks!
Code:
private int bfs(Graph G, int s) {
int d = 0;
Queue<Integer> q = new Queue<>();
int distTo[] = new int[G.V()], max = 0;
boolean[] marked = new boolean[G.V()];
int[] edgeTo = new int[G.V()];
for(int v = 0; v < G.V(); v++) {
distTo[s] = Integer.MAX_VALUE;
marked[s] = true;
distTo[s] = 0;
q.enqueue(s);
}
while(!q.isEmpty()) {
d = q.dequeue();
for(int w : G.adj(d)) {
if(!marked[w]) {
edgeTo[w] = d;
distTo[w] = distTo[d] + 1;
marked[w] = true;
q.enqueue(w);
}
}
for(boolean x : marked) {
if(x == false) throw new RuntimeException("not a connected graph.");
}
}
return d;
}
You check for connectivity after processing each vertex. Only in the simplest graphs will the test succeed after the first vertex.
Instead you should seed the queue with one vertex and move the for loop testing for connectivity out of the while loop.

ClassCastException to comparable

i'm making a school project wehere we have to implement the A* algorithm to solthe the 8-puzzle problem. When creating a Node and adding it to the queue, there is no problem, but when I create a second one, and try to add it to the queue, it can't compate them both, to check wich has the lowest f-cost.
private class Node implements Comparable<Node>{
private Node parent;
private int distance;
private int moves;
private Board board;
public Node(Node parent, Board board, int moves) {
this.parent = parent;
this.board = board;
this.moves = moves;
distance = board.manhattan();
}
#Override
public int compareTo(Node node) {
return this.moves + this.distance - node.moves - node.distance;
}
}
this is the class where I create my Node's.
Now when trying to test if this works, I created a slamm JUnit test to see if it would work, but I get the error that my Node class cannot be cast to a comparable.
Here is the code of the test I'm trying to run:
import java.util.PriorityQueue;
import org.junit.Test;
public class UnitTests {
private PriorityQueue<Node> closedPQ = new PriorityQueue<Node>();
#Test
public void pqTest() {
int N = 3, counter = 1;
int[][] tiles = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
tiles[i][j] = counter++;
}
}
tiles[2][2] = 0;
tiles[1][1] = 6;
tiles[1][2] = 5;
Board initial = new Board(tiles);
tiles[1][1] = 5;
tiles[1][2] = 6;
Board initial2 = new Board(tiles);
System.out.println(initial.manhattan());
System.out.println(initial2.manhattan());
closedPQ.add(new Node(null, initial, 0));
closedPQ.add(new Node(null, initial2, 0));
Node n = closedPQ.remove();
System.out.println(n.distance);
}
}
First u just make a new board, and then change some nubers to get different costs. The error i get is when I try to add the second Node to the PQ. Anyone got an idea of how to fix this? I'm expecting that the Node with the smallest f ost is returned to me at the remove operation. This is the second Node I add to the queue, because its manhatten-score is 0, while the firsts Node's board has a manhatten-score of 0.
The Failure trace I get is:
java.lang.ClassCastException: gna.UnitTests$Node cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(Unknown Source)
at java.util.PriorityQueue.siftUp(Unknown Source)
at java.util.PriorityQueue.offer(Unknown Source)
at java.util.PriorityQueue.add(Unknown Source)
at gna.UnitTests.pqTest(UnitTests.java:100)

Array index out of bounds java heap [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I know this is an amaetuer error, i understand what it means but i dont understand why i cant fix it. Ive been trying everything. Im trying to take an array of type T and switch its values around so it correctly corresponds to the rules of a heap, where the parent is always greater than the 2 children. The error is in my while loop
please dont be harsh if its something easily fixable. ive been struggling heavily and cant seem to find an answer.
public class myheap<T extends Comparable<T>> extends heap<T>
{
// constructors of the subclass should be written this way:
public myheap(int max) { super(max); }
public myheap(T[] A) {super(A);}
public void buildheap(T[] Arr){
int size = Arr.length;
int startsize = (size-1)/2;
for(int i=startsize;i>0;i--){
int l = left(i);
int r = right(i);
T temp = null;
while((Arr[r]!=null) && Arr[i].compareTo(Arr[r])<0){
if (Arr[l].compareTo(Arr[r])>0){
temp = Arr[l];
Arr[l] = Arr[i];
Arr[i] = temp;
}//if left is greater than right
else //then right must be greater than parent
temp = Arr[r];
Arr[r] = Arr[i];
Arr[i] = temp;
}//whileloop
if((Arr[r]==null) && Arr[i].compareTo(Arr[l])<0)
temp = Arr[l];
Arr[l] = Arr[i];
Arr[i] = temp;
}//for
}//buildheap
public static void main(String[] args){
String[] array = {"SH","AH","AB","YA","AY","AA","AB","LM","LL","LO"};
myheap<String> New = new myheap<String>(array.length);
for(int i=0;i<array.length;i++){
New.insert(array[i]);
}//insert
New.buildheap(array);
New.drawheap();
for(int i=0;i<array.length;i++){
System.out.println(New.deletemax() + " ");
}//for
System.out.println();
} //main
}
Heap superclass that myheap is extending
/*
Polymorphic priority heaps, largest value on top.
Heap axiom. The value at every node cannot be smaller than the values
at each of its children nodes.
Use internal array to implement heap "tree", with index 0 representing
the root. Given node index i, left(i)= 2*i+1 and right(i)=2*i+2, while
parent(i) = (i-1)/2.
*/
class heap<T extends Comparable<T>>
{
protected T[] H; // internal array representing heap.
protected int size; // size of current heap, not same as H.length!
public int size() { return size; } // size is read-only externally.
public int maxsize() { return H.length; }
public heap(T[] A) { H = A; size=0; } // preferred constructor
public heap(int m) // will cause compiler warning (ok to ignore)
{
H = (T[]) new Comparable[m]; // downcast from Object is OK.
size = 0;
}
protected int left(int i) { return 2*i+1; }
protected int right(int i) { return 2*i+2; }
protected int parent(int i) { return (i-1)/2; }
// protected is important!
// lookup heap, without delete
public T getmax()
{
if (size<1) return null;
return H[0];
}
// insert x into heap: place at end, then propagate upwards
// returns false on failure.
public boolean insert(T x)
{
if (size > H.length-1) return false;
H[size++] = x; // place at end, inc size
// propagate upwards
int cur = size-1; // current position
int p = parent(cur);
while (cur>0 && H[cur].compareTo(H[p])>0)
{ // propagate upwards
T temp = H[cur];
H[cur] = H[p]; H[p] = temp;
cur = p; // switch current to parent
p = parent(cur); // recalc parent
}//while
return true;
}//insert
// deletetop: take last element, move to top, propagate downwards:
public T deletemax()
{
if (size<0) return null;
T answer = H[0];
H[0] = H[--size]; // place at top:
// now propagate downwards.
boolean done = false;
int i = 0; // current position
int c = 0; // swap candidate
while (c != -1)
{
int l = left(i);
int r = right(i);
c = -1; // swap candidate
if (l<size && H[l].compareTo(H[i])>0) c = l; // set candidate to left
if (r<size && H[r].compareTo(H[i])>0 && H[r].compareTo(H[l])>0) c=r;
if (c!= -1)
{
T temp = H[i]; H[i] = H[c]; H[c] = temp;
i = c;
}
}//while
return answer;
}//deletemax
// but search is not log(n). Why?
public boolean search(T x)
{
for(int i=0;i<size;i++) {if (x.compareTo(H[i])==0) return true;}
return false;
}
public void drawheap() // use only with heapdisplay.java program
{
heapdisplay W = new heapdisplay(1024,768);
W.drawtree(H,size);
}
}//heap
public class heaps14
{
/**public static void main(String[] args){
heap<Integer> HI = new heap<Integer>(200);
for(int i=0;i<100;i++) HI.insert((int)(Math.random()*1000));
HI.drawheap();
for(int i=0;i<100;i++) System.out.print(HI.deletemax() + " ");
System.out.println();
}//main**/
}
You may check for null in your while loop, (Arr[r]!=null) but the problem is that you can't even get a value from the array to determine if it's null or not. You should check the index is within the range before trying to access the value from the array, using r < Arr.length or similar.
(If null) isnt the problem, arrayIndexOutofBounds means you are geting a value of an array that isnt there
Eg. Array.length =5; and you search Array[6]; - out of bounds....
The problem i think is your method right(i);
which is. i*2+2 and the array
So change the for loop to this
for(int i=startsize-2;i>0;i--)
comment if this helps.

How come my stack is getting overwritten after a for loop execution?

I am doing an algorithm for a hill climbing search, and for some reason, the stack that I'm supposed to have at the end of the loop seems to be overwritten with the last iteration of the state that the loop generated.
Basically, here is a rundown of what this algorithm is doing:
This algorithm is being used to solve the N queens problem. All of the underlying code with the state class works perfectly fine. With this algorithm, it iterates through all possible successor states of the current state. It stores the next successor state within the neighborState variable (as seen in the code below). If a state cost is less than the current cost, it will add the neighborState with that new low cost into a neighborNode and store that into a stack. Any new min values that get detected will wipe the stack and insert the new lowest minimum nodes.
I've done a few tests within the loop to see what the outputs look like from what is being inserted into the stack. All of them seem to be correctly outputting. However, when I am outside the loop and check the stack, all the nodes in the stack have their states replaced to the last generated successor state from the loop. It seems that in every node that has the neighborState stored, each time the neighborState updates, it changes all the node neighborState values as well. I just can't seem to find a way to fix this though.
Some advice as to how I can fix this would be greatly appreciated!
*Note: Disregard the code after the for loop starting at the if statement, as it is still incomplete.
Here is the code:
import java.util.Random;
import java.util.Stack;
public class HillClimber {
private LocalSearchNode _current;
private int _shoulderSearchStepsAllowed;
// may need more instance variables
public HillClimber(LocalSearchNode initial, int searchShoulder) {
_current = initial;
_shoulderSearchStepsAllowed = searchShoulder;
}
public LocalSearchNode findSolution() {
LocalSearchNode neighborNode = null;
//Stack <LocalSearchNode> nodeStack;
State currentState = null;
//State neighborState = null;
Double val = 0.0;
boolean start = true;
while (true) {
currentState = _current.getState();
Stack<LocalSearchNode> nodeStack = new Stack<LocalSearchNode>();
// finds the highest valued successor of current
for (String s : currentState.actions()) {
State neighborState = currentState.successor(s);
Double cost = neighborState.estimatedDistance(neighborState);
// execute this for the first successor found
if (start) {
val = cost;
System.out.println("Started with " + val);
neighborNode = new LocalSearchNode(neighborState,
s, val, 0);
nodeStack.push(neighborNode);
start = false;
((QState) nodeStack.peek().getState()).test();
System.out.println(nodeStack.size());
}
// resets node array if new min found and adds it to the array
else if (cost < val) {
System.out.println("Reset " + val + " with " + cost);
val = cost;
nodeStack = new Stack<LocalSearchNode>();
neighborNode= new LocalSearchNode(neighborState,
s, val, 0);
nodeStack.push(neighborNode);
((QState) nodeStack.peek().getState()).test();
System.out.println(nodeStack.size());
}
// if cost is the same as current min val, add it to the array
else if (cost.equals(val)) {
val = cost;
System.out.println("Added " + val);
neighborNode = new LocalSearchNode(neighborState,
s, val, 0);
nodeStack.push(neighborNode);
((QState) nodeStack.peek().getState()).test();
System.out.println(nodeStack.size());
}
}
System.out.println("Final min " + val);
System.out.println(nodeStack.size());
((QState) nodeStack.elementAt(0).getState()).test();
((QState) nodeStack.elementAt(1).getState()).test();
// returns current state if no better state found
if (_current.getValue() < val) {
// System.out.println(val);
// ((QState) _current.getState()).test();
return _current;
} else {
if (nodeStack.size() > 1) {
Random generator = new Random();
int i = generator.nextInt(nodeStack.size());
_current = nodeStack.elementAt(i);
} else {
_current = nodeStack.firstElement();
}
start = true;
}
}
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class QState implements State {
private List<String> _list;
private int[][] _state;
private int[] _qlist;
/**
* Constructor takes in the board and row index value corresponding to the
* queens at their respective column index
*
* #param state
* #param queens
*/
public QState(int[][] state, int[] queens) {
_state = state;
_qlist = queens;
_list = new ArrayList<String>();
// generates a list of all possible actions for this state
for (int i = 0; i < _qlist.length; i++) {
for (int j = 0; j < _qlist.length; j++) {
if (_state[i][j] != -1) {
_list.add("Move queen " + j + " to row " + i);
}
}
}
}
/**
* Returns a list of N * (N - 1) actions
*/
public List<String> actions() {
return _list;
}
/**
* Returns the matrix board configuration of this state
*
* #return
*/
public int[][] getMatrix() {
return _state;
}
/**
* Returns the array of queens row index for the board configuration
*
* #return
*/
public int[] getQList() {
return _qlist;
}
/**
* Parses the action and moves the queen to the new board location
*/
public State successor(String action) {
State temp = null;
int[][] newState = _state;
int[] newQList = _qlist;
String[] vals = action.split("\\s");
int i = Integer.parseInt(vals[5]); // parses the row index
int j = Integer.parseInt(vals[2]); // parses the column index
newState[_qlist[j]][j] = 0; // clears the old queen
newState[i][j] = -1; // sets the new queen
newQList[j] = i; // adds the new queen to the list
temp = new QState(newState, newQList);
return temp;
};
/**
* Returns the default step cost of 1.0
*/
public Double stepCost(String action) {
return 1.0;
}
// overrides the built-in Java equals method
#Override
public boolean equals(Object s) {
if (s == null) {
return false;
}
if (this.getClass() != s.getClass()) {
return false;
}
if (!Arrays.equals(this.getMatrix(), ((QState) s).getMatrix())) {
return false;
}
return true;
}
/**
* Returns the queen conflicts for the particular board
*/
public Double estimatedDistance(State s) {
double conflicts = 0.0;
int col = 0;
int row = 0;
for (int j = 0; j < _qlist.length; j++) {
row = _qlist[j] - 1;
col = j + 1;
// checks the upper right diagonal for queen conflicts
while (row >= 0 && col < _qlist.length) {
if (_state[row][col] == -1) {
conflicts++;
}
row--;
col++;
}
row = _qlist[j] + 1;
col = j + 1;
// checks the lower right diagonal for queen conflicts
while (row < _qlist.length && col < _qlist.length) {
if (_state[row][col] == -1) {
conflicts++;
}
row++;
col++;
}
row = _qlist[j];
col = j + 1;
// checks the sideways right for queen conflicts
while (col < _qlist.length) {
if (_state[row][col] == -1) {
conflicts++;
}
col++;
}
}
// test();
return conflicts;
}
public void test() {
for (int i = 0; i < _qlist.length; i++) {
for (int j = 0; j < _qlist.length; j++) {
if (_state[i][j] == -1) {
System.out.print("Q");
} else {
System.out.print("-");
}
}
System.out.println("");
}
System.out.println("\n");
}
}
If you look at successor, this looks suspicious to me:
int[][] newState = _state;
int[] newQList = _qlist;
Here, it looks like you're sharing these arrays between objects. Without knowing much about what the program is doing, this kind of thing is typically the cause of the "shared update" behavior you've observed.
So updating the array from the returned successor will also change the state of the object that returned it (and so on).
There are a couple of easy ways to copy an array, namely System#arraycopy, Arrays#copyOf and clone. (All arrays are cloneable.) For the 2D array you might want to make a helper method since you'd probably need to make a deep copy. Something like:
static int[][] copyState(int[][] toCopy) {
int[][] copy = new int[toCopy.length][];
for(int i = 0; i < copy.length; i++) {
// or = Arrays.copyOf(toCopy[i], toCopy[i].length);
copy[i] = toCopy[i].clone();
}
return copy;
}
I didn't spend a whole lot of time really parsing the code--there's a lot to go through, sorry--but I don't see you making a copies anywhere, just mutating them, so I'd put my bet on this.

Two point crossover in Java

I have implemented a one point crossover as follows;
public void onePointCrossover(Individual indi) {
if (SGA.rand.nextDouble() < pc) {
int xoverpoint = SGA.rand.nextInt(length);
int tmp;
for (int i=xoverpoint; i<length; i++){
tmp = chromosome[i];
chromosome[i] = indi.chromosome[i];
indi.chromosome[i] = tmp;
}
}
}
One point crossover - crossover point is selected, binary string from beginning of chromosome to the crossover point is copied from one parent, the rest is copied from the second parent.
Parent 1 = chromosome and Parent 2 = indi.
I am turning the parents into children inplace.
I now need to also do a two point crossover but having some trouble, this is what I have so far but I believe the bottom half of the code is doing the same thing as a one point crossover rather than swapping the middle sections.
public void twoPointCrossover(Individual indi) {
if (SGA.rand.nextDouble() < pc) {
int xoverpoint = SGA.rand.nextInt(length);
int xoverpoint2 = SGA.rand.nextInt(length);
int tmp;
if (xoverpoint > xoverpoint2){
tmp = xoverpoint;
xoverpoint = xoverpoint2;
xoverpoint2 = tmp;
}
for (int i=xoverpoint; i<xoverpoint2; i++){
tmp = chromosome[i];
chromosome[i] = indi.chromosome[i];
indi.chromosome[i] = tmp;
}
}
}
}
This does not seem right and any help will be appreciated so much! Thanks!
You should check for i < (or <=) xoverpoint2 rather than i<length in the loop.
I'm working on the same problem now. Here is my solution:
// Two-Point Crossover function
public Genome twoPtCrossover(Genome partner) {
Genome child = new Genome(partner.genome.length);
int crosspoint1 = xd.nextInt(genome.length);
int crosspoint2 = xd.nextInt(genome.length);
// Ensure crosspoints are different...
if (crosspoint1 == crosspoint2){
if(crosspoint1 == 0){
crosspoint2++;
} else {
crosspoint1--;
}
}
// .. and crosspoint1 is lower than crosspoint2
if (crosspoint2 < crosspoint1) {
int temp = crosspoint1;
crosspoint1 = crosspoint2;
crosspoint2 = temp;
}
for (int i = 0; i < genome.length; i++) {
if (i < crosspoint1 || i > crosspoint2)
child.genome[i] = genome[i];
else
child.genome[i] = partner.genome[i];
}
return child;
}

Categories

Resources