How do I Backtrack a Stack-Based Depth First Search - search

I am trying to implement a DFS algorithm to work in a maze. The maze has walls. The DFS gets stuck in a corner and does not backtrack therefore it results in an infinite loop. How should I rewrite my code to get it to backtrack. This is code for a space-search type of DFS.
Depth-First-Search Function
public List<Node<Point2D>> DFS(Problem p)
{
Node<Point2D> root = new Node<Point2D>() { Data = p.initial, Parent = null };
frontierStack.Push(root);
while (frontierStack.Count > 0 && explored.Count < 55)
{
Node<Point2D> currentNode = frontierStack.Pop();
explored.Add(currentNode.Data.ToString());
Console.WriteLine(currentNode);
//Debug.WriteLine(explored.Count);
foreach (string action in p.Action)
{
if (p.Result(currentNode.Data, action) != null)
{
Node<Point2D> adjacentNode
= new() { Data = p.Result(currentNode.Data, action), Parent = currentNode };
if (explored.Contains(adjacentNode.Data.ToString()) == false || frontierStack.Contains(adjacentNode) == false)
{
if (p.GoalTest(adjacentNode.Data) == true)
{
return GetNodes(adjacentNode);
}
}
frontierStack.Push(adjacentNode);
}
}
}
return null;
}
Here is Where it gets stuck:
The black line is the path it took, the blue 'X' are walls and the red 'X' is where it gets stuck at point (1,3) - (1,4). I have been trying to resolve this for a few hours now. Nothing seems to be working. I am still a beginner so sorry for asking something so trivial and thank you for your help in advance.

Solved it. Hope this is useful for other beginners out there.
Updated DFS Algorithm
foreach (string action in p.Action)
{
if (p.Result(currentNode.Data, action) != null)
{
Node<Point2D> adjacentNode = new() {
Data = p.Result(currentNode.Data, action),
Parent = currentNode
};
frontierStack.Push(adjacentNode);
if (explored.Contains(adjacentNode.Data.ToString()) == false || frontierStack.Contains(adjacentNode) == false)
{
if (p.GoalTest(adjacentNode.Data) == true)
{
return GetNodes(adjacentNode);
}
}
else if (explored.Contains(adjacentNode.Data.ToString()) == true && frontierStack.Contains(adjacentNode) == true)
{
frontierStack.Pop();
}
}
}
Add the else if to check if it is either visited/explored and still in the frontier.

Related

Clone of list still correct the original list

