Implementing Breadth First Search

Dec 13, 2014

I have always wanted to program A*, Breath First Search and Depth First Search ever since I took AI. I will only post BFS at the moment but it is only searching the row.

Java Code:

//Breath First Search. The first node passed to it is the start button
void bfs(Mybuttons button){
Queue<Mybuttons> q = new LinkedList<Mybuttons>();
q.add(button);
button.setIcon(button.setButtonToBlueWhileSearched());
button.model.visted=true;

[Code] ....

Output:

Java Code: In while loop
In get Child Node
In get Child Node
In get Child Node
In get Child Node
In while loop
In get Child Node
In get Child Node
In get Child Node
In while loop
In get Child Node
In get Child Node
In while loop
In get Child Node mh_sh_highlight_all('java');

View Replies


ADVERTISEMENT

Breadth First Search Traversal

Dec 5, 2014

This method uses BFS traversal on a vertex and displays the values. I have worked this out on paper and 2 out of 3 the results from my code match my work on paper. I believe the error is that it prints out 3's adjacent child before 3 itself. I have attached the results I did by hand. Here's the graph and results from my code:

0 1 2 3 4 5
------------
0| 0 1 1 0 0 0
1| 0 0 0 0 0 0
2| 0 0 0 1 0 0
3| 1 0 0 0 0 0
4| 0 0 1 0 0 1
5| 0 1 0 1 0 0

BFS:
5 1 3 0 2
4 2 5 0 3 1 //i think this is wrong. shouldnt it be 4 2 5 3 1 0?
0 1 2 3

Here is my code:

public void bfsTraversal(int vertex){
Queue<Integer> q = new LinkedList<Integer>();
visited[vertex] = 1;//mark vertex as visited
q.add(vertex);
System.out.print(vertex + " ");

[Code] .....

Attached image(s)

View Replies View Related

Breadth First Search - How To Iterate Through ArrayList

Aug 18, 2014

I have done this before in C++ but now I want to do it in Java. I am not sure how to iterate through a ArrayList, I have look several places because lets be honest the first stop is normally google. I tried the examples but with no luck.
 
for(auto it= foo.begin(); it!= foo.end(); foo++) {
*it //do something.
}

Here is the program:
 
package org.search.BFS;
import java.util.Queue;
public class BFS extends Graph {
private Queue<Integer> q;
BFS(int s) {
//mark all the vertices as not visited.

Also the below is giving me a Type safety: The expression of type ArrayList[] needs unchecked conversation to conform to ArrayList<Integer>[]

adj = new ArrayList[V];

What does this mean?

View Replies View Related

Implementing Search Algorithm To Solve 8 Puzzle

Oct 4, 2014

I have been working on a program that takes in a 2d array (there is a method to convert to 1d as necessary) and uses it as an 8 puzzle, which the program then solves (if it is solvable) using the A* Search algorithm, outputting each solution move. It needs error checkers/traps/exception handlers, and be able to create an 8 puzzle from user input, create an 8 puzzle from file input, and create an 8 puzzle from file input and then output to another file the solution move sequence. I have gotten nearly everything done except for implement the algorithm itself and the methods for handling input from files or output to files (the input/output file methods are a minor problem that I can probably solve fairly easily, I just want to be able to test the a* with the puzzle created from user input first.

I have taken several cracks at it, but I am not really good with Java in this type of situation and this is hurting me a lot. I have put in a method to determine if a puzzle is solvable, but the A* algorithm still eludes me. I understand the concept of the algorithm, you have a heuristic function, a cost function (each move equals 1 in this case), and you add the two together to get f(n), choosing the move that will get you the closest to your goal (best first search basically). here is what I have so far that works:

import java.io.File;
import java.io.IOException;
import java.util.Queue;
import java.util.Scanner;
public class Puzzle {
public static void main(String[] args) throws IOException {

[Code] ....

I have it outputting things to make sure all that works already, I have all the error handlers, but I think that before I can even implement the A*search algorithm, there may be something else I need. Conceptually, I understand I need Nodes, States and Stacks, and Queues (I think, I am not sure about this), but with the way my code has been made so far, I am not sure how to implement those and then implement them with the A* algorithm. What I should do next? I have looked at the code of other uses of A* algorithm(that is how I found out I might need Java data structures like queue and stack and list), but I am not sure exactly where to go to from where I am.

View Replies View Related

Ability To Search A Binary Search Tree And Return The Number Of Probes

Sep 1, 2014

I'm trying to build a method that can search a binary search tree for a specific target and then return the number of probes it took to get there. It seems to me that the best way to do this would be a recursive search method and a counter that tracks the number of calls. But I'm struggling with how to implement this. Here's the code I have so far. what works/doesn't work with the method.

// Method to search the tree for a specific name and
// return the number of probes
public T search(BTNode<T> btNode) {

[Code]....

View Replies View Related

Creating Search Method For Binary Search Tree

Apr 22, 2014

I want to create a search method that returns the frequency of a word in the search method.

public class IndexTree {
private class TreeNode {
TreeNode left;
String word;
int frequency;
TreeNode right;

[Code] .....

View Replies View Related

Implementing A FPS Counter

Jan 17, 2014

Ok, so I'm making a game with a space ship that flies around the universe and discovering new planets. It works fine so far, but I'm looking to make it perform better and be better compatible with lesser-processors.So, I'm trying to put in an FPS counter and an entirely new game loop so that my game can decide for me what FPS I should use.

I have two classes. Heres the big, main one: [Java] package cyentw.game.src; import java.awt.Color; import java.awt.Font; impor - Pastebin.com *I want to change the loop and put an FPS counter in around line 456, you can scroll past the rest if you'd like*And heres the init frame one, in case you'd like to see it for some reason.

Java Code:

package cyentw.game.src;
import javax.swing.JFrame;
public class Start extends JFrame{
public static JFrame frame;
public static int WIDTH = 500;
public static int HEIGHT = 500;
public Start() {

[code]....

how to make my game loop as quickly (or a bit slower) as it can, and my FPS is static.

View Replies View Related

Swing/AWT/SWT :: Implementing JTabbedPane GUI?

Aug 21, 2014

I have been trying to learn how to use the TabbedPane GUI. I can get the tabs to show up, but the buttons I have placed in each tab do not show up. Why this is not working. I assume that, for some reason, the buttons are not linking with their respective panels, or the panels are not linking to the respective tabs.

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

[Code] ....

View Replies View Related

Implementing Comparator Interface?

Mar 7, 2014

overriding of the compare method.

Here's an example I found:

public class Someone {
String name;
int age;
ArrayList <Someone> listarr = new ArrayList <Someone>();
public Someone(String name1, int age1) {
name = name1;
age = age1;

[code]...

1. In the compare method, what happens when it returns one of the 0, -1, or 1? How does returning such values contribute to the sorting process? How does it take in information (like I know it does through the parameters, but how exactly)?

2. Why do we use the class name for the generics?

View Replies View Related

Implementing Two Stack In One Array?

Jan 5, 2015

is this program correct? for Implementing two Stack in one array. how can i solve it ?

public class Stackation11 {
int max = 10;
int [] array = new int[max];
int top;
int top1;
Stackation11(){

[code]....

View Replies View Related

Implementing Custom Map Interface

Nov 5, 2014

I am supposed to implement a custom Map interface and I'm having some trouble with this method:

// 1. From the interface
/**
* Gives an iterator iterating over the key set from the smallest key that is not less than the key provided.
* @param key the key
* @return the iterator
* @throws NullPointerException if key == null
*/

public Iterator<Key> tailIterator(Key key);

[Code] .....

My implementation is wrong according to a JUnit test. Also, to get a full score this method should have a worst case running time of O(log N), which obviously isn't the case now. (My Map implementation is currently based on binary search in an ordered array, keeping a prallel array for the values).

View Replies View Related

Implementing Deserialization Of Objects?

Jul 16, 2014

Say you have a bunch of animals, `Rat` `Cat` `Dog` and `Fish`, and you want to serialize/deserialize these animals. Each has its own `serialize()` method. That all works fine and good, if you want to save your Cat to a file, you call `Cat.serialize()` and then you write it to a file.

But what about deserializing? Sure, you could save an extra bit of data that states the type of animal, then use reflection to get a static method (say, `deserialize(String serialized)`) and then invoke it. But that's not safe. What if someone creates a new animal 'Rabbit' and doesn't include a `deserialize(String serialized)` method? Sure, you could then just catch the error and ignore the issue, but that seems unclean and bad practice.

You could also create an enum. Each item in the enum must have a `deserialize(String serialized)` method, and the aforementioned piece of data that states the type references the name of its enum item. Problem is, not very adaptable. Enums don't allow for other animals to be added at runtime.

The way I have been solving this issue is mapping the name of the objects against a deserializer object. Basically each animal would have to 'register' itself by entering it's name and deserializer (implements `Deserializer` interface) object into a HashMap. The deserializer object can then be retrieved via the name of the animal at a later time.

My question is, what is the best method to go about implementing deserialization? Also, is the method I have been using good/bad practice?

Finally, if you are wondering why animals would be added at runtime, the reason is because animals might be added by other non accessible parts of the program, or by things such as plugins.

Example of the method I have been using is below.

Animal Interface

Java Code:

public class Animal{
public String serialize();
} mh_sh_highlight_all('java'); Deserializer Interface

[code]....

And when you needed to deserialize:

Java Code:

Deserializer d=AnimalSpecies.getSpeciesDeserializer(serialized.split(AnimalSpecies.DELIMITER)[0]);
if (d!=null){
d.deserialize(serialized);
} mh_sh_highlight_all('java');

What I mean by this is that any serialized Animal must have a way of identifying which animal it is so that it's deserializer can be accessed. This can be worked around by implementing a wrapper that adds this information directly before it is written to a file, and removes it directly before deserialization.

Why not use built in serialization/deserialization? I would like the serialized data to be readable and easily editable.

View Replies View Related

Implementing Heap From ArrayList

Nov 25, 2014

in my class is implement a heap and use some of the methods we were provided. The methods I was provided to code and use are "siftDown", "isEmpty" and "heapify". I'm pretty sure the code I have written for "heapify" and "isEmpty" is correct, where I think I am finding fault is the code for my "siftDown". Would you mind taking a look at my code and see why when adding integers to the heap object that I have created in the main code, that they are not being output correctly?

public class Tester {
public static void main(String[] args) {
Heap myHeap = new Heap();
myHeap.insert(9);
myHeap.insert(15);
myHeap.insert(6);
myHeap.insert(4);
myHeap.insert(10);
myHeap.insert(9);
myHeap.insert(3);

[code]....

View Replies View Related

Implementing Collisions In Frogger

Oct 5, 2014

I am building a frogger game and am having some trouble implementing collisions. I've been going off of various different tutorials and it seems like my frogCollisions function should work based off them, but no matter where I place it collisions aren't registering. Here is the frogCollisions function I am trying to use. I don't think it is very efficient to be checking all of the items in my manager class every loop, but can't think of another way to do this with manager classes. You can see my full code on my github if you would like to see the whole project. It's at: URL....

public void frogCollisions() {
for(int i = 0; i < carManager.smSize(); i++) {
if(f.intersects(carManager.smCars.get(i).getRect())){
player.decreaseLives();
System.out.println(player.getLives());
checkGameOver(); // NEED TO IMPLEMENT STILL

[code]....

View Replies View Related

Program For Implementing A Stack

Jan 3, 2015

I tried to write a program to implement a stack but it has a bug I am unable to solve.The bug is that whenever I choose an operation to perform, eg push, After performing the operation, the loop is executed once again and Invalid choice message appears, i.e. the default case. And then the loop again executes to choose further option. Here is my code

class Stack {
private char[] stck;
private int len;
private int top;

[code]....

View Replies View Related

Implementing Inheritance In Java

Apr 25, 2014

i was leaning inheritance and tried to implement it in Java.This is my base class vehicl.java

public class vehicle{
private int topSpeed;
private int cubicCap;
private String modelName;
private boolean hasAlloy;

[code]...

I also have a derived class called car.java.What i wanted to do in the derived class was that i wanted to override the constructor as well as the getInfo() method from the base class.I wanted to add an additional attribute to the car "numberSeats" and display tat too when the object to car class calls the getInfo() method .It showed an error "identifier required" when i tried to compile car.java program.

import java.util.Scanner;
public class car extends vehicle{
//int numberSeats;
//System.out.println("Enter the number of Seats");
Scanner numberSeats=new Scanner(System.in);
numberSeats=numberSeats.nextInt();
//System.out.println(numberSeats.nextInt());

[code]....

explain the errors that i get when i tried to compile car.java without using super keyword or without defining the constructor from the Car class ?

View Replies View Related

Swing/AWT/SWT :: Implementing Listener Of GUI In A Different Class?

Jun 26, 2014

I have two different classes called Login (in the package View) and RegButtonListener (in the package Controller). I want to use the MVC pattern.

Login creates a GUI for login. I used NetBeans GUI Builder to create it.

In the class RegButtonListener there is the code for the click of the buttons, then various listeners of the GUI.

Now I want to close the login frame at the click of a button so I want to use the dispose() method.

If I had all the code (GUI code and code of the listener) in the same file, close the frame would be easy enough to do because this.dispose(). But in my case I have two different classes.

I also have a second problem.

In Login class (in the packege View) I have included the line :

regButton.addActionListener(Controller.RegButtonListener).

However, Netbeans tells me an error "package regButton does not exist. <identifier> expected". Why does he consider regButton a package? How can I fix these two problems?

How do I do then?
 
Below is the code of the two classes.

Login class.
public class Login extends javax.swing.JFrame {
/** Creates new form Login */
public Login() {
initComponents();

[code]....

View Replies View Related

Implementing A Thread-safe Queue

Jul 10, 2014

I have situation where a user can request java server to send a value to an embedded device, and if the device is asleep, that value needs to be stored in a queue until the device wakes up and sends a position to java server, at which point the server checks if there is a value in the queue and if there is, it then sends that value to the device. The maximum size of the queue is 1 for now. And if the user makes continuous requests to java server, the old value is removed and the new value is added.

Initially I was looking into BlockingQueue, but the problem with that is, well, it blocks. queue.put(value) will block if queue is full, and queue.take() will block if queue is empty. I can't have something that blocks. When the device responds to server, server checks if value is in queue, if it is not then the server carries on the rest of its responsibility. Thus, I then entertained ConcurrentLinkedQueue. While queue.offer(value) and queue.poll(); allow you to add and remove values respectively from the queue without blocking, it does not allow you to set a maximum size limit of the queue. My queue must have a maximum size limit and it has to always be the newest value the user submits to the queue (where old values are removed).So this is what I came up with:

Java Code: class Unit {
private List<Integer> cmdQueue;

public Unit(){
cmdQueue = Collections.synchronizedList(new LinkedList<Integer>());

[code]....

I use Collections.synchronizedList, as I do here, do I still need to use synchronize as I did above?

View Replies View Related

Implementing A Java Class Library?

Apr 18, 2014

i have been given a homework assignment where I have to get rid of a stack object I wrote for a program and replace it with the Stack<E> library java offers ie:

public class Stack<E> extends Vector<E> {
public Stack(); // constructor
public Boolean empty();
public E peek();
public E pop();
public E push(E item);
}

my question is do i have to actually write all these methods? Or can i just construct a stack and use the methods?

View Replies View Related

Implementing Try / Catch With BinaryToDecimal Program

Apr 27, 2014

I've been assigned to write a program that will convert binary to decimal that uses the try/catch block. In the program that I have written, I was wondering if it is possible to write an addition catch statement that will present an error if any number other than a 0 or 1 is entered by the user. I have already done this in the binaryToDecimal method, but I am just messing around to see if it is, in fact, possible.

Java Code:

import java.io.IOException;
import java.util.Scanner;
public class BinaryToDecimal {
public static void main(String[] args){
Scanner input = new Scanner(System.in);

[Code] .....

View Replies View Related

Implementing Classes Instead Of Extending To Get Methods?

Sep 20, 2014

Basically I want to make a class called library, but I don't want to make an interface because I actually want to define the methods. I think I can only use abstract classes but not really sure how to use those. But I still have a problem, I want to create a Map that classes implementing Library class have to have in their code, and the Map will be a HashMap with <String, ParentClassHere>, so basically let's say I make a class called Car, implemeing Library to the Car class would create a Map library = new HashMap<String, Car>. Can I do something like this? And also include methods to get values and set values to the library Map?

View Replies View Related

Implementing Singly Linked List

Apr 17, 2015

I am trying to implement a singly linked list. My singly linked list, where I implemented a class named linkedlist, that I defined (this implementation of linkedlist is not the java class linkedlist, it is my own version of linkedlist):

Java Code:

public class SinglyLinkedList<E> implements LinkedList<E> {
public class Node<E> {
public Node<E> next;
public E element;
public Node(E element) {

this.element = element;
}

public Node (E element, Node<E> next) {

[code]...

But when I go to my main method to add into my SinglyLinkedList, it doesn't add anything.

View Replies View Related

Implementing ActionListener On Image Button

Nov 28, 2014

Is there something special about this? I would think not, however all of the buttons in my application work except those with images.Here's an example of one:

Java Code: // Class #1
// All components defined as private initially, used in initComponents() later to build GUI
private JButton btnRock = new JButton();
/** Create the frame. **/
public GameView() {
initComponents(); // Initialize components
} // End of GameView Method
public void initComponents() {
// ROCK BUTTON
btnRock = (JButton) mainController.createIcon("rock");
btnRock.setForeground(new Color(0, 0, 0));
btnRock.setBounds(12, 34, 97, 67);

[code]....

View Replies View Related

Implementing Merge Sort On Given Array

Jun 15, 2014

Merge sort implementation on the given array i listed in the code below. I know Arrays.sort() or Collections.sort() could do the trick but i want to achieve it through merge sort.

import java.util.*;
public class Merge{
public static void main(String[] args){
String[] myStringArray=new String[]{"z","a","z","b","c","e","z","f"
,"g","a","w","d","m" ,"x","a","R"
,"q","r","y","w","j","a","v","z","b"};
}
}

View Replies View Related

Implementing Java Project With Android

Nov 19, 2014

I have a gameengine stil partially in the works for pc made in java, I am attempting a port over to java but certain classes and other fuctions are not available for android that there is in java. this means that my render engine, gameengine and a couple of other clases therefore don't work.

My question is, is there anyway of using the gameengine classes that work into the project so that all i have to do is declare within the engine what i want to export for wheather this is android or java. or importing packages from the game engine project and directly linking with the ability of re-writing the odd few classes that do not work.

View Replies View Related

Implementing A Card Game In JAVA

Apr 19, 2015

I am facing with a JAVA code needed for my assignment.We are implementing a Card Game.. There is a Card Class which i have not included in the code below .We have a Dec class that has various arrays..

privateCard[] masterPack >> Is a master Pack that is initialized once and has all the 52 cards.

private Card[] cards >> Is the array that has the card values from masterPack array.

My problem is :

After I called the Deck object D1, it goes to the Deck COnstrucutor OK.It then populates the values of masterPack as per the allowmasterPack method.Then it stores the values of masterPack into cards array in the init method..I get an exception when line below is executed..

cards[pack * 52 + k]= masterPack[k];

I get a java.lang.NullPointerException error..

public class debug
{
public static void main(String[] args)
{
int pack = 1;
Dec D1;
D1 = new Dec(pack);

[oode]...

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved