Why wrong with the breadth first search of graph - graph

public static void BFS(TTNode node){
Set<TTNode> accessedNodes = new HashSet<TTNode>();
Queue<TTNode> queue = new LinkedList<TTNode>();
queue.offer(node);
while (!queue.isEmpty()){
TTNode accessingNode = queue.poll();
System.out.println(accessingNode.payload);
accessedNodes.add(accessingNode);
for (TTNode child : accessingNode.children){
if (!accessedNodes.contains(child)){
queue.offer(child);
}
}
}
}
why the result is : 1 2 3 4 5 5 5, the 5 shows up three times?

The problem with your code is that you should mark a node visited just before
pushing it in the queue. Say we have a graph with three nodes 1 to 3. And the edges
are (1-2) , (1-3) , (3-2). Now you push say 1 first, according to your code you pop 1 mark it as visited and push 2 and 3 ( say in this order ). Now you pop 2 and mark it visited. Now amongst neighbors of 2, 3 is still marked unvisited so you push it again. So node 3 ends up multiple times in the queue in bfs. I don't know what language you have written the code in but I have made the change hope syntax is correct
public static void BFS(TTNode node){
Set<TTNode> accessedNodes = new HashSet<TTNode>();
Queue<TTNode> queue = new LinkedList<TTNode>();
queue.offer(node);
accessedNodes.add(node);
while (!queue.isEmpty()){
TTNode accessingNode = queue.poll();
System.out.println(accessingNode.payload);
for (TTNode child : accessingNode.children){
if (!accessedNodes.contains(child)){
accessedNodes.add(child);
queue.offer(child);
}
}
}
}
Do comment if I made a mistake in code or if you still have a doubt.

Related

Cannot get Realm result for objects filtered by the latest (nsdate) value of a property of a collection property swift (the example is clearer)