In groovy the original value get overwritten when I change values in a clone list. Does anyone know if I am doing it wrong or it is a bug older groovy?
I am doing something like this:
List<Foo> myFooList = fooList.newFoos.findAll { it.type == "Types}
List<Foo> newFoo = fooList.oldFoos.findAll { it.type == "Types}.clone()
newFoo.each {
it.value = "neeeew value"
}
Foo fooOne = newFoo.each { foooo ->
fooTwo = fooList.oldFoos.find { it.id == foooo.id}
if(fooTwo.value != foooo.value) {
//Here it should go... but it turns out that fooTwo.value == foooo.value
}
}
the clone method called on list produces a new list but with the same objects in it.
you want to build new list with new objects. here is an example:
#groovy.transform.ToString
class Foo{
String type
String value
}
def fooList = [
new Foo(type:"Types", value:'old value1'),
new Foo(type:"Not", value:'old value2'),
new Foo(type:"Types", value:'old value3'),
new Foo(type:"Not", value:'old value4'),
]
def newFooList = fooList.
findAll{it.type=='Types'}.
collect{ new Foo(type:it.type, value:"new value") } //build new array with transformed elements
//check the original list
fooList.each{assert it.value!='new value'}
//check new list
newFooList.each{assert it.value=='new value'}
assert newFooList.size()==2
println fooList
println newFooList
I solved the issue by adding clone of the element as well, any way it became to much of cowboy fix:
List<Foo> myFooList = fooList.newFoos.findAll { it.type == "Types}
List<Foo> newFoo = fooList.oldFoos.findAll { it.type == "Types}.collect {it.clone()}
newFoo.each {
it.value = "neeeew value"
}
Foo fooOne = newFoo.each { foooo ->
fooTwo = fooList.oldFoos.find { it.id == foooo.id}
if(fooTwo.value != foooo.value) {
//Here it should go... but it turns out that fooTwo.value == foooo.value
}
}

shouldInteractWithURL called twice on 3d touch

Below is the issue that i am trying to fix. I have a textView whose text is an attributed string with link attribute. On clicking the link, i should go to other screen. So, I am performing that screen navigation on shouldInteractWithURL() delegate method of the textView. Everything works fine except on force touching the textView, the next page is loading twice. That means shouldInteractWithURL() is called twice on force tap. I fixed it by checking the stack of the view controllers and if the last VC is the one that is about to load, I am returning from there. But, I wanted to know if there is any other solution other than this. Below is the code snippet
textView.text = ""
guard var str = myStr else {
return nil
}
let linkAttribute = [NSLinkAttributeName: NSURL(string: "")!]
var attributedStr:NSMutableAttributedString?
if delay {
str += " "
attributedStr = NSMutableAttributedString(string: str)
let ctaStr = kSuccessStr
let ctaAttributedString = NSAttributedString(string: ctaStr, attributes: linkAttribute)
attributedStr!.appendAttributedString(ctaAttributedString)
} else {
let ctaStr = kFailedStr
attributedStr = NSMutableAttributedString(string: ctaStr, attributes: linkAttribute)
}
textView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.grayColor()]
textView.attributedText = attributedStr
textView.delegate = thisTableViewDelegate
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool
{
if let textLink = textView.text
{
if (textLink.rangeOfString(str1) != nil) ||
(textLink.rangeOfString(str2) != nil)
{
showSignUpForm(self)
}
else
{
showSuccessfulForm()
}
}
return true
}
Use textView:shouldInteractWithURL:inRange:interaction: instead.
Check if interaction != UITextItemInteractionInvokeDefaultAction and return NO.
See https://developer.apple.com/reference/uikit/uitextviewdelegate/1618606-textview?language=objc
I handle only invokeDefaultAction and it works for me:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if interaction == .invokeDefaultAction {
//do some stuff
}
return false
}

Accidently deleting entire linked list when trying to delete the head

I'm working on a checker's simulation game for my C++ class. My issue is with the linked list that holds the checkers. I can delete any checker perfectly with the exception of the head of the list. I've looked around here and other websites and I believe there's a memory leak somewhere. I'm fairly new to C++ so I'm not sure what to really do other than playing around with things (which will probably just create a bigger problem). I've never posted here before, so excuse me if the formatting is slightly off or too messy. I'll try to make it brief. First, here's a snippet of the node class for the linked list.
class CheckerpieceNode
{
private:
Checkerpiece *Node;
CheckerpieceNode *Next;
public:
CheckerpieceNode(); // sets Node and Next to NULL in .cpp file
void setNode(Checkerpiece *node);
void setNext(CheckerpieceNode *next);
Checkerpiece* getNode();
CheckerpieceNode* getNext();
};
And the functions are set up pretty much as you would expect in a Checkerpiece.cpp class.
Here's how the code is used. Its called by a Checkerboard object in my main class.
theCheckerboard.removeChecker(theCheckerboard.findChecker(selector->getCurrentX() + 0, selector->getCurrentY() - VERTICAL_SHIFT, listHead), listHead);
The VERTICAL_SHIFT simply has to do with the way my checkerboard graphic is on the console. Since it works perfectly for all other nodes (excluding the head) I've ruled it out as a source of error. Selector is a checkerpiece object but its not part of the list.
Here's the actual findChecker and removeChecker code from Checkerboard class.
Checkerpiece* findChecker(int x, int y, CheckerpieceNode* list_head)
{
if(list_head== NULL) return NULL; // do nothing
else
{
CheckerpieceNode* node = new CheckerpieceNode;
node = list_head;
while(node != NULL && node->getNode() != NULL)
{
if()// comparison check here, but removed for space
{
return node->getNode();
delete node;
node = NULL;
}
else // traversing
node = node->getNext();
}
return NULL;
}
}
void removeChecker(Checkerpiece* d_checker, CheckerpieceNode* list_head)
{
if(list_head== NULL) // throw exception
else
{
CheckerpieceNode *temp = NULL, *previous = NULL;
Checkerpiece* c_checker= new Checkerpiece;
temp = list_head;
while(temp != NULL && temp->getNode() != NULL)
{
c_checker= temp->getNode();
if(d_checker!= c_checker)
{
previous = temp;
temp = temp->getNext();
}
else
{
if(temp != list_head)
{
previous->setNext(temp->getNext());
delete temp;
temp = NULL;
}
else if(temp == list_head) // this is where head should get deleted
{
temp = list_head;
list_head= list_head->getNext();
delete temp;
temp = NULL;
}
return;
}
}
}
}
Oh my, you're complicating it. Lots of redundant checks, assignments and unnecessary variables (like c_checker which leaks memory too).
// Write down the various scenarios you can expect first:
// (a) null inputs
// (b) can't find d_checker
// (c) d_checker is in head
// (d) d_checker is elsewhere in the list
void removeChecker(Checkerpiece* d_checker, CheckerpieceNode* list_head) {
// first sanitize your inputs
if (d_checker == nullptr || list_head == nullptr) // use nullptr instead of NULL. its a keyword literal of type nullptr_t
throw exception;
// You understand that there is a special case for deleting head. Good.
// Just take care of it once and for all so that you don't check every time in the loop.
CheckerpieceNode *curr = list_head;
// take care of deleting head before traversal
if (d_checker == curr->getNode()) {
list_head = list_head->next; // update list head
delete curr; // delete previous head
return; // we're done
}
CheckerpieceNode *prev = curr;
curr = curr->next;
// traverse through the list - keep track of previous
while (curr != nullptr) {
if (d_checker == curr->getNode()) {
prev->next = curr->next;
delete curr;
break; // we're done!
}
prev = curr;
curr = curr->next;
}
}
I hope that helps. Take the time to break down the problem into smaller pieces, figure out the scenarios possible, how you'll handle them and only then start writing code.
Based on this edit by the question author, the solution he used was to:
I modified the code to show the address passing in the checker delete
function.
void delete_checker(Checker* d_checker, CheckerNode* &list_head) // pass by address
{
if(list_head== NULL) // throw exception
else
{
CheckerNode*temp = NULL, *previous = NULL;
Checker* c_checker= new Checker;
temp = list_head;
while(temp != NULL && temp->node!= NULL)
{
c_checker= temp->node;
if(d_checker!= c_checker)
{
previous = temp;
temp = temp->next;
}
else
{
if(temp != list_head)
{
previous->next = temp->next;
delete temp;
temp = NULL;
}
else if(temp == list_head) // this is where head should get deleted
{
temp = list_head;
list_head= list_head->next;
delete temp;
temp = NULL;
}
delete c_checker;
c_checker = nullptr;
return;
}
}
}
}
removeChecker cannot modify the value of list_head as it is past by value. The method signature should be:
void removeChecker(Checkerpiece* d_checker, CheckerpieceNode** list_head)
// You will need to call this function with &list_head
or
void removeChecker(Checkerpiece* d_checker, CheckerpieceNode* &list_head)
// Calling code does not need to change

Linq-to-Entities returns results, but not iterating in ForEach

Here I have what I believe is a simple Linq-to-Entities query:
static IEnumerable<T> SequenceByExample<T>(T t) { return null; } // Learnt this from SOF
var clientsMonthly = SequenceByExample(new { ClientCode = "", InvoicingActivityStartDay = "", InvoicingActivityEndDay = "" });
if (DateTime.TryParse(Date1Param, out date1))
{
tmp_day1 = date1.Day.ToString();
clientsMonthly = from cd in mydbcontext.ClientSchedules
where cd.ClientSchedule == "Monthly"
&& cd.InvoicingActivityStartDay == tmp_day1
select new
{
cd.CLIENT.ClientCode,
cd.InvoicingActivityStartDay,
cd.InvoicingActivityEndDay
};
}
else
{
clientsMonthly = from cd in mydbcontext.ClientSchedules
where cd.ClientSchedule == "Monthly"
&& cd.InvoicingActivityStartDay == SqlFunctions.StringConvert((double)DateTime.Now.Day)
select new
{
cd.CLIENT.ClientCode,
cd.InvoicingActivityStartDay,
cd.InvoicingActivityEndDay
};
}
foreach (var item in clientsMonthly)
{
// this part is never executed
}
The if executes when a date is passed to the method, otherwise it goes to the else part.
When debugging, the flow hits the else part, it executes the Linq query; however the foreach that follows the if..else does not iterate. It skips the foreach loop as if there were no data returned.
When I tried the Linq query in LinqPad, I can see it returns results. This is driving me nuts, and don't know what is wrong. Kindly take a look and tell me what is wrong.
Thank you.

Comparing pointers fails mystically in VC++

I have a tree structure and I want to find all nodes matching a given criteria. Each time I call the find function, it returns next matching node. Children are searched by recursive function call.
For some reason a key comparison of pointers fails for this implementation. Please see the code below, I have pointed out the failing comparison.
HtmlTag* HtmlContent::FindTag(string tagName, string tagParameterContent)
{
if (tagName.empty() && tagParameterContent.empty())
return NULL;
if (this->startTag == NULL)
return NULL;
this->findContinue = this->FindChildren(this->startTag, &tagName, &tagParameterContent);
return this->findContinue;
}
HtmlTag* HtmlContent::FindChildren(HtmlTag* firstTag, string* tagName, string* tagParameterContent)
{
HtmlTag* currentTag = firstTag;
HtmlTag* childrenFound = NULL;
while (currentTag != NULL)
{
if (!tagName->empty() && *tagName == currentTag->tagName)
{
if (tagParameterContent->empty() || currentTag->tagParameters.find(*tagParameterContent, 0) != -1)
{
if (this->findContinue == NULL)
break; // break now when found
else if (this->findContinue == currentTag) // TODO why this fails?
this->findContinue == NULL; // break on next find
}
}
if (currentTag->pFirstChild != NULL)
{
childrenFound = this->FindChildren(currentTag->pFirstChild, tagName, tagParameterContent);
if (childrenFound != NULL)
{
currentTag = childrenFound;
break;
}
}
currentTag = currentTag->pNextSibling;
}
return currentTag;
}
VC++ compiler accepts this code but for some reason I can't put a breakpoint on this comparison. I guess this is optimized out, but why? Why this comparison fails?
I think that you shoud replace == with = in assignment after comparison. Compiler optimalized this whole section because it doesnt do anything useful.

Resources