Merge sort step by step execution - java

I am trying to execute merge sort step by step handled by an button click event. I am unable to perform this. What i want is when i click on a button called next, it executes a single step and so on.
Core is my main class. which includes all the gui buttons etc.
here is my code.
`
package sorter;
import sorter.Core;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import sorter.Core$step;
import javax.swing.JOptionPane;
// Referenced classes of package sorter:
// Core
public class MergeSort_Step
implements Runnable, ActionListener
{
private static List<Integer> lists;
private int counter =0;
private int length_list;
public static boolean STEP_BY_STEP=false;
Thread sortingThread=null;
public MergeSort_Step()
{
//JOptionPane.showMessageDialog(Core.form, "Changes will apply on next sort");
Core.btnNext.addActionListener(new Core$step(this));
}
private void clickperformed_1(ActionEvent evt) {
STEP_BY_STEP = true;
//sortingThread = new Thread (this);
//sortingThread.resume();
//run();
}
static void access$click(MergeSort_Step x0, ActionEvent x1) {
x0.clickperformed_1(x1);
}
public void run()
{
//*****************list
length_list = Core.length;
lists = new ArrayList<Integer>(length_list);
for (int i = 0; i < length_list; i++) {
lists.add(0);
}
//System.out.println("Results from file in list: " +lists.size());
mergesort_list (0,length_list-1);
JOptionPane.showMessageDialog(null, "Comparisions : "+ counter, "Notification!", 1);
Core.toggleSorting();
}
//***************list
public void mergesort_list(int low, int high)
{
sortingThread = new Thread (this);
if(low < high)
{
int middle = low + (high - low) / 2;
mergesort_list(low, middle);
mergesort_list(middle + 1, high);
if (Core.STEP_BY_STEP == true || STEP_BY_STEP == true)
{
merge_list(low, middle, high);
//sortingThread.
STEP_BY_STEP = false;
Core.STEP_BY_STEP = false;
}
}
}
//***************list
private void merge_list(int low, int middle, int high)
{
int i;
for(i = low; i <= high; i++)
{
lists.set(i, Core.num.get(i)); //= (List<Integer>) Core.num.get(i);
System.out.println("Current Array Status: " +lists.toString());
Core.numStatus[i] = Core.DONE;
}
i = low;
int j = middle + 1;
int k = low;
{
while(i <= middle && j <= high)
{
if( lists.get(i) <= lists.get(j))
{
Core.num.set(k, lists.get(i));
Core.numStatus[i] = Core.DONE;
Core.updateScreen();
i++;
} else
{
Core.num.set(k, lists.get(j));
Core.numStatus[i] = Core.DONE;
Core.updateScreen();
j++;
}
k++;
Core.numStatus[i] = Core.EVENT;
Core.updateScreen();
//Core.STEP_status = false;
counter++;
}
while(i <= middle)
{
Core.num.set(k, lists.get(i));
Core.numStatus[i] = Core.EVENT;
Core.updateScreen();
k++;
i++;
Core.updateScreen();
//Core.STEP_status = false;
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}`
I am very new to event handling and java gui implementation as well. any help will be appreciated.

Related

How can I move this into a other class

