Finding Shortest Path of Graph and print Routing Table - java

This is for a data structures class in java, and I need to create a graph that reads text input, converts this information into a graph, and from there print the adjacency list and print a max spanning tree, which I have done. However, the final aspect is to
The full routing table that your program must produce will have for every pair [i,j] (i != j) of computers in the network, the first computer on an optimum route from i to j. If i and j have a direct connection, then j will be the result (table entry) for that route (pair [i,j]). If the optimum route from i to j is i -> a -> b -> j, then a will be the result (table entry) for that route. One could then construct the route by looking at the value from [i,j] (=a), then [a,j] (=b), then [b,j] (=j).
So basically Dijksta's algorithm. However, I cannot use any Java APIs that deal with graphs (all others are allowed). So far I have
import java.util.ArrayList;
//import java.util.Stack;
public class Graph2 {
ArrayList<Vertex> vert = new ArrayList<Vertex>();
private static int counter = 0;
private int edges;
private Edge[] allEdges = new Edge[50];
private class Vertex{
String ip;
private int id;
ArrayList<Edge> nb = new ArrayList<Edge>();
/**
* Constructor for Vertex
* #param String of IP
*/
public Vertex(String s){
ip = s;
id = counter;
counter++;
}
/**
* Gets the ID of a vertex
* #return unique ID
*/
public int getId(){
return id;
}
/*
public boolean isSame(Vertex v){
if(this.ip.equals(v.getIp()))
return true;
else
return false;
}
*/
/**
* Gets the IP of a vertex
* #return the IP of the vertex
*/
public String getIp(){
return this.ip;
}
/**
* Adds an edge to nb
* #param edge to be added
*/
public void addList(Edge e){
nb.add(e);
}
/**
* Determines if an edge exists
* #param edge to be checked
* #return true if exists, false if not
*/
public boolean exists(Edge e){
if(nb.indexOf(e) != -1){
return true;
}
else
return false;
}
/**
* Gets the size of an edge
* #return size of edge
*/
public int edgeSize(){
return nb.size();
}
/**
* Gets the edges
* #return String of edges
*/
public String getEdges(){
String all = "";
Edge e;
for(int i = 0; i < nb.size(); i++){
e = nb.get(i);
int ti = this.getId();
int fin = e.getFinish().getId();
if(ti == fin)
all += e.getStart().getId() + " ";
else
all += e.getFinish().getId() + " ";
}
return all;
}
/**
* Overrides toString method
* #return ID and IP of vertex
*/
public String toString(){
return id + " " + " " + ip;
}
}
private class Edge{
int weight;
Vertex finish;
Vertex start;
/**
* Constructor of Edge
* #param vertex 1, start vertex
* #param vertex 2, endpoint vertex
* #param weight of edge
*/
public Edge(Vertex v, Vertex v2, int w){
start = v;
finish = v2;
weight = w;
}
/**
* Gets the start of an edge
* #return edge start
*/
public Vertex getStart(){
return start;
}
/**
* Gets the endpoint of an edge
* #return endpoint of edge
*/
public Vertex getFinish(){
return finish;
}
/**
* Gets the weight of an edge
* #return weight of edge
*/
public int getWeight(){
return weight;
}
/**
* Overrides toString
* #return start of edge and endpoint of edge
*/
public String toString(){
return start + " " + finish;
}
}
/**
* Adds an edge to 2 verticies
* #param s, starting vertex IP
* #param t, enpoint vertex IP
* #param w, weight of edge
*/
public void add(String s, String t, int w){
Vertex v3, v4;
v3 = exists(new Vertex(s));
v4 = exists(new Vertex(t));
Edge e;
if(v3 == null && v4 == null){
v3 = new Vertex(s);
v4 = new Vertex(t);
vert.add(v3);
vert.add(v4);
e = new Edge(v3, v4, w);
v3.addList(e);
v4.addList(e);
}
else if(v3 != null && v4 == null){
counter--;
v4 = new Vertex(t);
vert.add(v4);
e = new Edge(v3, v4, w);
v3.addList(e);
v4.addList(e);
}
else if(v3 == null && v4 !=null){
counter--;
v3 = new Vertex(s);
vert.add(v3);
e = new Edge(v3, v4, w);
v3.addList(e);
v4.addList(e);
}
else{
counter -= 2;
e = new Edge(v3, v4, w);
if(!v3.exists(e)){
v3.addList(e);
v4.addList(e);
}
}
allEdges[edges] = e;
edges++;
}
/**
* Determines if an edge already exists
* #param vertex to be checked
* #return vertex if exists, null if not
*/
public Vertex exists(Vertex v){
for(int i = 0; i < vert.size(); i++){
if(v.getIp().equals(vert.get(i).getIp()))
return vert.get(i);
}
counter--;
return null;
}
/**
* Puts vert ArrayList into an array
* #return String array of vert
*/
public String[] toArray(){
String[] all = new String[vert.size()];
for(int i = 0; i < vert.size(); i++){
all[i] = vert.get(i).toString();
}
return all;
}
/**
* Determines if a vertex is adjacent to another vertex
* #return String array of adjacent verticies
*/
public String[] adjaceny(){
String[] all = new String[vert.size()];
Vertex v1;
for(int i = 0; i < vert.size(); i++){
v1 = vert.get(i);
all[i] = v1.getEdges();
}
return all;
}
/**
* Determines which vertex is in which cluster
* #return String array of clusters
*/
/*
public String[] cluster(){
Vertex[] temp = (Vertex[]) vert.toArray();
Sorter sort = new Sorter();
sort.heapsort(temp);
String[] cluster = new String[vert.size()];
int[] verts = new int[vert.size()];
for(int i = 0; i < vert.size();i++)
verts[i] = i;
return null;
}
*/
/**
* Gets the max spanning tree of the graph
* #return spanning tree of graph
*/
public String[] maxTree(){
sortEdges();
String[] max = new String[vert.size() -1];
Edge e;
for(int i = 0; i < vert.size()-1; i++){
e = allEdges[i];
max[i] = e.getStart().getId() + ", " + e.getFinish().getId() + ", " + e.getWeight();
}
return max;
}
/**
* Sorts edges by max weight
*/
private void sortEdges(){
Sorter sort = new Sorter();
sort.heapsort(allEdges);
}
public class Sorter{
/**
* Heapsorts the Object array
* #param Object array to be sorted
*/
public void heapsort(Object[] a)
{
for(int i = edges / 2; i >= 0; i-- ) /* buildHeap */
percDown(a, i, edges);
for( int i = edges - 1; i > 0; i-- )
{
swapReferences( a, 0, i ); /* deleteMax */
percDown( a, 0, i );
}
}
/**
* Performs swapping of elements
* #param Object array
* #param index1
* #param index2
*/
public void swapReferences(Object[] a, int index1, int index2 )
{
if(a[0] instanceof Edge){
Edge tmp = (Edge)a[index1];
a[index1] = a[index2];
a[index2] = tmp;
}
else if(a[0] instanceof Vertex){
Vertex temp = (Vertex)a[index1];
a[index1] = a[index2];
a[index2] = temp;
}
}
/**
* Internal method for heapsort.
* #param i the index of an item in the heap.
* #return the index of the left child.
*/
private int leftChild(int i)
{
return 2 * i + 1;
}
/**
* Internal method for heapsort that is used in
* deleteMax and buildHeap.
* #param a an array of Comparable items.
* #int i the position from which to percolate down.
* #int n the logical size of the binary heap.
*/
private void percDown(Object[] a, int i, int n)
{
int child;
if(a[0] instanceof Edge){
Edge tmp;
for( tmp = (Edge) a[i]; leftChild(i) < n; i = child )
{
child = leftChild(i);
if( child != n - 1 && ((Edge)a[child]).getWeight() - ((Edge)(a[child + 1])).getWeight() > 0 )
child++;
if(tmp.getWeight() - ((Edge)a[child]).getWeight() > 0 )
a[i] = a[child];
else
break;
}
a[i] = tmp;
}
else if(a[0] instanceof Vertex){
Vertex temp;
for(temp = (Vertex) a[i]; leftChild(i) < n; i = child){
child = leftChild(i);
if(child != n-1 && ((Vertex)a[child]).edgeSize() - ((Vertex)a[child+1]).edgeSize() > 0)
child++;
if(temp.edgeSize() - ((Vertex)a[child]).edgeSize() > 0)
a[i] = a[child];
else
break;
}
a[i] = temp;
}
}
}
}
}
With a main consisting of:
import java.util.*;
import java.io.*;
public class pg6main {
public static void main(String[] args) throws IOException{
String filename;
String first, second;
int weight;
Graph2 graph = new Graph2();
Scanner kb = new Scanner(System.in);
boolean go = false;
Scanner infile = null;
PrintWriter outfile = new PrintWriter(new FileWriter("results.txt"));
do{
try{
System.out.print("Enter a file to read from: ");
filename = kb.nextLine();
infile = new Scanner(new FileReader(filename));
}catch(Exception e){
go = true;
System.out.println("file doesn't exist");
}
}while(go);
while(infile.hasNext()){
first = infile.next().trim();
second = infile.next().trim();
weight = Integer.parseInt(infile.nextLine().trim());
graph.add(first, second, weight);
}
outfile.println("IP and their unique IDs: ");
String[] a = graph.toArray();
for(int i = 0; i < a.length; i++)
outfile.println(a[i]);
outfile.println("Adjaceny List: ");
String[] adj = graph.adjaceny();
for(int j = 0; j < adj.length; j++)
outfile.println(j + ": " + adj[j]);
outfile.println("Max spanning tree: ");
String[] max = graph.maxTree();
for(int k = 0; k < max.length; k++)
outfile.println("(" + max[k] + ") ");
/*
//Attempting to do clusters based on length of string of neighbors, does not work
for(int x = 0; x < adj.length; x++){
if(adj[x].length() > adj[x+1].length()){
outfile.println("WHAT I DID: " + adj[x]);
}
else if(adj[x].length() == adj[x+1].length()){
adj[x] = adj[x+1];
outfile.println("WHAT I DID: " + adj[x]);
}
else if(adj[x].length() < adj[x+1].length()){
adj[x] = adj[x+1];
outfile.println("WHAT I DID: " + adj[x]);
}
*/
/*//Attempted to do neighbors slighly different way
String[] cluster = graph.cluster();
for(int x = 0; x < cluster.length; x++){
if(cluster[x] != null)
outfile.println(cluster[x]);
*/
outfile.close();
}//end main
}//end pg6main
I was wondering if anyone could help, I've never worked with graphs until today. So far, I believe my code works as intended, but there could potentially be some errors with my logic. Basically my issue is most of the implementations of Dijkstra's have parameters as a graph, and I am unsure if this is actually how I should be doing this. Thanks for any help.

