Depth first search did find solution state in Missionaries and Cannibals problems - c#

I am doing my project on Missionaries and Cannibals using C#. I have used two search algorithms namely breadth first search and depth first search. Using Breadth first search, the program finds the result at level 12 from the root. But using Depth first search, it can not find solution and this hangs my computer. I think it enters a cycle in the graph. So my question is, can't i use Depth first search to solve Missionaries and cannibals problem?
Code for Breadth first search is
public State getSolutionStatesBFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, true);
while (searchAgenda.Count > 0) {
CurState = (State)searchAgenda.Dequeue();
if (CurState.Equals(EndState)) {
break;
} else {
if (!isVisited(CurState, visited))
{
generateSucessors(CurState, true);
visited.Add(CurState);
}
}
}
return CurState;
}
and the code for depth first search is
public State getSolutionStatesDFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, false);
while (searchAgendaS.Count > 0)
{
CurState = (State)searchAgendaS.Pop();
if (CurState.Equals(EndState))
{
break;
}
else
{
if(!isVisited(CurState,visited))
{
generateSucessors(CurState, false);
}
}
}
return CurState;
}

It is hard to tell answer seeing your code. However, based upon my experience: a DFS search does not provide complete solution. There is a good possibility that your code might have got stuck into some infinite loop (which is common with dfs) or (since, you are checking isVisited), there is a possibility that you are not reaching the end goal.

So my question is, can't i use Depth first search to solve Missionaries and cannibals problem?
Yes, it is deffinatly possible, take a look at this site:
http://www.aiai.ed.ac.uk/~gwickler/missionaries.html
With the code given its hard to tell where your issue is.

Related

How to create a tag on a specific line/column/length in Visual Studio editor?