I am working on a Four in a row game.
But I have run into a problem with it. I have been able to make the game work. But I would like to know if I can move my public void fillBoard() and public void presentBoard() into another class. This is because I would like to make the code more organised.
package com.company;
public class Main {
public static void main(String[] args)
{
GameMechanics game = new GameMechanics();
game.play();
}
}
package com.company;
import java.util.Scanner;
public class GameMechanics
{
/*
This is my local variables
*/
public Scanner scanner = new Scanner(System.in);
public char token;
public int column;
public int player = 2;
public int turn = 2;
public int count = 0;
public boolean gameRunning = true;
public void play()
{
this.createBoard();
//While gameRunning is true, the methods inside the { } will run, and that's the 4InARow game
while (gameRunning)
{
this.presentBoard();
this.changeTurn();
this.dropToken();
this.gameWon();
}
presentBoard();
}
public void gameWon()
{
this.winConHorizontal();
this.winConVertical();
}
private char[][] board = new char[6][7];
//Creating my board and assign "space" to all the fields in the array.
public void createBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
board[i][j] = ' ';
}
}
}
//Presents the board, it prints the board with |"space"| so it looks more like a gameboard.
public void presentBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (j == 0) {
System.out.print("|");
}
System.out.print(board[i][j] + "|");
}
System.out.println();
}
}
public void changeTurn() {
if (this.turn == this.player) {
this.turn = 1;
this.token = 'X';
} else {
this.turn++;
this.token = 'O';
}
}
public void dropToken() {
System.out.println("player " + turn + ": press 1-7 to drop the token");
column = scanner.nextInt() - 1;
//If pressed any intValue outside the board, it will tell you to try again.
if (column >= 7 || column <= -1)
{
System.out.println("place the token inside the bord");
changeTurn();
} else {
//Drops the token and replace it with playerChar.
for (int i = 5; i > -1; i--) {
if (board[i][column] == ' ')
{
board[i][column] = token;
break;
}
}
}
}
public boolean winConHorizontal() {
while (gameRunning) {
for (int i = 0; 6 > i; i ++) {
for (int j = 0; 7 > j; j ++) {
if (board[i][j] == this.token) {
count ++;
} else {
count = 0;
}
if (count >= 4) {
System.out.println("player " + (turn) + " Wins!!!!");
gameRunning = false;
}
}
}
break;
}
return gameRunning;
}
public boolean winConVertical() {
while (gameRunning) {
for (int i = 0; 7 > i; i ++) {
for (int j = 0; 6 > j; j ++) {
if (board[j][i] == this.token) {
count ++;
} else {
count = 0;
}
if (count >= 4) {
System.out.println("player " + (turn) + " Wins!!!!");
gameRunning = false;
}
}
}
break;
}
return gameRunning;
}
}
An easy way to do this is as follows:
extract your char[][] board into its own class, e.g. Board
Said class could expose the function char getField(int index)
Extract the ,,presenting" part of your code into another class, e.g. BoardPresenter. Said class should have a function presentBoard(Board board) which internally uses getField(int index) of the Board class.
By doing this you abstract away your internal board storage mechanism while also reducing the number of responsibilities the GameMechanics class has (See https://en.wikipedia.org/wiki/Single_responsibility_principle)
yes, you can make another class and extend it with the current class GameMechanics and inside another class you can define the functions.
Note : This is a very simple approachable way.
Otherwise better if you manage your classes and interfaces similar to mvc model, for which you can search youtube for mvc structure java.

Autocomplete byReverseWeightOrder comparator issue

I have been working on this problem for several hours now and I just cannot figure out what I am doing wrong here. Could anyone help point me in the right direction?
I was asked to write an Autocomplete program and I've completed everything except for this one method I cannot get working. Each term has: 1. String query and 2. long weight.
Here is the method:
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() { // LINE CAUSING PROBLEM
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) { // LINE CAUSING PROBLEM
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
My problem is that no matter how I mess with the method I always result in a NullPointerException(). Which, it points to this method (byReverseWeightOrder) as well as these two statements.
Arrays.sort(matches, Term.byReverseWeightOrder());
Term[] results = autocomplete.allMatches(prefix);
Here is the rest of the code if it can be found helpful:
Term
import java.util.Comparator;
public class Term implements Comparable<Term> {
public String query;
public long weight;
public Term(String query, long weight) {
if (query == null) {
throw new java.lang.NullPointerException("Query cannot be null");
}
if (weight < 0) {
throw new java.lang.IllegalArgumentException("Weight cannot be negative");
}
this.query = query;
this.weight = weight;
}
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() {
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) {
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
public static Comparator<Term> byPrefixOrder(int r) {
if (r < 0) {
throw new java.lang.IllegalArgumentException("Cannot order with negative number of characters");
}
final int ref = r;
return
new Comparator<Term>() {
public int compare(Term t1, Term t2) {
String q1 = t1.query;
String q2 = t2.query;
int min;
if (q1.length() < q2.length()) {
min = q1.length();
}
else {
min = q2.length();
}
if (min >= ref) {
return q1.substring(0, ref).compareTo(q2.substring(0, ref));
}
else if (q1.substring(0, min).compareTo(q2.substring(0, min)) == 0) {
if (q1.length() == min) {
return -1;
}
else {
return 1;
}
}
else {
return q1.substring(0, min).compareTo(q2.substring(0, min));
}
}
};
}
public int compareTo(Term that) {
String q1 = this.query;
String q2 = that.query;
return q1.compareTo(q2);
}
public long getWeight() {
return this.weight;
}
public String toString() {
return this.weight + "\t" + this.query;
}
}
BinarySearchDeluxe
import java.lang.*;
import java.util.*;
import java.util.Comparator;
public class BinarySearchDeluxe {
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) <= 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
return -1;
}
public static <Key> int lastIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a == null || a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) < 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
return -1;
}
}
AutoComplete
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
public class Autocomplete {
public Term[] terms;
public Autocomplete(Term[] terms) {
if (terms == null) {
throw new java.lang.NullPointerException();
}
this.terms = terms.clone();
Arrays.sort(this.terms);
}
public Term[] allMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int count = start;
System.out.println("Start: " + start + " End: " + end);
if (start == -1 || end == -1) {
// System.out.println("PREFIX: " + prefix);
throw new java.lang.NullPointerException();
} // Needed?
Term[] matches = new Term[end - start + 1];
//matches = Arrays.copyOfRange(terms, start, end);
for (int i = 0; i < end - start; i++) {
matches[i] = this.terms[count];
count++;
}
Arrays.sort(matches, Term.byReverseWeightOrder());
System.out.println("Finished allmatches");
return matches;
}
public int numberOfMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
System.out.println("Finished numberMatches");
return end - start + 1; // +1 needed?
}
public static void main(String[] args) throws IOException {
// Read the terms from the file
Scanner in = new Scanner(new File("wiktionary.txt"));
int N = in.nextInt(); // Number of terms in file
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.nextLong(); // read the next weight
String query = in.nextLine(); // read the next query
terms[i] = new Term(query.replaceFirst("\t",""), weight); // construct the term
}
Scanner ip = new Scanner(System.in);
// TO DO: Data Validation Here
int k;
do {
System.out.println("Enter how many matching terms do you want to see:");
k = ip.nextInt();
} while (k < 1 || k > N);
Autocomplete autocomplete = new Autocomplete(terms);
// TO DO: Keep asking the user to enter the prefix and show results till user quits
boolean cont = true;
do {
// Read in queries from standard input and print out the top k matching terms
System.out.println("Enter the term you are searching for. Enter * to exit");
String prefix = ip.next();
if (prefix.equals("*")) {
cont = false;
break;
}
Term[] results = autocomplete.allMatches(prefix);
System.out.println(results.length);
for(int i = 0; i < Math.min(k,results.length); i++)
System.out.println(results[i].toString());
} while(cont);
System.out.println("Done!");
}
}
I apologize for the sloppy code, I have been pulling my hair out for awhile now and keep forgetting to clean it up.
Two examples:
Example 1:
int k = 2;
String prefix = "auto";
Enter how many matching terms do you want to see:
2
Enter the term you are searching for. Enter * to exit
auto
619695 automobile
424997 automatic
Example 2:
int k = 5;
String prefix = "the";
Enter how many matching terms do you want to see:
5
Enter the term you are searching for. Enter * to exit
the
5627187200 the
334039800 they
282026500 their
250991700 them
196120000 there