You should use the Floyd algorithm instead, it gives you a full table of shortest routes, exactly as you described in the requirements.
As you can see from the pseudocode, it's really simple and all you need is to create a two-dimensional array and initialise it with the edges. (So basically it's your weighted adjacency table.)

Related

How to compute distance to all other vertices in Graph using BFS?

How do I compute the distance from a start vertex to all other vertices using BFS search?
If there is no path to a vertex then the distance should be reported as -1.
I have a class that generates a Graph and a method distance(int start) that I have implemented BFS search on, but I do not not how to compute the distances and return it in a suitable data-structure.
Ecpected output:
graph.distance(0);
>>> Distance from vertex 0 to 1 is 1
>>> Distance from vertex 0 to 2 is 1
>>> Distance from vertex 0 to 3 is 2
>>> Distance from vertex 0 to 4 is 2
>>> Distance from vertex 0 to 5 is 3
import java.util.*;
import static java.lang.System.out;
import java.util.concurrent.ThreadLocalRandom;
public class Graph {
int _vertices;
ArrayList<ArrayList<Integer>> adj_list;
private void addEdge(int u, int v) {
adj_list.get(u).add(v);
adj_list.get(v).add(u);
//out.println(adj_list);
}
/*
* loop through all pairs of vertices u, v and decide,
* randomly with probability p, whether the edge (u, v)
* is in the graph.
*/
Graph(int vertices, double prob){
_vertices = vertices;
adj_list = new ArrayList<ArrayList<Integer>>(vertices);
for (int u = 0; u < vertices; u++) {
//System.out.println(i);
adj_list.add(new ArrayList<Integer>());
}
for (int v = 0; v < vertices; v++) {
for(int u = 0; u < vertices; u++) {
double random = ThreadLocalRandom.current().nextDouble(0, 1);
if (random > prob) {
//System.out.println(checkElem(adj_list, v));
if (checkElem(adj_list, v, u) == false && u != v){
addEdge(v, u);
}
}
}
}
}
public void printGraph() {
for (int i = 0; i < adj_list.size(); i++) {
System.out.println("\nAdjacency list of vertex " + i);
for (int j = 0; j < adj_list.get(i).size(); j++) {
System.out.print(" -> "+adj_list.get(i).get(j));
}
System.out.println();
}
}
/*
* #param vert: A vertex in the graph
*/
public void printVertex(int vert) {
System.out.print(" -> "+adj_list.get(vert));
}
/*
* #param arr: list of list that represents graph
* #param vertex: a vertex in the graph
* #param node: node to be checked in vertex
*/
private boolean checkElem(ArrayList<ArrayList<Integer>> arr, int vertex, int node) {
ArrayList<Integer> temp = arr.get(vertex);
if(temp.contains(node)){
return true;
} else {
return false;
}
}
/*
* #param start: A vertex to start the search from in the graph
*/
public void distance(int start) {
boolean visited[] = new boolean[_vertices];
ArrayList<Integer> queue = new ArrayList<Integer>();
visited[start] = true;
queue.add(start);
while (queue.size() != 0) {
//out.println(queue);
// Dequeue a vertex from queue and print it
start = queue.remove(0);
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it
// visited and enqueue it
ArrayList<Integer> temp = adj_list.get(start);
Iterator<Integer> i = temp.listIterator();
//out.println("Vertex: " + start +" Dist: " + edgeDist);
while (i.hasNext()) {
out.println(start);
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(5, 0.5);
graph.distance(0);
}
}
Calculating the distance from the source to all adjacency
Update your code to use isEmpty() because it's constant time and don't use size()==0
, Use Queue to add adjacency vertex
public int distance(int vertex) {
boolean visited[] = new boolean[_vertices];
Queue<Integer> queue = new ArrayDeque<>();
visited[vertex] = true;
queue.add(vertex);
int distance = 0;
while (!queue.isEmpty()) {
int v = queue.poll();
List<Integer> adj = adj_list.get(v);
distance++;
for (Integer w : adj) {
if (!visited[w]) {
System.out.println("Distance from vertex: " + vertex + " to: " + w +" is " + distance);
visited[w] = true;
queue.add(w);
}
}
}
return distance == 0 ? -1 : distance;
}

Sorting array into three different ArrayLinearLists

You can find ArrayLinearLists from here in EPROGS Trying to sort a datas from .txt file into three different ArrayLinearLists. But the problem is about their capacity. Whenever the .add function is called the capacity is doubled.
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String line;
int indexOfCode = 0;
int indexOfName = 1;
int indexOfCredit = 2;
int count = 0;
ArrayLinearList codeR = new ArrayLinearList();
ArrayLinearList nameR = new ArrayLinearList();
ArrayLinearList creditR = new ArrayLinearList();
try (BufferedReader br = new BufferedReader(new FileReader("Subjects.txt"))) {
while ((line = br.readLine()) != null) {
String values[] = line.split("/");
codeR.add(0, values[indexOfCode]);
nameR.add(0, values[indexOfName]);
creditR.add(0, values[indexOfCredit]);
}
System.out.println(codeR);
System.out.println(nameR);
System.out.println(creditR);
}
}
}
Here is the ArrayLinearList codes
protected Object[] element; // array of elements
protected static int size; // number of elements in array
protected static ArrayLinearList theObject;
// constructors
/**
* create a list with initial capacity initialCapacity
*
* #throws IllegalArgumentException
* when initialCapacity < 1
*/
public ArrayLinearList(int initialCapacity) {
if (initialCapacity < 1)
throw new IllegalArgumentException("initialCapacity must be >= 1");
// size has the default initial value of 0
element = new Object[initialCapacity];
}
/** create a list with initial capacity 10 */
public ArrayLinearList() {// use default capacity of 10
this(10);
}
// methods
/** #return true iff list is empty */
public boolean isEmpty() {
return size == 0;
}
/** #return current number of elements in list */
public int size() {
return size;
}
/**
* #throws IndexOutOfBoundsException
* when index is not between 0 and size - 1
*/
void checkIndex(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("index = " + index + " size = " + size);
}
/**
* #return element with specified index
* #throws IndexOutOfBoundsException
* when index is not between 0 and size - 1
*/
public Object get(int index) {
checkIndex(index);
return element[index];
}
/**
* #return index of first occurrence of theElement, return -1 if theElement
* not in list
*/
public int indexOf(Object theElement) {
// search element[] for theElement
for (int i = 0; i < size; i++)
if (element[i].equals(theElement))
return i;
// theElement not found
return -1;
}
/**
* Remove the element with specified index. All elements with higher index
* have their index reduced by 1.
*
* #throws IndexOutOfBoundsException
* when index is not between 0 and size - 1
* #return removed element
*/
public Object remove(int index) {
checkIndex(index);
// valid index, shift elements with higher index
Object removedElement = element[index];
for (int i = index + 1; i < size; i++)
element[i - 1] = element[i];
element[--size] = null; // enable garbage collection
return removedElement;
}
/**
* Insert an element with specified index. All elements with equal or higher
* index have their index increased by 1.
*
* #throws IndexOutOfBoundsException
* when index is not between 0 and size
*/
public void add(int index, Object theElement) {
if (index < 0 || index > size)
// invalid list position
throw new IndexOutOfBoundsException("index = " + index + " size = " + size);
// valid index, make sure we have space
if (size == element.length)
// no space, double capacity
element = ChangeArrayLength.changeLength1D(element,2* size);
// shift elements right one position
for (int i = size - 1; i >= index; i--)
element[i + 1] = element[i];
element[index] = theElement;
size++;
}
/** convert to a string */
public String toString() {
StringBuffer s = new StringBuffer("[");
// put elements into the buffer
for (int i = 0; i < size; i++)
if (element[i] == null)
s.append("null, ");
else
s.append(element[i].toString() + ", ");
if (size > 0)
s.delete(s.length() - 2, s.length()); // remove last ", "
s.append("]");
// create equivalent String
return new String(s);
}
/** create and return an iterator */
public Iterator iterator() {
return new ArrayLinearListIterator((MyArrayList) this);
}
/** test program */
public static void main(String[] args) {
// test default constructor
LinearList x = new ArrayLinearList();
// test size
System.out.println("Initial size is " + x.size());
// test isEmpty
if (x.isEmpty())
System.out.println("The list is empty");
else
System.out.println("The list is not empty");
// test put
x.add(0, new Integer(2));
x.add(1, new Integer(6));
x.add(0, new Integer(1));
x.add(2, new Integer(4));
System.out.println("List size is " + x.size());
// test toString
System.out.println("The list is " + x);
// test indexOf
int index = x.indexOf(new Integer(4));
if (index < 0)
System.out.println("4 not found");
else
System.out.println("The index of 4 is " + index);
index = x.indexOf(new Integer(3));
if (index < 0)
System.out.println("3 not found");
else
System.out.println("The index of 3 is " + index);
// test get
System.out.println("Element at 0 is " + x.get(0));
System.out.println("Element at 3 is " + x.get(3));
// test remove
System.out.println(x.remove(1) + " removed");
System.out.println("The list is " + x);
System.out.println(x.remove(2) + " removed");
System.out.println("The list is " + x);
if (x.isEmpty())
System.out.println("The list is empty");
else
System.out.println("The list is not empty");
System.out.println("List size is " + x.size());
}
}
And thanks in advance ,great senior developers :D
For a developer using ArrayLinearList this means giving a larger initial capacity, to prevent too many increases.
Using an estimate:
Path path = Paths.get("Subjects.txt");
int initialCapacity = (int)(Files.size(path) / 3);
For a developer implementing ArrayLinearList heshe could pick a larger default initial capacity, or something like increasing the array size by 1000 + array.length/4, to not waiste as much space, and initially have not so many repeated increases.