I would like to create tags in the Visual Studio editor to insert all sorts of glyphs, adornments, text hightlightings, etc., based on line/column/length locations in the code.
I have been carefully reading the documentation walkthrough pages (https://learn.microsoft.com/en-us/visualstudio/extensibility/walkthrough-creating-a-margin-glyph?view=vs-2017 and related pages). Although a bit complex and hard to understand, it seems like the API is very much oriented on giving the means to analyse the code: it is able to give your code split into spans, with classifications, etc.
However, I have the "opposite" need: I already have the analysis done by my external analysis engine. And I already have a set of results to be displayed in the editor with line/column/length for each one. Like:
function "foo", located at line 345, column 1, length 3, and other fields containing information to be displayed,
variable "my_var", located at line 349, column 13, length 6, and other fields containing information to be displayed,
Is it possible to create tags in the Visual Studio editor directly based on their line/column/length location? Any hint, any pointer to more detailed documentation or tutorial would be greatly appreciated.
Lance's link was quite helpful to understand another way to create tags different from the MS documentation example.
Indeed, I don't analyse the text contained into the spans, the analysis is already done outside. I get some list of "defects" locations.
I get them into a defectsLocation dictionary (defectsLocation[filename][line] = location data (...)
Here is was I did:
internal class MyDefectTagger : ITagger<MyDefectTag>
{
private IClassifier m_classifier;
private ITextBuffer m_buffer;
internal MyDefectTagger(IClassifier classifier, ITextBuffer buffer)
{
m_classifier = classifier;
m_buffer = buffer;
}
IEnumerable<ITagSpan<MyDefectTag>>
ITagger<MyDefectTag>.GetTags(NormalizedSnapshotSpanCollection spans)
{
if (MyModel.Instance == null || MyModel.Instance.defectsLocation == null)
{
yield return null;
}
var filename = GetFileName(m_buffer);
if (!MyModel.Instance.defectsLocation.ContainsKey(filename))
{
yield return null;
}
foreach (SnapshotSpan span in spans)
{
ITextSnapshot textSnapshot = span.Snapshot;
foreach (ITextSnapshotLine textSnapshotLine in textSnapshot.Lines)
{
var line = textSnapshotLine.LineNumber + 1; // Lines start at 1 in VS Editor
if (MyModel.Instance.defectsLocation[filename].ContainsKey(line) &&
!MyModel.Instance.defectsLocation[filename][line].rendered)
{
var rendered = MyModel.Instance.defectsLocation[filename][line].rendered;
yield return new TagSpan<MyDefectTag>(
new SnapshotSpan(textSnapshotLine.Start, 0),
new MyDefectTag()
);
}
}
}
}
}

IsolatedStorage and navigation

I can't sort this weird issue out and I have tried anything and everything I can think of.
I got 5 pages, everyone of them passing variables with navigation this way:
Pass:
NavigationSerice.Navigate(new Uri("/myPage.xaml?key=" + myVariable, UriKind.Relative));
Retrieve:
If (NavigationContext.QueryString.ContainsKey(myKey))
{
String retrievedVariable = NavigationContext.QueryString["myKey"].toString();
}
I open a list on many pages and one of the pages automatically deletes an item from the list actualProject (actualProject is a variable for a string list). Then, when I go so far back that I reach a specific page - the app throws an exception. Why? I have no idea.
The code that deletes the item:
// Remove the active subject from the availible subjects
unlinkedSubjects.Remove(actualSubject);
unlinkedsubjectsListBox.ItemsSource = null;
unlinkedsubjectsListBox.ItemsSource = unlinkedSubjects;
Then the page that throws the exception's OnNavigatedTo event:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.ContainsKey("key"))
{
actualProject = NavigationContext.QueryString["key"];
try
{
//Read subjectList from IsolatedStorage
subjectList = readSetting(actualProject) != null ? (List<String>)readSetting(actualProject) : new List<String>();
//Put the subjectList into the subjectListBox
subjectListBox.ItemsSource = subjectList;
//Set the subjectsPageTitle to the "actualProject" value, to display the name of the current open project at the top of the screen
subjectsPageTitle.Text = actualProject;
}
catch (Exception)
{
if (language.Equals("en."))
{
// Language is set to english
MessageBox.Show("Couldn't open the project, please try again or please report the error to Accelerated Code - details on the about page");
}
else if (language.Equals("no."))
{
// Language is set to norwegian
MessageBox.Show("Kunne ikke åpne prosjektet, vennligst prøv igjen eller rapporter problemet til Accelerated Code - du finner detaljer på om-siden");
}
}
}
}
Exception:
_exception {System.ArgumentException: Value does not fall within the expected range.} System.Exception {System.ArgumentException}
My theory:
The app kind of loads the currently opened and modified List. Is that possible? No idea.
So there are a number of ways to pass data between pages.
The way you have chosen is the least suggested.
You can use the PhoneApplicationService.Current dictionary but this is messy also if you have a ton of variables, doesn't persist after app shut down and could be simplified.
I wrote a free DLL that kept this exact scenario in mind called EZ_iso.
You can find it here
Basically what you would do to use it is this.
[DataContractAttribute]
public class YourPageVars{
[DataMember]
public Boolean Value1 = false;
[DataMember]
public String Value2 = "And so on";
[DataMember]
public List<String> MultipleValues;
}
Once you have your class setup you can pass it easily between pages
YourPageVars vars = new YourPageVars { /*Set all your values*/ };
//Now we save it
EZ_iso.IsolatedStorageAccess.SaveFile("PageVars",vars);
That's it! Now you can navigate and retrieve the file.
YourPageVars vars = (YourPageVars)EZ_iso.IsolatedStorageAccess.GetFile("PageVars",typeof(YorPageVars));
This is nice because you can use it for more than navigation. You can use it for anything that would require Isolated storage. This data is serialized to the device now so even if the app shuts down it will remain. You can of course always delete the file if you choose as well.
Please make sure to refer to the documentation for any exceptions you have. If you still need help feel free to hit me up on twitter #Anth0nyRussell or amr#AnthonyRussell.info

Conversion OF FIFO code from Java to c#

couple of days ago i posted a topic about fifo programming and how to do it because the topic was a bit broad and vague and lacks coding example, so i followed experts advice and searched for codes and tried a bit of coding. and i knew exactly what i wanted to do
i want to create a DES (Discrete event simulation) for the FIFO (first in first out) scheduling algorithm using the C# as my programming language.
so i searched the net and i couldn't find something really helpful in c# for guidance but i found exactly what i wanted to in java codes. which i will post now
The process of Initialization
Queue q = new Queue();
EventQueue eventq = new EventQueue();
Random rand = new Random();
Distribution interarrivalTimeDist =
new ExponentialDistribution(lambda, rand);
Distribution serviceTimeDist =
new ExponentialDistribution(mu, rand);
double t = 0;
// generate first arrival
eventq.addEvent(new Event(Event.ARRIVAL,
interarrivalTimeDist.nextRandom()));
Main program
while (t < simLength) {
Event e = eventq.nextEvent();
t = e.getTime();
switch (e.getType()) {
case Event.ARRIVAL : {
// handle arrival
}
case Event.DEPARTURE : {
// handle departure
}
}
}
Case of Arrival
case Event.ARRIVAL : {
// schedule next arrival
eventq.addEvent(new Event(Event.ARRIVAL,
t + interarrivalTimeDist.nextRandom()));
double serviceTime =
serviceTimeDist.nextRandom();
q.addCustomer(new Customer(t, serviceTime));
if (q.getSize() == 1) {
eventq.addEvent(new Event(Event.DEPARTURE,
t + serviceTime));
}
break;
}
Case of departure
case Event.DEPARTURE : {
q.removeCustomer(t);
if (q.getSize() > 0) {
double serviceTime =
q.getCustomerAt(0).getServiceTime();
eventq.addEvent(new Event(Event.DEPARTURE,
t + serviceTime));
}
break;
}
any clues or guidance how to convert this code to c#??
and help will help highly appreciated it
PS:- for the experts please show some tolerance if my topic wasn't as professional as you guys thought it will be
thanks
Your question sounds a lot like "how do I program this idea", and isn't a good SO question. You should design a lot about what you want to do, build it in steps, and come here with specific questions you have, not broad ideas or lots of code.
To answer just FIFO, that is a queue. Read about queues and practice with them.

Recursive conditions

Sorry to put up yet another recursion question, but I've looked over a fair few on here and haven't found the solution for my problem.
I use the below function:
unsafe
{
// Allocate global memory space for the size of AccessibleContextInfo and store the address in acPtr
IntPtr acPtr = Marshal.AllocHGlobal(Marshal.SizeOf(new AccessibleContextInfo()));
try
{
Marshal.StructureToPtr(new AccessibleContextInfo(), acPtr, true);
if (WABAPI.getAccessibleContextInfo(vmID, ac, acPtr))
{
acInfo = (AccessibleContextInfo)Marshal.PtrToStructure(acPtr, typeof(AccessibleContextInfo));
if (!ReferenceEquals(acInfo, null))
{
AccessibleTextItemsInfo atInfo = new AccessibleTextItemsInfo();
if (acInfo.accessibleText)
{
IntPtr ati = Marshal.AllocHGlobal(Marshal.SizeOf(new AccessibleTextItemsInfo()));
WABAPI.getAccessibleTextItems(vmID, ac, ati, 0); //THIS IS WHERE WE DO IT
atInfo = (AccessibleTextItemsInfo)Marshal.PtrToStructure(ati, typeof(AccessibleTextItemsInfo));
if (ati != IntPtr.Zero)
{
Marshal.FreeHGlobal(ati);
}
}
AccessibleTreeItem newItem = BuildAccessibleTree(acInfo, atInfo, parentItem, acPtr);
newItem.setAccessibleText(atInfo);
if (!ReferenceEquals(newItem, null))
{
for (int i = 0; i < acInfo.childrenCount; i++)
{
//Used roles = text, page tab, push button
if (acInfo.role_en_US != "unknown" && acInfo.states_en_US.Contains("visible")) // Note the optomization here, I found this get me to an acceptable speed
{
AccessibleContextInfo childAc = new AccessibleContextInfo();
IntPtr childContext = WABAPI.getAccessibleChildFromContext(vmID, ac, i);
GetAccessibleContextInfo(vmID, childContext, out childAc, newItem);
if (childContext != IntPtr.Zero)
{
Settings.Save.debugLog("Releasing object " + childContext.ToString() + " from JVM: " + vmID);
WABAPI.releaseJavaObject(vmID, childContext);
childContext = IntPtr.Zero;
}
}
}
}
return newItem;
}
}
else
{
acInfo = new AccessibleContextInfo();
}
}
finally
{
if (acPtr != IntPtr.Zero)
Marshal.FreeHGlobal(acPtr);
}
}
return null;
}
To build an AccessibleTreeItem representing the entire GUI of a Java application. However, this function takes 5-6 seconds to run. I'm only looking for one particular subsection of the tree (Lets call it Porkchops).
What I'd like to do is prior to building the tree, get the values and as soon as acRole.name == "Porkchop", use that as the parent object and create an AccessibleTreeItem that represents the subtree.
How on earth do I manage this? If this is a simple question, apologies, but it's driving me crazy.
Edit 1 - The performance hit is encountered on releaseJavaObject(), as when I remove that line the function completes in less than a second, but it creates a horrible memory leak.
Therefore, I'm not really looking for alternative solutions, as I know that the above does work correctly. I just need some way to check the value of acInfo.name prior to creating the tree, and then using the correct acInfo node as the parent.
Edit 2 - See the attached image for a better explanation than my rambling. Currently, the function will pull this entire tree from the JVM. I've highlighted the appropriate section that I work with, and would like to know if there's a way that will allow me to get that information, without building the entire tree. Or even if I could just return the tree once all children of that node have been populated.

