I have run into a problem converting pseudocode of Dijkstras algorithm into actual code. I was given and adjacency list such as "Location - adjacent location - distance to location," example for one node: AAA AAC 180 AAD 242 AAH 40.
My task was to read a file organized as adjacency list as described, and compute the shortest path from one node to another.
Here is the Dijkstra pseudocode:
void dijkstra( Vertex s )
{
for each Vertex v
{
v.dist = INFINITY;
v.known = false;
}
s.dist = 0;
while( there is an unknown distance vertex )
{
Vertex v = smallest unknown distance vertex;
v.known = true;
for each Vertex w adjacent to v
if( !w.known )
{
DistType cvw = cost of edge from v to w;
if( v.dist + cvw < w.dist )
{
// Update w
decrease( w.dist to v.dist + cvw );
w.path = v;
}
}
}
}
im having the most trouble with the line "for each Vertex w adjacent to v"
Here is my nonworking code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class Dijkstra {
public static boolean isInteger(String s) {
return isInteger(s, 10);
}
public static boolean isInteger(String s, int radix) {
if (s.isEmpty())
return false;
for (int i = 0; i < s.length(); i++) {
if (i == 0 && s.charAt(i) == '-') {
if (s.length() == 1)
return false;
else
continue;
}
if (Character.digit(s.charAt(i), radix) < 0)
return false;
}
return true;
}
public static void dijkstra(Vertex[] a, Vertex s, int lineCount) {
int i = 0;
while (i < (lineCount)) // each Vertex v
{
a[i].dist = Integer.MAX_VALUE;
a[i].known = false;
i++;
}
s.dist = 0;
int min = Integer.MAX_VALUE; //
while (!(a[0].known == true && a[1].known == true && a[2].known == true && a[3].known == true
&& a[4].known == true && a[5].known == true && a[6].known == true && a[7].known == true
&& a[8].known == true && a[9].known == true && a[10].known == true && a[11].known == true
&& a[12].known == true)) {
System.out.println("here");
for (int b = 0; b < lineCount; b++) {
if (a[b].dist < min && a[b].known == false) {
min = a[b].dist;
}
}
int c = 0;
while (c < lineCount) {
if (a[c].dist == min && a[c].known == false) {
break;
}
c++;
}
System.out.println(min);
a[c].known = true;
int adjSize = a[c].adj.size();
int current = 0;
System.out.println(adjSize);
while (current < adjSize - 1) {
String currentAdjacent = (String) a[c].adj.get(current);
int p = 0;
while (p < lineCount) {
if (a[p].name.equals(currentAdjacent)) {
if (!a[p].known) {
String cvwString = (String) a[c].distance.get(current);
int cvw = Integer.parseInt(cvwString);
System.out.println(" This is cvw" + cvw);
System.out.println("Here2");
if (a[c].dist + cvw < a[p].dist) {
a[p].dist = a[c].dist + cvw;
a[p].path = a[c];
}
}
}
p++;
}
current++;
}
}
}
public static class Vertex {
public List adj; // Adjacency list
public List distance;
public boolean known;
public int dist; // DistType is probably int
public Vertex path;
public String name;
// Other fields and methods as needed
}
public static void printPath(Vertex v) {
if (v.path != null) {
printPath(v.path);
System.out.print(" to ");
}
System.out.print(v);
}
public static void main(String[] args) throws IOException {
int lineCounter = 0;
BufferedReader br = new BufferedReader(new FileReader("airport.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
lineCounter = lineCounter + 1;
}
Vertex[] arr = new Vertex[lineCounter];
for (int i = 0; i < lineCounter; i++) {
arr[i] = new Vertex();
arr[i].adj = new LinkedList<String>();
arr[i].distance = new LinkedList<Integer>();
}
;
//
int arrayCounter = 0;
String everything = sb.toString();
String[] lines = everything.split("\\s*\\r?\\n\\s*");
for (String line1 : lines) {
arr[arrayCounter] = new Vertex();
arr[arrayCounter].adj = new LinkedList<String>();
arr[arrayCounter].distance = new LinkedList<Integer>();
String[] result = line1.split("\\s+");
for (int x = 0; x < result.length; x++) {
if (x == 0) {
arr[arrayCounter].name = result[0];
continue;
} else if (isInteger(result[x])) {
arr[arrayCounter].distance.add(result[x]);
continue;
} else {
arr[arrayCounter].adj.add(result[x]);
continue;
}
}
arrayCounter++;
}
for (int i = 0; i < 12; i++) {
System.out.println(arr[i].name);
}
System.out.println(lineCounter);
dijkstra(arr, arr[3], lineCounter - 1);
printPath(arr[11]);
} finally {
br.close();
}
}
}
Using my vertex class as is I was using a series of while loops to first, traverse the adjacency strings stored in a linked list while comparing to see which vertex is equivalent to the adjacency list string. Is there a better way to code "for each Vertex w adjacent to v" using my Vertex class? And apologies ahead for messy code and any others style sins i may have committed. Thanks!
To solve this problem you need a bunch of "Node" objects, stored in a HashMap, keyed on Source Location.
In the node, you need a collection of references to adjacent "Node" objects (or at least their "key" so you can write logic against it. The "Node" also needs to know it's location and distance to each "adjacent" node. Think Lundon Underground Tube Maps - each station connects to at least one other station. Usually two or more. Therefore, adjacent nodes to tube stations are the immediate next stops you can get to from that station.
Once you have that data structure in place, you can then use a recursive routine to iterate through each individual node. It should then iterate through each child node (aka adjacent node), and track distances from the initial (source) node to the current node by storing this data in a HashMap and using the current accumulated distance whilst recursing (or "walking" the graph"). This tracking information should be part of your method signature when recursing. You will also need to track the current path you have taken when recursing, in order to avoid circular loops (which will ultimately and ironically cause a StackOverflowError). You can do this by using a HashSet. This Set should track the source and current node's location as the entry key. If you see this present during your recursion, then you have already seen it, so don't continue processing.
I'm not going to code the solution for you because I suspect that you ask more specific questions as you work your way through understanding the answer, which are very likely answered elsewhere.
I am working on building the game of Tic Tac Toe. Please find below the description of the classes used.
Game:: The main class. This class will initiate the multiplayer mode.
Board: This class sets the board configurations.
Computer: This class comprises of the minimax algorithm.
BoardState: This class comprises of the Board Object, along with the last x and y coordinates which were used to generate the board
configuration.
State: This class comprises of the score and the x and y coordinates that that will lead to that score in the game.
Context
Working on DFS here.
Exploring the whole tree works fine.
The game is set in such a way that the user is prompted to play first.
The user will put x and y co ordinates in the game.Coordinates are between 0 to 2. The Play of the player is marked as 1
The response from the computer is 2, which the algorithm decides. Th algorithm will determine the best possible coordinates to play and then play 2 on the position.
One of the winning configurations for Player is :
Player wins through diagonal
121
112
221
One of the winning configuration for AI is:
222
121
211
AI wins Horizontal
Problem
All the states give the max score.
Essentially, when you start the game in your system, you will find that since all states are given the max score, the computer looks to play sequentially.
As in if you put at (00), the computer plays at (01) and if you play at (02), the computer will play at (10)
I have been trying to debug it for a long time now. I believe, I may be messing up something with the scoring function. Or there could be a bug in the base recursion steps. Moreover, I don't think immutability among classes could cause problems as I have been recreating/creating new objects everywhere.
I understand, this might not be the best context I could give, but it would be a great help if you guys could help me figure out where exactly is it going wrong and what could I do to fix it. Answers through code/logic used would be highly appreciated. Thanks!
Game Class
import java.io.Console;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Game {
static int player1 = 1;
static int player2 = 2;
public static void main(String[] args) {
// TODO Auto-generated method stub
//
//PLays Game
playGame();
/* Test Use Case
ArrayList<Board> ar = new ArrayList<Board>();
Board b = new Board();
b.setVal(0,0,1);
b.setVal(0,1,1);
b.setVal(0,2,2);
b.setVal(1,0,2);
b.setVal(1,1,2);
b.setVal(2,0,1);
b.setVal(2,1,1);
b.display();
Computer comp = new Computer();
State x = comp.getMoves(b, 2);
*/
}
private static void playGame() {
// TODO Auto-generated method stub
Board b = new Board();
Computer comp = new Computer();
while(true)
{
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
int[] pmove = getPlayerMove(b);
b.setVal(pmove[0],pmove[1], player1);
if(b.isVictoriousConfig(player1))
{
System.out.println("Player 1 Wins");
break;
}
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
System.out.println("Computer Moves");
/*For Random Play
* int[] cmove = comp.computeMove(b);
*/
Computer compu = new Computer();
State s = compu.getMoves(b, 2);
int[] cmove = new int[2];
cmove[0] = s.x;
cmove[1] = s.y;
b.setVal(cmove[0],cmove[1], player2);
if(b.isVictoriousConfig(player2))
{
System.out.println("Computer Wins");
break;
}
}
System.out.println("Game Over");
}
//Gets Player Move. Basic Checks on whether the move is a valud move or not.
private static int[] getPlayerMove(Board b) {
// TODO Auto-generated method stub
int[] playerMove = new int[2];
System.out.println("You Play");
while(true)
{
#SuppressWarnings("resource")
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter X Position: ");
while(true)
{
playerMove[0] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[0] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("Enter Y Position: ");
while(true)
{
playerMove[1] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[1] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("You entered positions: X is " + playerMove[0] + " and Y is " + playerMove[1] );
if(!b.isPosOccupied(playerMove[0], playerMove[1]))
{
break;
}
System.out.println("Incorrect Move. PLease try again");
}
return playerMove;
}
}
Board Class
import java.util.Arrays;
public class Board {
// Defines Board Configuration
private final int[][] data ;
public Board()
{
data = new int[3][3];
for(int i=0;i<data.length;i++ )
{
for(int j=0;j<data.length;j++ )
{
data[i][j] = 0;
}
}
}
//Displays Current State of the board
public void display()
{
System.out.println("Board");
for(int i = 0; i< data.length;i++)
{
for(int j = 0; j< data.length;j++)
{
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
// Gets the Value on a specific board configuration
public int getVal(int i, int j)
{
return data[i][j];
}
//Sets the value to a particular board location
public void setVal(int i, int j,int val)
{
data[i][j] = val;
}
public boolean isBoardFull()
{
for(int i=0;i< data.length ; i++)
{
for(int j=0;j< data.length ;j++)
{
if(data[i][j] == 0)
return false;
}
}
return true;
}
public boolean isVictoriousConfig(int player)
{
//Noting down victory rules
//Horizontal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [0][1]) && (data[0][1] == data [0][2]) && (data[0][2] == player)))
return true;
if ((data[1][0] != 0) && ((data[1][0] == data [1][1]) && (data[1][1] == data [1][2]) && (data[1][2] == player)))
return true;
if ((data[2][0] != 0) && ((data[2][0] == data [2][1]) && (data[2][1] == data [2][2]) && (data[2][2] == player)))
return true;
//Vertical Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][0]) && (data[1][0] == data [2][0]) && (data[2][0] == player)))
return true;
if ((data[0][1] != 0) && ((data[0][1] == data [1][1]) && (data[1][1] == data [2][1]) && (data[2][1] == player)))
return true;
if ((data[0][2] != 0) && ((data[0][2] == data [1][2]) && (data[1][2] == data [2][2]) && (data[2][2] == player)))
return true;
//Diagonal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][1]) && (data[1][1] == data [2][2]) && (data[2][2] == player)))
return true;
if ( (data[0][2] != 0) && ((data[0][2] == data [1][1]) && (data[1][1] == data [2][0]) && (data[2][0] == player)))
return true;
//If none of the victory rules are met. No one has won just yet ;)
return false;
}
public boolean isPosOccupied(int i, int j)
{
if(data[i][j] != 0)
{
return true;
}
return false;
}
public Board(int[][] x)
{
this.data = Arrays.copyOf(x, x.length);
}
}
Board State
public class BoardState {
final Board br;
final int x ;
final int y;
public BoardState(Board b, int posX, int posY)
{
br = b;
x = posX;
y = posY;
}
}
State
public class State {
final int s;
final int x;
final int y;
public State(int score, int posX, int posY)
{
s = score;
x = posX;
y = posY;
}
}
Computer
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class Computer {
int[] pos = new int[2];
static int player2 = 2;
static int player1 = 1;
ArrayList<Board> win =new ArrayList<Board>();
ArrayList<Board> loose =new ArrayList<Board>();
ArrayList<Board> draw =new ArrayList<Board>();
public Computer()
{
}
public int[] computeMove(Board b)
{
while(true)
{
Random randX = new Random();
Random randY = new Random();
pos[0] = randX.nextInt(3);
pos[1] = randY.nextInt(3);
if(!b.isPosOccupied(pos[0], pos[1]))
{
return pos;
}
}
}
public State getMoves(Board b,int p)
{
//System.out.println("test2");
int x = 0;
int y = 0;
BoardState bs = new BoardState(b,0,0);
//System.out.println("test");
State s = computeMoveAI(bs,p);
//System.out.println("Sore : X : Y" + s.s + s.x + s.y);
return s;
}
private State computeMoveAI(BoardState b, int p) {
// TODO Auto-generated method stub
//System.out.println("Hello");
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.br.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("d is ");
//d.display();
//System.out.println("p is "+ p);
int xvalue= b.x;
int yvalue = b.y;
BoardState bs = new BoardState(d,xvalue,yvalue);
if(getConfigScore(d,p) == 1)
{
//System.out.println("Winning Config");
//System.out.println("X is " + b.x + " Y is " + b.y);
// b.br.display();
State s = new State(-1,bs.x,bs.y);
return s;
}
else if (getConfigScore(d,p) == -1)
{
//System.out.println("LooseConfig");
State s = new State(1,bs.x,bs.y);
//System.out.println("Coordinates are "+bs.x + bs.y+ " for " + p);
return s;
}
else if(bs.br.isBoardFull())
{
//System.out.println("Board is full");
State s = new State(0,bs.x,bs.y);
//System.out.println("score " + s.s + "x "+ s.x + "y "+ s.y);
return s;
}
else
{
//Get Turn
//System.out.println("In else condiyion");
int turn;
if(p == 2)
{
turn = 1;
}else
{
turn = 2;
}
ArrayList<BoardState> brr = new ArrayList<BoardState>();
ArrayList<State> st = new ArrayList<State>();
brr = getAllStates(d,p);
for(int k=0;k<brr.size();k++)
{
//System.out.println("Goes in " + "turn " + turn);
//brr.get(k).br.display();
int xxxxx = computeMoveAI(brr.get(k),turn).s;
State temp = new State(xxxxx,brr.get(k).x,brr.get(k).y);
st.add(temp);
}
//Find all Nodes.
//Go to First Node and proceed with recursion.
//System.out.println("Displaying boards");
for(int i=0;i<brr.size();i++)
{
//brr.get(i).br.display();
//System.out.println(brr.get(i).x + " " + brr.get(i).y);
}
//System.out.println("Board configs are");
for(int i=0;i<st.size();i++)
{
//System.out.println(st.get(i).x + " " + st.get(i).y + " and score " + st.get(i).s);
}
//System.out.println("xvalue" + xvalue);
//System.out.println("yvalue" + yvalue);
//System.out.println("Board was");
//d.display();
//System.out.println("Coming to scores");
//System.out.println(" p is "+ p);
if(p == 2)
{
//System.out.println("Size of first response" + st.size());
//System.out.println("Returns Max");
return max(st);
}
else
{
//System.out.println("The last");
return min(st);
}
}
}
private State min(ArrayList<State> st) {
// TODO Auto-generated method stub
ArrayList<State> st1= new ArrayList<State>();
st1= st;
int min = st.get(0).s;
//System.out.println("Min score is " + min);
for(int i=1;i<st1.size();i++)
{
if(min > st1.get(i).s)
{
min = st1.get(i).s;
//System.out.println("Min is");
//System.out.println(min);
//System.out.println("Min" + min);
State s = new State(min,st1.get(i).x,st1.get(i).y);
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Exits Min");
//System.out.println("Min Score" + st1.get(0).s + " x" + st1.get(0).x + "y " + st1.get(0).y);
return s;
}
private State max(ArrayList<State> st) {
// TODO Auto-generated method stub
//System.out.println("Size of first response in funciton is " + st.size());
ArrayList<State> st1= new ArrayList<State>();
st1 = st;
int max = st1.get(0).s;
for(int i=0;i<st1.size();i++)
{
// System.out.println(i+1 + " config is: " + "X:" + st1.get(i).x + "Y:" + st1.get(i).y + " with score " + st1.get(i).s);
}
for(int i=1;i<st1.size();i++)
{
//.out.println("Next Item " + i + st.get(i).s + "Coordinates X"+ st.get(i).x +"Coordinates Y"+ st.get(i).y );
if(max < st1.get(i).s)
{
max = st1.get(i).s;
//System.out.println("Max" + max);
//System.out.println("Max is");
//System.out.println(max);
State s = new State(max,st1.get(i).x,st1.get(i).y);
//System.out.println("Max Score returned" + s.s);
//System.out.println("Returned");
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Max is outer");
//System.out.println(st.get(0).s);
return s;
}
//Basic brain Behind Min Max algorithm
public int getConfigScore(Board b,int p)
{
int score;
int turn ;
int opponent;
if(p == player1)
{
turn = p;
opponent = player2;
}
else
{
turn = player2;
opponent = player1;
}
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("s arrasy is ");
//d.display();
//System.out.println("turn is " + turn);
if(d.isVictoriousConfig(turn))
{
score = 1;
}
else if(d.isVictoriousConfig(opponent))
{
score = -1;
}
else
{
score = 0;
}
return score;
}
public static ArrayList<BoardState> getAllStates(Board b, int player)
{
ArrayList<BoardState> arr = new ArrayList<BoardState>();
int[][]s1 = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s1[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(s1);
for(int i = 0;i <3; i ++)
{
for (int j=0;j<3;j++)
{
if(!d.isPosOccupied(i, j))
{
int previousState = d.getVal(i, j);
int[][]s = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s[i1][j1] = d.getVal(i1, j1);
}
}
s[i][j] = player;
Board d1 = new Board(s);
BoardState bs = new BoardState(d1,i,j);
arr.add(bs);
}
}
}
return arr;
}
}
This is the output of the test case in the Game class:
Board
1 1 2
2 2 0
1 1 0
Score : X : Y -> 1: 1: 2
The solution here is score:1 for x:1, y:2. It looks correct.
But again, you could say since it is moving sequentially, and since position (1,2) will come before (2,2), it gets the right coordinate.
I understand that this may be huge lines of code to figure out the problem. But
computemoveAI(), getConfigScore() could be the functions to look out for. Also I do not want to bias your thoughts with where I think the problem could as sometimes, we look somewhere , but the problem lies elsewhere.!!
I am trying to complete an assignment where I need to write a Java program to take a string from the command line, and implement it as a Binary Tree in a specific order, then get the depth of the binary tree.
For example: "((3(4))7((5)9))"
would be entered as a tree with 7 as the root, 3 and 9 as the children, and 4 as a right child of 3, and 5 as a left child of 9.
My code is below.. The problem I am having is that, because I am basing my checks off of finding a right bracket, I am unsure how to get the elements correctly when they are not directly preceding the brackets, such as the 3 in the above string. Any direction would be greatly appreciated..
class Node {
int value;
Node left, right;
}
class BST {
public Node root;
// Add Node to Tree
public void add(int n) {
if (root == null) {
root = new Node( );
root.value = n;
}
else {
Node marker = root;
while (true) {
if (n < marker.value) {
if (marker.left == null) {
marker.left = new Node( );
marker.left.value = n;
break;
} else {
marker = marker.left;
}
} else {
if (marker.right == null) {
marker.right = new Node( );
marker.right.value = n;
break;
} else {
marker = marker.right;
}
}
}
}
} // End ADD
//Find Height of Tree
public int height(Node t) {
if (t.left == null && t.right == null) return 0;
if (t.left == null) return 1 + height(t.right);
if (t.right == null) return 1 + height(t.left);
return 1 + Math.max(height(t.left), height(t.right));
} // End HEIGHT
// Check if string contains an integer
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
} // End ISINT
public int elementCount(String[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
if (isInt(a[i])) count++;
}
return count;
}
} // End BST Class
public class Depth {
public static void main(String[] args) {
String[] a = args[0].split(" ");
BST tree = new BST();
int[] bcount = new int[10];
int[] elements = new int[10];
int x = 0, bracketcount = 0;
// Display entered string
System.out.print("Entered Format: ");
for (int j=0; j < a.length; j++) {
System.out.print(a[j]);
}
for (int i=0; i < a.length; i++) {
char c = a[i].charAt(0);
switch (c)
{
case '(':
bracketcount++;
break;
case ')':
if (isInt(a[i-1])) {
bcount[x] = bracketcount--;
elements[x++] = Integer.parseInt(a[i-1]);
}
break;
case '1':
case '7':
default : // Illegal character
if ( (a[i-1].charAt(0) == ')') && (a[i+1].charAt(0) == '(') ) {
bcount[x] = bracketcount;
elements[x++] = Integer.parseInt(a[i]);
}
break;
}
}
System.out.println("\nTotal elements: " + tree.elementCount(a));
// Display BracketCounts
for (int w = 0; w < x; w++) {
System.out.print(bcount[w] + " ");
}
System.out.println(" ");
// Display Elements Array
for (int w = 0; w < x; w++) {
System.out.print(elements[w] + " ");
}
System.out.println("\nDepth: " + tree.height(tree.root));
// Build the tree
for (int y = 0; y < x-1; y++) {
for (int z = 1; z < tree.height(tree.root); z++) {
if (bcount[y] == z) {
tree.add(elements[y]);
}
}
}
} // End Main Function
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
}
} // End Depth Class
I would do a couple of statements to get access to a tree with that kind of shape:
For input string : input= "((3(4))7((5)9))"
You could do :
public class Trial {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = "((3(4))7((5)9))";
String easier = input.replaceAll("\\(\\(", "");
String evenEasier = easier.replaceAll("\\)\\)", "");
System.out.println(evenEasier);
int firstVal = Integer.parseInt(evenEasier.substring(0, 1));
int firstBracketVal = Integer.parseInt(evenEasier.substring(2, 3));
int middleVal = Integer.parseInt(evenEasier.substring(3, 4));
int secondBracketVal = Integer.parseInt(evenEasier.substring(4,5));
int lastVal = Integer.parseInt(evenEasier.substring(6));
System.out.println("First Val:"+firstVal);
System.out.println("First bracket Val:"+firstBracketVal);
System.out.println("Middle Val:"+middleVal);
System.out.println("Second Bracket Val:"+secondBracketVal);
System.out.println("Last Val:"+lastVal);
}
}
This however would only ever work for entries in that specific format, if that were to change, or the length of the input goes up - this would work a bit or break.....If you need to be able to handle more complicated trees as input in this format a bit more thought would be needed on how to best handle and convert into your internal format for processing.
pseudocode:
function getNode(Node)
get one char;
if (the char is "(")
getNode(Node.left);
get one char;
end if;
Node.value = Integer(the char);
get one char;
if (the char is "(")
getNode(Node.right);
get one char;
end if;
//Now the char is ")" and useless.
end function
Before calling this function, you should get a "(" first.
In this method, the framwork of a Node in string is "[leftchild or NULL] value [rightchild or NULL])".
"("is not belong to the Node, but ")" is.
Any hint to avoid getting time limit exceeded for this problem :_
http://www.spoj.com/problems/BUGLIFE/
how could i optimize this code
is there a faster method for reading input
these are my methods for reading input :_
http://ideone.com/GtSIAC
my solution :_
import java.io.*;
import java.util.*;
public class buglife {
static int first;
static ArrayList[] graph = new ArrayList[2000];
static int[] colour = new int[2000];
static int[] queue = new int[2000];
static int start;
static int index;
static int current;
public static boolean bfs(int f) {
for (int p = 0; p < first; p++) {
if (colour[p] != f && colour[p] != f + 1) {
int x;
start = 0;
index = 0;
queue[index++] = p;
colour[p] = f;
while (start < index) {
current = queue[start++];
for (int i = 0; i < graph[current].size(); i++) {
x = (Integer) graph[current].get(i);
if (colour[x] != f && colour[x] != f + 1) {
if (colour[current] == f) {
colour[x] = f + 1;
} else if (colour[current] == f + 1) {
colour[x] = f;
}
queue[index++] = x;
} else if (colour[current] == colour[x]) {
return false;
}
}
}
}
}
return true;
}
public static void main(String[] args) throws IOException, Exception {
int second;
int one, two;
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
int test = nextInt();
int j, k, i;
for (i = 1; i <= test; i++) {
first = nextInt();
second = nextInt();
for (k = 0; k < first; k++)
graph[k] = new ArrayList();
for (j = 0; j < second; j++) {
one = nextInt();
two = nextInt();
graph[one - 1].add(two - 1);
graph[two - 1].add(one - 1);
}
out.println("Scenario #" + i + ":");
if (bfs( 2 * i) == false) {
out.println("Suspicious bugs found!");
} else {
out.println("No suspicious bugs found!");
}
}
out.flush();
}
}
You can not solve it using only bfs, this problem is about Bipartite graph
Just look it at wikipedia
I solved this problem more than a year ago. my profile
I am trying to implement Karger's min cut algorithm but I am unable to get the correct answer. Can someone please have a look at my code and help me figure out what I am doing wrong? Would really appreciate the help.
package a3;
import java.util.*;
import java.io.*;
public class Graph {
private ArrayList<Integer>[] adjList;
private int numOfVertices = 0;
private int numOfEdges = 0;
public Graph(String file) throws IOException {
FileInputStream wordsFile = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(wordsFile));
adjList = (ArrayList<Integer>[]) new ArrayList[201];
for (int i = 1; i < 201; i++) {
adjList[i] = new ArrayList<Integer>();
}
while (true) {
String s = br.readLine();
if (s == null)
break;
String[] tokens = s.split("\t");
int vertex = Integer.parseInt(tokens[0]);
this.numOfVertices++;
for (int i = 1; i < tokens.length; i++) {
Integer edge = Integer.parseInt(tokens[i]);
addEdge(vertex, edge);
this.numOfEdges++;
}
}
}
public void addEdge(int v, int w) {
adjList[v].add(w);
//this.numOfEdges++;
}
public ArrayList<Integer> getNeighbors(Integer v) {
return adjList[v];
}
public boolean hasEdge(Integer i, Integer j) {
return adjList[i].contains(j);
}
public boolean removeEdge(Integer i, Integer j) {
if (hasEdge(i, j)) {
adjList[i].remove(j);
adjList[j].remove(i);
this.numOfEdges -= 2;
return true;
}
return false;
}
public int getRandomVertex(){
Random rand = new Random();
return (rand.nextInt(this.getNumOfVertices()) + 1);
}
//Returns an array which consists of vertices connected by chosen edge
public int[] getRandomEdge(){
int arr[] = new int[2];
arr[0] = this.getRandomVertex();
while (adjList[arr[0]].size() == 0) {
arr[0] = this.getRandomVertex();
}
Random rand = new Random();
arr[1] = adjList[arr[0]].get(rand.nextInt(adjList[arr[0]].size()));
return arr;
}
//Algorithm for min cut
public int minCut() {
while (this.getNumOfVertices() > 2) {
int[] edge = this.getRandomEdge();
this.removeEdge(edge[0], edge[1]);
//Adding edges of second vertex to first vertex
for (Integer v: adjList[edge[1]]) {
if (!adjList[edge[0]].contains(v)) {
addEdge(edge[0], v);
}
}
//Removing edges of second vertex
for (Iterator<Integer> it = adjList[edge[1]].iterator(); it.hasNext();) {
Integer v = it.next();
it.remove();
this.numOfEdges--;
}
//Removing self-loops
for (Iterator<Integer> it = adjList[edge[0]].iterator(); it.hasNext();) {
Integer v = it.next();
if (v == edge[0])
it.remove();
//this.numOfEdges--;
}
this.numOfVertices--;
}
return this.numOfEdges;
}
public int getNumOfVertices() {
return this.numOfVertices;
}
public int getNumOfEdges() {
return (this.numOfEdges) / 2;
}
public String toString() {
String s = "";
for (int v = 1; v < 201; v++) {
s += v + ": ";
for (int e : adjList[v]) {
s += e + "-> ";
}
s += null + "\n";
//s += "\n";
}
return s;
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int min = 1000;
//Graph test = new Graph("C:\\Users\\UE\\Desktop\\kargerMinCut.txt");
for (int i = 0; i < 10; i++) {
Graph test = new Graph("C:\\Users\\UE\\Desktop\\kargerMinCut.txt");
int currMin = test.minCut();
min = Math.min( min, currMin );
}
System.out.println(min);
}
}