I Have the following model
class Process: Object {
#objc dynamic var processID:Int = 1
let steps = List<Step>()
}
class Step: Object {
#objc private dynamic var stepCode: Int = 0
#objc dynamic var stepDateUTC: Date? = nil
var stepType: ProcessStepType {
get {
return ProcessStepType(rawValue: stepCode) ?? .created
}
set {
stepCode = newValue.rawValue
}
}
}
enum ProcessStepType: Int { // to review - real value
case created = 0
case scheduled = 1
case processing = 2
case paused = 3
case finished = 4
}
A process can start, processing , paused , resume (to be in step processing again), pause , resume again,etc. the current step is the one with the latest stepDateUTC
I am trying to get all Processes, having for last step ,a step of stepType processing "processing ", ie. where for the last stepDate, stepCode is 2 .
I came with the following predicate... which doesn't work. Any idea of the right perform to perform such query ?
my best trial is the one. Is it possible to get to this result via one realm query .
let processes = realm.objects(Process.self).filter(NSPredicate(format: "ANY steps.stepCode = 2 AND NOT (ANY steps.stepCode = 4)")
let ongoingprocesses = processes.filter(){$0.steps.sorted(byKeyPath: "stepDateUTC", ascending: false).first!.stepType == .processing}
what I hoped would work
NSPredicate(format: "steps[LAST].stepCode = \(TicketStepType.processing.rawValue)")
I understand [LAST] is not supported by realm (as per the cheatsheet). but is there anyway around I could achieve my goal through a realm query?
There are a few ways to approach this and it doesn't appear the date property is relevant because lists are stored in sequential order (as long as they are not altered), so the last element in the List was added last.
This first piece of code will filter for processes where the last element is 'processing'. I coded this long-handed so the flow is more understandable.
let results = realm.objects(Process.self).filter { p in
let lastIndex = p.steps.count - 1
let step = p.steps[lastIndex]
let type = step.stepType
if type == .processing {
return true
}
return false
}
Note that Realm objects are lazily loaded - which means thousands of objects have a low memory impact. By filtering using Swift, the objects are filtered in memory so the impact is more significant.
The second piece of code is what I would suggest as it makes filtering much simpler, but would require a slight change to the Process model.
class Process: Object {
#objc dynamic var processID:Int = 1
let stepHistory = List<Step>() //RENAMED: the history of the steps
#objc dynamic var name = ""
//ADDED: new property tracks current step
#objc dynamic var current_step = ProcessStepType.created.index
}
My thought here is that the Process model keeps a 'history' of steps that have occurred so far, and then what the current_step is.
I also modified the ProcessStepType enum to make it more filterable friendly.
enum ProcessStepType: Int { // to review - real value
case created = 0
case scheduled = 1
case processing = 2
case paused = 3
case finished = 4
//this is used when filtering
var index: Int {
switch self {
case .created:
return 0
case .scheduled:
return 1
case .processing:
return 2
case .paused:
return 3
case .finished:
return 4
}
}
}
Then to return all processes where the last step in the list is 'processing' here's the filter
let results2 = realm.objects(Process.self).filter("current_step == %#", ProcessStepType.processing.index)
The final thought is to add some code to the Process model so when a step is added to the list, the current_step var is also updated. Coding that is left to the OP.

How do I translate LR(1) Parse into a Abstract syntax tree?

I have coded a table driven LR(1) parser and it is working very well however I am having a bit of a disconnect on the stage of turing a parse into a syntax tree/abstract syntax tree. This is a project that I m very passionate about but I have really just hit a dead end here. Thank you for your help in advance.
Edit: Also my parser just uses a 2d array and an action object that tells it where to go next or if its a reduction where to go and how many items to pop. I noticed that many people use the visitor pattern. Im not sure how they know what type of node to make.
Here is the pushdown automata for context
while (lexer.hasNext() || parseStack.size() > 0) {
Action topOfStack = parseStack.peek();
token = parseStack.size() > 0 ? lexer.nextToken() : new Token(TokenType.EOF, "EOF");
topOfStack.setToken(token);
int row = topOfStack.getTransitionIndex();
int column = getTerminalIndex(token.getLexeme());
column = token.getType() == TokenType.IDENTIFIER
&& !terminalsContain(token.getLexeme()) ? 0 : column;
Action action = actionTable[row][column];
if (action instanceof Accept) {
System.out.println("valid parse!!!!!!");
} else if (action instanceof Reduction) {
Reduction reduction = (Reduction) action;
popStack(parseStack, reduction.getNumberOfItemsToPop());
column = reduction.getTransitionIndex();
row = parseStack.peek().getTransitionIndex();
parseStack.push(new Action(gotoTable[row][column]));
lexer.backupTokenStream();
} else if (action != null) {
parseStack.push(actionTable[row][column]);
} else {
System.out.println("Parse error");
System.out.println("On token: " + token.getLexeme());
break;
}
Each reduction in the LR parsing process corresponds to an internal node in the parse tree. The rule being reduced is the internal AST node, and the items popped off the stack correspond to the children of that internal node. The item pushed for the goto corresponds to the internal node, while those pushed by shift actions correspond to leaves (tokens) of the AST.
Putting all that together, you can easily build an AST by createing a new internal node every time you do a reduction and wiring everything together appropriately.

How to check characters at a certain position in a string .net

In my project the customer have a card and a 7 letter particular security code is in it. I want to ask 3 letters from that security code by position.
eg. card security code is **57GHY58**
I want to ask what is the Character at 2,4 and 7 position in your security code?
answer is **7H8**
How to generate that question with random postion and how to check it ?
private static int[] GetThreeRandomNumbers()
{
List<int> list = new List<int>();
Random r = new Random();
while (list.Count < 3)
{
int num = r.Next(1, 7);
if (!list.Contains(num))
{
list.Add(num);
}
}
list.Sort();
return list.ToArray();
}
You have a string with indices 0-6. You need to pick 3 indices from that range randomly. The Random class will help you with this, have a look at its method Random.Next(int, int), it will return you a random number from the specified range. Then the only other thing you have to do is skip the indices you have already used.

Object differentiation

I'm creating a graph with nodes (with integer value) and edges (source, destination and weight) by reading a file with the format
1 51 1
1 72 2
1 77 1
etc.
Set<Node> nodes = new HashSet<Node>(); //a set of the nodes of a graph
ArrayList<Node> nodeList = new ArrayList<Node>();
ArrayList<Edge> edgeList = new ArrayList<Edge>();
...
Node node1=new Node(Integer.parseInt(temprelation[0]));
Node node2=new Node(Integer.parseInt(temprelation[1]));
nodes.add(node1);
nodes.add(node2);
Edge edge = new Edge(node1, node2, Integer.parseInt(temprelation[2]));
edgeList.add(edge);
}
The class Node has also a field "number of neighbors", and I wanted to go through all the edges and increment the number of neighbors whenever either source or destinatio appears.
for (int edge=0; edge<graph.getEdges().size(); edge++){
graph.getEdges().get(edge).getSource().neighborUp();
graph.getEdges().get(edge).getDestination().neighborUp();
}
Strangely enough, although the objects seem to be the same (I checked it with equals), the counter does not go up. E.g., for 1, it goes up once with the first edge, but does not go up when I try to increment it when the second edge is concerned. When considering the second edge before incrementing, it somehow shows the number of neighbors is 0, although I incremented the number of neighbors of the first node already in the first edge. So if I did printouts of counters before and after incrementation I always get 0 1 0 1 as if some other objects were concerned.
I assume that you use Java.
The problem is with creation of the graph, every time when you create an edge you create new objects for nodes:
Node node1=new Node(Integer.parseInt(temprelation[0]));
Node node2=new Node(Integer.parseInt(temprelation[1]));
The set contains only one copy for every Integer, but your edges contain different instancies.
To solve it you can create a map of all already parsed nodes and at every iteration instead of creating object from Integer, check if you have already created the object from Integer:
//one global object
Map<Integer,Node> map = new HashMap<Integer,Node> ();
...
Integer val = Integer.parseInt(temprelation[0]);
if (map.get(val)==null) {
map.put(val, new Node(val));
}
Node node1 = map.get(val);
val = Integer.parseInt(temprelation[1]);
if (map.get(val)==null) {
map.put(val, new Node(val));
}
Node node2 = map.get(val);

Pathfinding issues

Ok I am trying to make a dynamic pathing system so the player can move from point A to point B without having predefined paths. Note this game is all text based no graphics. The player can move in 10 directions: up, down, n, e, s, w, sw, se, nw and ne.
The map of the entire world is in a database, each row of the database contains a room or a node, each room/node has directions it's capable of going. The room may not be sequential persay. An Example:
Map Number, Room Number, Direction_N, Direction_S, Direction_E, Direction_W, etc.
1 1 1/3 1/100 1/1381 1/101
The Direction_N indicates it goes to Map 1 Room 3, Direction_S Map 1 Room 100, etc...
Ok, I reworked the code with suggestions (thank you guys by the way!) here is revised code. It seems to find the rooms now, even vast distances! But now the issue is finding the shortest path to the destination, I tried traversing the collection but the path is not coming out right...
In the image link below, I have start point in red square in center and stop point at red square at upper left. This returns visitedStartRooms = 103 and visitedStopRooms = 86, when it's only about 16 rooms.
Quess my missing piece of the puzzle is I am not sure how to sort out the rooms in those collection to gain the true shortest route.
Example of map
Here is the new code
public void findRoute(ROOM_INFO startRoom, ROOM_INFO destinationRoom)
{
Dictionary<ROOM_INFO, bool> visitedStartRooms = new Dictionary<ROOM_INFO, bool>();
Dictionary<ROOM_INFO, bool> visitedStopRooms = new Dictionary<ROOM_INFO, bool>();
List<string> directions = new List<string>();
startQueue.Enqueue(startRoom); // Queue up the initial room
destinationQueue.Enqueue(destinationRoom);
visitedStartRooms.Add(startRoom, true);// say we have been there, done that
visitedStopRooms.Add(destinationRoom, true);
string direction = "";
bool foundRoom = false;
while (startQueue.Count != 0 || destinationQueue.Count != 0)
{
ROOM_INFO currentStartRoom = startQueue.Dequeue(); // remove room from queue to check out.
ROOM_INFO currentDestinationRoom = destinationQueue.Dequeue();
ROOM_INFO startNextRoom = new ROOM_INFO();
ROOM_INFO stopNextRoom = new ROOM_INFO();
if (currentStartRoom.Equals(destinationRoom))
{
break;
}
else
{
// Start from destination and work to Start Point.
foreach (string exit in currentDestinationRoom.exitData)
{
stopNextRoom = extractMapRoom(exit); // get adjacent room
if (stopNextRoom.Equals(startRoom))
{
visitedStopRooms.Add(stopNextRoom, true);
foundRoom = true;
break;
}
if (stopNextRoom.mapNumber != 0 && stopNextRoom.roomNumber != 0)
{
if (!visitedStopRooms.ContainsKey(stopNextRoom))
{
if (visitedStartRooms.ContainsKey(stopNextRoom))
{
foundRoom = true;
}
else
{
destinationQueue.Enqueue(stopNextRoom);
visitedStopRooms.Add(stopNextRoom, true);
}
}
}
}
if (foundRoom)
{
break;
}
}
// start from the start and work way to destination point
foreach (string exit in currentStartRoom.exitData)
{
startNextRoom = extractMapRoom(exit); // get adjacent room
if (startNextRoom.Equals(destinationRoom))
{
visitedStartRooms.Add(startNextRoom, true);
foundRoom = true;
break;
}
if (startNextRoom.mapNumber != 0 && startNextRoom.roomNumber != 0)
{
if (!visitedStartRooms.ContainsKey(startNextRoom))
{
if (visitedStopRooms.ContainsKey(startNextRoom))
{
foundRoom = true;
break;
}
else
{
startQueue.Enqueue(startNextRoom);
visitedStartRooms.Add(startNextRoom, true);
}
}
}
}
if (foundRoom)
{
break;
}
}
}
You have a good start. There are a few basic improvements that will help. First, to be able to reconstruct your path, you should create a new data structure to store visited rooms. But for each entry, you want to store the room, plus the previous room in the path back to the starting point. A good data structure for this would be a dictionary where the key is the room identifier, and the value is the previous room identifier. To know if you've visited a room, you look to see if it exists in that data structure, not your openList queue. With this new structure, you can properly check if you've visited a room, and you can reconstruct the path back by repeatedly looking up the previous room in the same structure until you get to the origination.
The second improvement will increase the performance quite a bit. Instead of just doing a breadth-first search from the start point until you bump into the destination, as you currently do, instead create matching data structures like you have for the start room search, but have them be for the destination room. After you've looked one room away from the start, look one room away from the destination. Repeat this...two rooms away from start, then two rooms away from destination.. etc., working your way out, until you discover a room that has been visited by both your search from start and your search from destination. Build the path from this room back to the start, and back to the destination, and that will be your shortest path.
The problem you are trying to solve is the shortest path problem with unweighted edges or where the weights of all edges are equal. The weight of an edge is the time/cost to move from one room to another. If the cost to move from one room to another varies depending on which pair of rooms you're talking about, then the problem is more complicated, and the algorithm you started with and for which I've suggested modifications, will not work as it is. Here are some links about it:
Shortest path (fewest nodes) for unweighted graph
http://en.wikipedia.org/wiki/Shortest_path_problem
You may also be interested in the A* algorithm which uses a different approach. It uses a hueristic approach to concentrate the search in a subset of the solution space more likely to contain the shortest path. http://en.wikipedia.org/wiki/A%2a_search_algorithm
But A* is probably overkill in your case since the weight of all edges is the same between all rooms.

Resources