Image

Imagematthias382 wrote in Imagephp 😎productive

Listens: Staind - Outside

I SO have no sense of direction...

Let me see if I can amaze and astound any of you with this problem. It's partially logic, partially PHP implementation. I'm trying to create a function that will receive an array of cardinal directions and from that array remove any directions that cancel each other out. The problem here is that there may be consecutive instances of the same direction in the array. I want to do this as efficiently as possible, though. Anybody know an algorithm or approach to this problem? What I basically need is a way to find the fastest path through a maze. I've only got one line of thought on the problem at the moment.

Let's say that the array contains three consecutive "north" items, followed by three consecutive "south" items. The items in this array obviously cancel each other out and put you right back where you started. Somewhere in that list, though, there should be a "north" and a "south" right next to each other. That is...

1 - n
2 - n
3 - n
4 - s
5 - s
6 - s

In this list, items 3 and 4 are opposites. So if the function recognizes this and removes them from the list, here's what we've got...

1 - n
2 - n
5 - s
6 - s

So there's still an instance of a "north" and a "south" right up against each other. If the function loops until it finds no consecutive directions that are opposites, that should theoretically give me the optimal path to get to my destination.

However, there's a problem with this approach. What if you have a situation like this?

1 - n
2 - w
3 - s
4 - e

You've just gone in a circle, but this algorithm would never pick that up. Also...

1 - n
2 - w
3 - s
4 - w

Obviously, the most efficient way would've been to just go west twice, but what if there's a wall there that prevents taking this route.

Any ideas??