get combinations of sets created after combinations in java

I've come to a dead end and need your help!!
I've managed to get combinations of a list of numbers(Double) that give a specific sum.I also have a hashtable which values are the numbers of the previous list and keys are some Strings eg. numbers(Double)[2.45,2.65,4.67,5.25,2.45,2.65....] and table[(E-40=2.45),(E-45=2.45),(E-56=2.65),(E-34=2.65),(E-24=4.67),(E-14=5.25)....].So after the numbers combinations for a specific sum I get: For sum: 5.10 ---> 2.45 - 2.65 which corresponds to (E-40,E-45) - (E-56,E-34).I would like to get now the combinations of these sets.
eg
[(E-40)-(E-56)],[(E-40)-(E-34)],
[(E-45)-(E-56)],[(E-45)-(E-34)]
And here is my code:`
public class TestTheCombinations {
public static void main(String[] args) {
ArrayList<Double> numbers = new ArrayList<>(Arrays.asList(2.45,2.45,2.65,2.65,4.67,5.25));
LinkedHashSet<Double> targets = new LinkedHashSet<Double>() {{
add(5.10);
}};
for (Double target: targets) {
Combinations combinations = new Combinations(numbers, target, false);
combinations.calculateCombinations();
for (String solution: combinations.getCombinations()) {
System.out.println(solution);
}
}
}
public static class Combinations {
private boolean allowRepetitions;
private int[] repetitions;
private ArrayList<Double> numbers;
private Hashtable<String,Double> table;
private Double target;
private Double sum;
private boolean hasNext;
private Set<String> combinations;
/**
* Constructor.
*
* #param numbers Numbers that can be used to calculate the sum.
* #param target Target value for sum.
*/
public Combinations(ArrayList<Double> numbers, Double target) {
this(numbers, target, true);
}
/**
* Constructor.
*
* #param numbers Numbers that can be used to calculate the sum.
* #param target Target value for sum.
*/
public Combinations(ArrayList<Double> numbers, Double target, boolean allowRepetitions) {
this.allowRepetitions = allowRepetitions;
if (this.allowRepetitions) {
Set<Double> numbersSet = new HashSet<>(numbers);
this.numbers = new ArrayList<>(numbersSet);
} else {
this.numbers = numbers;
}
this.numbers.removeAll(Arrays.asList(0));
Collections.sort(this.numbers);
this.target = target;
this.repetitions = new int[this.numbers.size()];
this.combinations = new LinkedHashSet<>();
this.sum = 0.0;
if (this.repetitions.length > 0)
this.hasNext = true;
else
this.hasNext = false;
}
/**
* Calculate and return the sum of the current combination.
*
* #return The sum.
*/
private Double calculateSum() {
this.sum = 0.0;
for (int i = 0; i < repetitions.length; ++i) {
this.sum += repetitions[i] * numbers.get(i);
}
return this.sum;
}
/**
* Redistribute picks when only one of each number is allowed in the sum.
*/
private void redistribute() {
for (int i = 1; i < this.repetitions.length; ++i) {
if (this.repetitions[i - 1] > 1) {
this.repetitions[i - 1] = 0;
this.repetitions[i] += 1;
}
}
if (this.repetitions[this.repetitions.length - 1] > 1)
this.repetitions[this.repetitions.length - 1] = 0;
}
/**
* Get the sum of the next combination. When 0 is returned, there's no other combinations to check.
*
* #return The sum.
*/
private Double next() {
if (this.hasNext && this.repetitions.length > 0) {
this.repetitions[0] += 1;
if (!this.allowRepetitions)
this.redistribute();
this.calculateSum();
for (int i = 0; i < this.repetitions.length && this.sum != 0; ++i) {
if (this.sum > this.target) {
this.repetitions[i] = 0;
if (i + 1 < this.repetitions.length) {
this.repetitions[i + 1] += 1;
if (!this.allowRepetitions)
this.redistribute();
}
this.calculateSum();
}
}
if (this.sum.compareTo(0.0) == 0.0)
this.hasNext = false;
}
return this.sum;
}
/**
* Calculate all combinations whose sum equals target.
*/
public void calculateCombinations() {
while (this.hasNext) {
if (this.next().compareTo(target) == 0)
this.combinations.add(this.toString());
}
}
/**
* Return all combinations whose sum equals target.
*
* #return Combinations as a set of strings.
*/
public Set<String> getCombinations() {
return this.combinations;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public String toString() {
Hashtable<String,Double> table = new Hashtable<String,Double>();
table.put("E-40",2.45);
table.put("E-45",2.45);
table.put("E-56",2.65);
table.put("E-34",2.65);
table.put("E-24",4.67);
table.put("E-14",5.25);
StringBuilder stringBuilder = new StringBuilder("For SUM " + sum + ": "+"\n");
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < repetitions.length; ++i) {
for (int j = 0; j < repetitions[i]; ++j) {
Set keys = new HashSet();
Double value = numbers.get(i);
for(Map.Entry entry: table.entrySet()){
if(value.equals(entry.getValue())){
keys.add(entry.getKey());
}
}
stringBuilder.append(numbers.get(i)+ " Corresponds WorkCode "+ keys+"\n");
}
}
return stringBuilder.toString() ;
}
}
}
`
Thanks for any help!!!