Maze solver cannot find exit

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class Maze
{
private int[][] maze;
private boolean exitFound;
public Maze()
{
exitFound = false;
maze = new int[0][0];
}
public Maze(int size, String line)
{
exitFound=false;
maze = new int[size][size];
int spot=0;
for(int r= 0; r<maze.length; r++)
{
for(int c =0; c<maze[r].length; c++)
{
maze[r][c]=(line.charAt(spot*2)-48);
spot++;
}
}
}
public void checkForExitPath(int r, int c)
{
if (r >= 0 && r <maze.length &&c >= 0 && c < maze[0].length && maze[r][c] == 1)
{
checkForExitPath(r + 1, c);
checkForExitPath(r - 1, c);
checkForExitPath(r, c + 1);
checkForExitPath(r, c - 1);
maze[r][c] = 7;
if (r == maze.length-1 && c == maze[0].length-1){
this.exitFound =true;
}
}
}
public String toString()
{
String hol = "";
for(int i = 0; i<maze.length; i++){
for(int j = 0; j<maze[0].length; j++){
hol += " ";
if(maze[i][j] == 7){
hol += "1";
}
else
{
hol += maze[i][j];
}
}
hol += "\n";
}
if(this.exitFound)
{
hol+= "exit found";
}
else {
hol += "exit not found";
}
return hol;
}
}
That is my maze class the method checkForExitPath is not working or at least I think because everytime I run the maze solver with this runner class
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class MazeRunner
{
public static void main( ) throws IOException
{
Scanner file = new Scanner(new File("maze.dat"));
while(file.hasNext())
{
int size = file.nextInt();
file.nextLine();
Maze test = new Maze(size, file.nextLine());
test.checkForExitPath(0,0);
out.println(test);
}
}
}
The only output I get is that an exit is not found, but I can find an exit.
I am doing this recursively.
Your whole method does not really work recursively. If the upper left corner has a 1 which I interpret from your code as walkable way, it is changed to 7 and your method ends without recursion.
I think the four recursive method calls should be part of the first if block and no else block is necessary.