Complicated C# for learning purposes

I'm trying to read some of other people's code, both to help me learn C#, and also purely to develop my ability to understand other people's code, but a lot of what I've found online to look at is both very long, and relatively simple. I wonder if anyone could point me to something short but more complex, preferably including less common uses of the language.
(It doesn't need to do anything sensible, so long as it does something. Something entirely pointless, like a C# equivilent of the XSLT Mandelbrot, would be perfectly fine)
Eric Lippert has recently been writing a series on graph colouring on his blog. This may well be something to sink your teeth into as it's a multi-part series that should allow you to work your way from simple to brain-meltingly-ouch as he progresses with explaining graph colouring. =)
I'd recommend looking at the Effective C# books. They'll help you learn more complex uses of the language.
Take a look at the mono source code - many of the BCL classes are implemented and you are sure to learn something :)
There are also many open source .NET projects out there that are not small and simple applications that you can look at.
Here are some off the top of my head:
MonoDevelop - a .NET IDE
nHibernate - an ORM
Pinta - image manipulation a la gimp
Raytracing in one LINQ statement, from Luke Hoban's blog, jumps immediately to mind.
Take a look at the .NET framework assemblies themselves using the .NET Reflector. There is a bunch of really great stuff in there and has helped me a lot during my learning.
Many times I have thought to myself how Microsoft has done certain things in the framework and I was easily able to find the answers right within their source.
Check out Coding4Fun. It's a mix of .Net languages and some (most) of the projects are really cool. XNA Creators Club is pretty cool as well... plenty of samples and it you have an XBox360 or a Zune you can write games for them as well.
How about this?
private Element ReadMemberExpression()
{
var queue = new Queue<Element[]>();
var newDepth = 0;
var argsCount = 0;
_scanner.CreateRestorePoint();
while (true)
{
_scanner.CreateRestorePoint();
{
var a = ReadArguments();
if (a != null)
{
argsCount++;
if (argsCount > newDepth)
{
_scanner.Restore();
break;
}
queue.Enqueue(new[] { default(Element), default(Element), a });
_scanner.DeleteRestorePoint();
continue;
}
}
_scanner.DeleteRestorePoint();
var pe = ReadPrimaryExpression();
if (pe != null)
{
queue.Enqueue(new[] { pe });
continue;
}
var fe = ReadFunctionExpression();
if (fe != null)
{
queue.Enqueue(new[] { fe });
continue;
}
if (_scanner.MatchNext(Grammar.New))
{
newDepth++;
queue.Enqueue(new[] { Grammar.New });
}
else if (_scanner.Match(Grammar.LeftSquareBracket))
{
var e = ReadExpression();
if (e == null)
{
throw new ParseException();
}
if (!_scanner.MatchNext(Grammar.RightSquareBracket))
{
throw new ParseException();
}
queue.Enqueue(new[]{default(Element), Grammar.LeftSquareBracket, e, Grammar.RightSquareBracket});
}
else if (_scanner.Match(Grammar.FullStop))
{
if (!_scanner.MatchNext(ElementType.IdentifierName))
{
throw new ParseException();
}
queue.Enqueue(new[] { default(Element), Grammar.FullStop, _scanner.Current });
}
else
{
_scanner.Unwind();
break;
}
}
if (queue.Count == 0)
{
_scanner.DeleteRestorePoint();
return null;
}
else
{
var element = default(Element);
var children = queue.Dequeue();
while (children[0] == Grammar.New)
{
children = queue.Dequeue();
}
element = new Element(ElementType.MemberExpression, children);
while (queue.Count > 0)
{
children = queue.Dequeue();
if (children.Length == 3 && children[2].Type == ElementType.Arguments)
{
newDepth--;
children[0] = Grammar.New;
children[1] = element;
element = new Element(ElementType.MemberExpression, children);
}
else
{
children[0] = element;
element = new Element(ElementType.MemberExpression, children);
}
}
if (newDepth > 0)
{
_scanner.Restore();
return null;
}
_scanner.DeleteRestorePoint();
return element;
}
}
It's not terribly complex, but may be briefly entertaining -- Mads Torgersen has implemented a fixed-point combinator in C# here:
http://blogs.msdn.com/b/madst/archive/2007/05/11/recursive-lambda-expressions.aspx
This may be an obvious suggestion, but I would checkout the articles on CodeProject.com. You can search for specific articles relevant to C#, and the contributors generally do a great job of explaining their code.
For instance, here is an article on creating a Mandelbrot set in C# (though this may not be as complex as you might be looking for).
Other than that, I would take a peak inside any C# opensource projects you may find via Google.

Categories

Resources