Eight Queens Algorithm for Different Starting Points

I am trying to find a solution to the Eight Queens problem regardless of the starting point. Below is my Solver class, however it doesn't work for some reason when I place the queen in a row other than the first one.
import java.util.*;
public class Queens {
private static int x;
private static int y;
private static ArrayList<Integer> rows = new ArrayList<Integer>();
public Queens(int index, int row, int pos) {
for (int i = 0; i<index; i++)
rows.add(i);
rows.remove(row);
x = pos;
y = row;
}
public static boolean solve(int row, int[][] board, int N, int pos) {
board[y][x] = 1;
System.out.println("row: " + row);
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 8; j++) {
if(board[i][j]==1) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
}
System.out.println();
if(row>=N-1) return true;
for(int position = pos; position < N; position++) {
if(isValid(board, rows.get(row), position, N)) {
board[rows.get(row)][position] = 1;
if(!solve(row+1, board, N, 0)) {
board[rows.get(row)][position] = 0;
} else
return true;
}
}
return false;
}
public static boolean isValid(int[][] board, int y, int x, int N) {
int i, j;
for(i = 0; i < y; i++)
if(board[i][x]==1)
return false;
i = y - 1;
j = x - 1;
while((i>=0)&&(j>=0))
if(board[i--][j--]==1) return false;
i = y - 1;
j = x + 1;
while((i>=0)&&(j<N))
if(board[i--][j++]==1) return false;
return true;
}
}
For example, when I place the initial queen on board[2][2], this is the solution I get:
Q * * * * * * *
* * Q * * * * *
* * Q * * * * *
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
* * * * * * Q *
What is wrong with the code? Why does it disregard the initial piece? Thanks in advance.
What are the bounds for the for loop in isValid? Do they prevent you from placing a queen into a column where there's another queen below?
A similar question applies also to the while loops -- can they detect that there's a queen on the diagonal but below the one you're placing now?