Java/LWJGL: Code Executing Twice for no Reason

I am developing a game in LWJGL. I have an item pickup code to add an item to the player's inventory, but whenever I call it, it adds the item to the slot (x) and the slot after slot (x). (x meaning any random number) I was hoping I could have some help debugging it.
The class add method is being called in:
package geniushour.gameobject.entity;
import static org.lwjgl.input.Keyboard.KEY_A;
import static org.lwjgl.input.Keyboard.KEY_D;
import static org.lwjgl.input.Keyboard.KEY_P;
import static org.lwjgl.input.Keyboard.KEY_SPACE;
import static org.lwjgl.input.Keyboard.isKeyDown;
import java.util.ArrayList;
import java.util.Random;
import geniushour.engine.Physics;
import geniushour.engine.time.Delay;
import geniushour.engine.time.Time;
import geniushour.game.Game;
import geniushour.game.Util;
import geniushour.game.type.ArmorType;
import geniushour.game.type.ClawType;
import geniushour.game.type.EntityType;
import geniushour.gameobject.GameObject;
import geniushour.gameobject.StatObject;
import geniushour.gameobject.item.Backpack;
import geniushour.gameobject.item.Item;
public class Player extends StatObject {
private Delay delay;
private boolean collide = false;
private int facingDirection = 0;
private int firstFree = 0;
private Random damageRandom;
private final int NORTH = 0;
private final int EAST = 1;
private final int SOUTH = 2;
private final int WEST = 3;
public Player(float x, float y){
super(true,0,6);
init(x,y,ENTITY_SIZE,ENTITY_SIZE,0.25f,1f,.25f,EntityType.PLAYER_ID.getID());
deleteBackpack();
setClaw(ClawType.BASIC);
setArmorType(ArmorType.SKIN);
setStrength(1, claw);
delay = new Delay(500); delay.terminate();
}
public void update(){
ArrayList<GameObject> items = Game.rectCollide(x, y, x+ENTITY_SIZE, y+ENTITY_SIZE);
for(GameObject go : items){
if(go.getType() == EntityType.ITEM_ID.getID()){
go.remove();
inv.add ((Item)go);
}
}
ArrayList<GameObject> wall = Game.rectCollide(x, y, x+ENTITY_SIZE, y+ENTITY_SIZE);
for(GameObject go : wall){
if(go.getType() == EntityType.BLOCK_ID.getID()){
if(Physics.checkCollision(this, go) != null){
collide = true;
}
else if(Physics.checkCollision(this, go) == null){
collide = false;
}
}
if(collide){
if(this.facingDirection == WEST){
move(1,0);
collide = false;
}
else if(this.facingDirection == EAST){
move(-1,0);
collide = false;
}
}
}
if(getCurrentHealth() <= 0){
addHP(-getCurrentHealth());
deleteBackpack(); //TODO: Backpack temp or not?
}
for(int i = 0; i < inv.getLength(); i++){
if(inv.get( i ) instanceof Backpack){
ownBackpack();
inv.remove(i);
inv.setSlots(27);
}
}
}
outputData(true);
}
public void getInput(){
if(!collide){
if(isKeyDown(KEY_A)){
move(-1,0);
}
if(isKeyDown(KEY_D)){
move(1,0);
}
if(isKeyDown(KEY_SPACE) && delay.over()){
attack();
}
if(isKeyDown(KEY_P)){
}
}
}
private void move(int magX, int magY){
if(magX == 1){
facingDirection = EAST;
}
if(magX == -1){
facingDirection = WEST;
}
x += getSpeed(armor) * magX * Time.getDelta();
y += getSpeed(armor) * magY * Time.getDelta();
}
private void attack(){
//Find GameObjects in Attack Range
ArrayList<GameObject> obj = new ArrayList<GameObject>();
switch(facingDirection){
case NORTH: obj = Game.rectCollide(x, y, x + ENTITY_SIZE, y + getCloseAttackRange());
break;
case EAST: obj = Game.rectCollide(x, y, x + getCloseAttackRange(), y + ENTITY_SIZE);
break;
case SOUTH: obj = Game.rectCollide(x, y - getCloseAttackRange() + ENTITY_SIZE, x + ENTITY_SIZE, y);
break;
case WEST: obj = Game.rectCollide(x - getCloseAttackRange() + ENTITY_SIZE, y, x, y + ENTITY_SIZE);
break;
}
//Find which GOs are Enemy Type
ArrayList<Enemy> enemies = new ArrayList<Enemy>();
for(GameObject go : obj){
if(go.getType() == EntityType.ENEMY_ID.getID()){
enemies.add((Enemy)go);
}
}
//Find closest existing enemy
if(enemies.size() > 0){
Enemy target = enemies.get(0);
if(enemies.size() > 1){
for(Enemy e : enemies){
if(Util.dist(x, y, e.getX(), e.getY()) < Util.dist(x, y, target.getX(), target.getY())){
target = e;
}
}
}
damageRandom = new Random();
double e = Math.pow(getStrength(claw), (Math.cbrt(damageRandom.nextInt(15)) + 1)) / (Math.sqrt(getStrength(claw) + 1));
target.damage((int) Math.round(e));
Util.writeLine(" : " + target.getCurrentHealth() + "/" + target.getMaxHP());
if(target.getCurrentHealth() <= 0){
addXP(100);
}
}
delay.start();
}
private void outputData(boolean ask){
if(ask){
for(int i = 0; i < inv.getLength(); i++){
Util.writeLine("Main Inv Slot "+i+": " + inv.get(i));
}
Util.writeLine("");
Util.writeLine("Backpack Owned: " + getBackpack());
Util.writeLine("");
Util.writeLine("Inventory Size: " + inv.getLength());
Util.writeLine("");
Util.writeLine("Health: "+getCurrentHealth());
Util.writeLine("");
Util.writeLine("End of Information Output");
}
}
}
The Class add() is defined in:
package geniushour.game.inventory;
import geniushour.game.Util;
import geniushour.gameobject.item.Item;
public class Inventory {
private Item[] items;
private int firstFree;
public Inventory(int size){
items = new Item[size];
firstFree = 0;
}
public boolean add(Item item){
for(int i = 0; i < items.length; i++){
if(get(i) == null){
firstFree = i;
break;
}
}
Util.writeLine(firstFree);
if(add(item, firstFree)){
firstFree++;
if(firstFree > items.length){
firstFree = items.length;
}
return true;
}
return false;
}
public boolean add(Item item, int index){
if(items[index] == null && index <= items.length){ // != or == ?
items[index] = item;
return true;
}
else{
return false;
}
}
public Item get(int index){
return items[index];
}
public void remove(int index){
items[index] = null;
if(index < firstFree){
firstFree = index;
}
if(firstFree < 0){
firstFree = 0;
}
}
public void remove(Item item){
for(int i = 0; i < items.length; i++){
if(items[i] == item){
remove(i);
return;
}
}
}
public Item[] getItemList(){
return items;
}
public int getLength(){
return items.length;
}
public void setSlots(int amt){
Item[] temp = new Item[items.length];
for(int i = 0; i < items.length; i++){
temp[i] = items[i];
}
items = new Item[amt];
for(int i = 0; i < temp.length; i++){
items[i] = temp[i];
}
temp = new Item[items.length];
}
}