Neural Network bad convergeance

I read a lot about NN last two weeks, I think i saw pretty much every "XOR" approach tutorials on net. But, i wasn't able to make work my own one. I started by a simple "OR" neuron approach. Giving good results. I think my problem is in backpropagation implementation. I did an object approach, so here are the main lines.
Three classes :
Neuron
public class Neuron {
/*
* Attributes
*/
double[] inputs;
double[] weights;
double output;
double error;
double delta;
double deltaWeight;
/*
* Constructors
*/
public Neuron(int nInputs)
{
inputs = new double[nInputs + 1];
inputs[inputs.length - 1] = 1; // bias
weights = new double[nInputs + 1];
}
/*
* Methods
*/
/**
* Reset all weights of the neuron to random values between -1 and 1
*/
public void reset()
{
Random random = new Random();
for (int i = 0; i < weights.length; i++)
weights[i] = (random.nextDouble() * ((0.5d - (-0.5d))) + (-0.5d));
}
/**
* Compute output for given inputs
* #param inputs
*/
public void computeOutput(double inputs[])
{
setInputs(inputs);
output = Sigmoid.activation(getDotProduct());
}
/**
* Compute error for given ideal
* #param ideal
*/
public void computeError(double ideal)
{
error = ideal - output;
delta = error;
}
/**
* Compute error for hidden neurons
*/
public void computeError(FeedForwardLayer previousLayer, int position)
{
double sum = 0;
for (int i = 0; i < previousLayer.neurons.length; i++)
sum += (previousLayer.neurons[i].delta * previousLayer.neurons[i].weights[position]);
delta = Sigmoid.derivative(getDotProduct()) * sum;
error = delta;
}
/**
* Adjust every weight of the neuron
*/
public void adjustWeights(double lambda, double momentum)
{
for (int i = 0; i < weights.length; i++)
{
double lastDeltaWeight = deltaWeight;
deltaWeight = lambda * (delta * inputs[i]) + momentum * lastDeltaWeight;
weights[i] += deltaWeight;
}
}
#Override
public String toString()
{
String str = "";
for (int i = 0; i < weights.length; i++)
str = str.concat(String.format("IN|W --> %.6f | %.6f \n", (float) inputs[i], (float) weights[i]));
str = str.concat("Output = " + output + "\n");
str = str.concat("Error = " + error + "\n");
return str;
}
/*
* Getters & Setters
*/
/**
* #return weights * inputs + bias
*/
public double getDotProduct()
{
double sum = 0;
for (int i = 0; i < inputs.length; i++)
sum += (weights[i] * inputs[i]);
return sum;
}
/**
* Set inputs (keep bias input)
* #param inputs
*/
public void setInputs(double[] inputs)
{
for (int i = 0; i < inputs.length; i++)
this.inputs[i] = inputs[i];
}
/**
* Set every weight to a single value
* #param weight
*/
public void setWeights(double weight)
{
for (int i = 0; i < weights.length; i++)
this.weights[i] = weight;
}
}
FeedForwardLayer (which contain neurons)
public class FeedForwardLayer {
/*
* Attributes
*/
Neuron[] neurons;
LayerTypes type;
/*
* Constructors
*/
/**
* First layer constructor
* #param nNeurons
*/
public FeedForwardLayer(int nInputs, int nNeurons, LayerTypes type)
{
neurons = new Neuron[nNeurons];
for (int i = 0; i < neurons.length; i++)
neurons[i] = new Neuron(nInputs);
this.type = type;
}
/*
* Methods
*/
/**
* Reset all weights of the layer's neurons to random values between -1 and 1
*/
public void reset()
{
for (Neuron neuron : neurons)
neuron.reset();
}
/**
* Compute output, if layer isn't input one, you can pass null into parameter
* #param inputs
*/
public void computeOutputs(double[] inputs)
{
for (int i = 0; i < neurons.length; i++)
neurons[i].computeOutput(inputs);
}
/**
* Compute error, if layer is output one
* #param ideals
*/
public void computeErrors(double[] ideals)
{
for (int i = 0; i < neurons.length; i++)
neurons[i].computeError(ideals[i]);
}
/**
* Compute error, if layer isn't output one
* #param layer n+1
*/
public void computeErrors(FeedForwardLayer next)
{
for (int i = 0; i < neurons.length; i++)
neurons[i].computeError(next, i);
}
/**
* Adjust weights for every neurons
*/
public void adjustWeights(double lambda, double momentum)
{
for (Neuron neuron : neurons)
neuron.adjustWeights(lambda, momentum);
}
#Override
public String toString()
{
String str = "";
for (int i = 0; i < neurons.length; i++)
str = str.concat("Neuron " + i + "\n" + neurons[i]);
return str;
}
/*
* Getters - Setters
*/
/**
* #return true if layer is input, false otherwise
*/
public boolean isInput()
{
if (type == LayerTypes.INPUT)
return true;
return false;
}
/**
* #return true if layer is input, false otherwise
*/
public boolean isOutput()
{
if (type == LayerTypes.OUTPUT)
return true;
return false;
}
/**
* #return an array of layer's outputs
*/
public double[] getOutputs()
{
double[] outputs = new double[neurons.length];
for (int i = 0; i < neurons.length; i++)
outputs[i] = neurons[i].output;
return outputs;
}
/**
* #return array of layer's errors
*/
public double[] getErrors()
{
double[] errors = new double[neurons.length];
for (int i = 0; i < neurons.length; i++)
errors[i] = neurons[i].error;
return errors;
}
/**
* Set all the weights of the layer to given weight
* #param weight
*/
public void setWeights(double weight)
{
for (int i = 0; i < neurons.length; i++)
neurons[i].setWeights(weight);
}
}
FeedForwardNetwork (which contain FeedForwardLayers)
public class FeedForwardNetwork {
static final double lambda = 0.1;
static final double momentum = 0;
/*
* Attributes
*/
private ArrayList<FeedForwardLayer> layers;
/*
* Constructors
*/
public FeedForwardNetwork()
{
layers = new ArrayList<FeedForwardLayer>();
}
/*
* Methods
*/
/**
* Init all the weights to random values
*/
public void reset()
{
for (int i = 0; i < layers.size(); i++)
layers.get(i).reset();;
}
/**
* Compute output for all the neurons of all the layers for given inputs
* #param inputs
*/
public void feedForward(double[] inputs)
{
//System.err.println("FeedForwardNetwork.feedForward(" + inputs[0] + ", " + inputs[1] +")");
for (int i = 0; i < layers.size(); i++)
{
//System.err.println("\n*** COMPUTING OUTPUT FOR LAYER " + i + "***\n");
if (layers.get(i).isInput())
layers.get(i).computeOutputs(inputs);
else
layers.get(i).computeOutputs(layers.get(i - 1).getOutputs());
}
}
/**
* Compute errors for all the neurons of all the layers starting by output layer
* #param ideals
*/
public void feedBackward(double[] ideals)
{
//System.err.println("FeedForwardNetwork.feedBackward(" + ideals[0] + ")");
// For each layers starting by output one
for (int i = layers.size() - 1; i > 0; i--)
{
//System.err.println("*** COMPUTING ERROR FOR LAYER " + i + "***");
if (layers.get(i).isOutput())
layers.get(i).computeErrors(ideals);
else
layers.get(i).computeErrors(layers.get(i + 1));
}
}
/**
* Adjust weights of every layer
*/
public void adjustWeights()
{
for (FeedForwardLayer feedForwardLayer : layers)
feedForwardLayer.adjustWeights(lambda, momentum);
}
/**
* Train the nn with given inputs and outputs
* #param inputs
* #param outputs
*/
public void train(double[] inputs, double... outputs)
{
feedForward(inputs);
feedBackward(outputs);
adjustWeights();
}
/**
* Add a layer to the network
* #param layer
*/
public void addLayer(FeedForwardLayer layer)
{
layers.add(layer);
}
#Override
public String toString()
{
String str = "";
for (int i = 0; i < layers.size(); i++)
str = str.concat("Layer " + LayerTypes.values()[i] + "\n" + layers.get(i));
str = str.concat("\n");
str = str.concat("OUTPUT = " + getOutputs()[0] + "\n");
str = str.concat("ERROR = " + getError(false) + "\n");
return str;
}
/*
* Getters & Setters
*/
public FeedForwardLayer getInputLayer()
{
return layers.get(0);
}
public FeedForwardLayer getOutputLayer()
{
return layers.get(layers.size() - 1);
}
public FeedForwardLayer getLayer(int index)
{
return layers.get(index);
}
public double getError(boolean abs)
{
if (abs)
return Math.abs(getOutputLayer().neurons[0].error);
return getOutputLayer().neurons[0].error;
}
public double[] getOutputs()
{
return getOutputLayer().getOutputs();
}
}
So i train the network by giving it epoch of the xor table
XOR table
X | Y | S
0 0 0
0 1 1
0 1 1
0 0 0
The network will output after thousands epoch approximately 0.5...
Interesting fact is, if i replace the training set by a AND table, a OR table or an NAND table, the nn will output the number of 1 in the S column of the training set.. (it will output 0.25 for AND and NAND table and 0.75 for OR table)
I just want to know if my implementation is good enough to make it work, ty !
So, after some research, i realized that my implementation was good, except that I didn't understand how the input layer works. That was it, the input layer works like In = Out

Categories