Java Implementation, Priority Queue

I have a hard time to figure out one error after assigning
int evaluationNode = getMinDistances();
settled.add(evaluationNode);
checkNeighbours(evaluationNode);
The error show type mismatch: connot convert from Node to int. I am appreciated if anyone can help me this. Below is a complete code.
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
import java.util.Comparator;
public class DijkstraPriorityQueue
{
private int distances[];
private Set<Integer> settled;
private PriorityQueue<Node> priorityQueue;
private int number_of_nodes;
private int adjacencyMatrix[][];
public DijkstraPriorityQueue(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>();
priorityQueue = new PriorityQueue<Node>(number_of_nodes,new Node());
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{
distances[i] = Integer.MAX_VALUE;
}
priorityQueue.add(new Node(source, 0));
distances[source] = 0;
while (!priorityQueue.isEmpty())
{
evaluationNode = getMinDistances();
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getMinDistances()
{
int node = priorityQueue.remove();
return node;
}
private void checkNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
priorityQueue.add(new Node(destinationNode,distances[destinationNode]));
}
}
}
}
public static void main(String[] args)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Enter the source ");
source = scan.nextInt();
DijkstraPriorityQueue dijkstrasPriorityQueue = new DijkstraPriorityQueue(number_of_vertices);
dijkstrasPriorityQueue.dijkstra_algorithm(adjacency_matrix, source);
System.out.println("The Shorted Path to all nodes are ");
for (int i = 1; i <= dijkstrasPriorityQueue.distances.length - 1; i++)
{
System.out.println(source + " to " + i + " is " + dijkstrasPriorityQueue.distances[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
class Node implements Comparator<Node>
{
public int node;
public int cost;
public Node()
{
}
public Node(int node, int cost)
{
this.node = node;
this.cost = cost;
}
#Override
public int compare(Node node1, Node node2)
{
if (node1.cost < node2.cost)
return -1;
if (node1.cost > node2.cost)
return 1;
return 0;
}
}
In the getMinDistances method you are calling
int node = priorityQueue.remove();
But the priority queue contains Node objects, and not int values.
Maybe you wanted something like
private int getMinDistances()
{
Node node = priorityQueue.remove();
return node.getDistance();
}
but this is something that can not be answered by the debugging cloud (aka stackoverflow).
In order to use the PriorityQueue, you have to implement MinPQ extending the PriorityQueue and you'll also need a Comparator between nodes that returns the Node with a minimum distance in the MinPQ.
Take a look here for more details.

Categories

Resources