Finding an algorithm that can find the shortest way to solve a one dimensional variant of the "lights out" game - algorithm

I'm solving a task from an old programming competition. The task is to make a program that can find if there exists a possible solution, and what the shortest solution is, for a version of the well known game "lights out". In short, we have several lights connected. By clicking on of the lights you change the status of it, and the two adjacent lights. The goal is to activate all the lights.
In the classic version of "lights out" we are working with two dimensions, but in this version the lights are connected in a "one dimensional" string, where the "edges" are connected. Basically a circle of lights.
The number of lights can go up to 10000, so the bruteforce method I tried was obviously not good enough. It only manages to solve the versions that have a solution, and where there are under ~10 lights. Here is an example of a solveable setup. The 1's mark lights that are activated, and the 0's mark lights that are deactivated. The first line includes the number of lights in the string. If a solution doesn't excist, the program will output that it isn't possible. Remember that the edges are connected.
5
10101
Click one of the "edges" (doesn't matter which one, I clicked the left one).
01100
Click the opposite edge
11111
If a solution doesn't excist the program outputs a message. If not, it outputs the shortest solution, in this case: 2.
Could anyone help me find an algorithm?
Thanks for the help.

Suppose you knew whether in the solution (if one exists) you need to click on the first and second light.
Once we have this information, we can immediately deduce whether we need to click on the third light as this is the last choice that can affect the second light (clicking on the first light changes the last/first/second, clicking on the second light changes the first/second/third, clicking on the third light changes the second/third/fourth - but no other clicks can change the second light).
Similarly, we can then immediately deduce whether to click the fourth light, as this is the last choice that can affect the third light.
You can then work all the way round to the end to find out whether you have a consistent solution (with all lights out).
Simply try all 4 options for the first 2 switches, and pick the best scoring one.
Complexity O(4n)

Related

recovering order from samples

I have a pool of balls of 30 different color patterns(solid green, green and red striped, etc), and I also have 6 boxes ordered from 1 to 6. Now randomly I select 6 balls out of the pool and put each ball in one box so that each box contains exactly one ball. And among the 6 balls, the color pattern of each ball can be different from or the same as color pattern of other balls in other boxes. Now I want you to guess the color pattern of the ball in each box by doing the following:
Every time you make a request to me and I will randomly select 3 balls and display the balls in front of you in the same order of the box order. You can make unlimited requests.
The problem is how to tell the color pattern of the ball in each box by making least requests, I feel like there should be a well-known algorithm for this problem, but I can not find any. Has anybody seen this before?
I think there is a lot of statistics in this. First of all, I would make the simplifying assumption that (if you don't know which colour balls are present) the only colours and patterns available are those which you have seen.
Now write down, or work out how to calculate, a formula that gives you the probability of the observed data given the listing of which balls are present in which boxes.
Now all you have to do is find the combination of balls in boxes that gives the highest probability to the observed data, and hope that as you get more and more data the right answer wins out.
You could think of this as a generic optimisation problem, and try hill-climbing from multiple random starts, or genetic programming, or whatever your favourite heuristic is.
Or you could do a bit more web-searching about statistics and recognise that this is a missing data problem, where the hidden data is the knowledge of which box each sampled ball came from. Statisticians often solve hidden data problems with the EM algorithm. There is an introduction for mathematicians at http://www.inf.ed.ac.uk/teaching/courses/pmr/docs/EM.pdf. Your problem can be thought of as a simple case of a hidden Markov model, with the hidden state being the box which produced a particular ball.

Indefinitely move objects around randomly without collision

I have an application where I need to move a number of objects around on the screen in a random fashion and they can not bump into each other. I'm looking for an algorithm that will allow me to generate the paths that don't create collisions and can continue for an indefinite time (i.e.: the objects keep moving around until a user driven event removes them from the program).
I'm not a game programmer but I think this looks like an AI problem and you guys probably solve it with your eyes closed. From what I've read A* seems to be the recommended 'basic idea' but I don't really want to invest a lot of time into it without some confirmation.
Can anyone shed some light on an approach? Anti-gravity movement maybe?
This is to be implemented on iOS, if that is important
New paths need to be generated at the end of each path
There is no visible 'grid'. Movement is completely free in 2D space
The objects are insects that walk around the screen until they are killed
A* is an algorithm to find the shortest path between a start and a goal configuration (in terms of whatever you define as short: common are e.g. euclidean distance, cost or time, angular distance...). Your insects seem not to have a specific goal, they don't even need a shortest path. I would certainly not go for A*. (By the way, since you are having a dynamic environment, D* would have been an idea - still it's meant to find a path from A to B).
I would tackle the problem as follows:
Random Paths and following them
For the random paths I see two methods. The first would be a simple random walk (click here to see a nice 2D animation with explanations), which can suffer from jittering and doesn't look too nice. The second one needs a little bit more detailed explanations.
For each insect generate four random points around them, maybe starting on a sinusoid. With a spline interpolation generate a smooth curve between those points. Take care of having C1 (in 2D) or C2 (in 3D) continuity. (Suggestion: Hermite splines)
With Catmull-Rom splines you can find your configurations while moving along the curve.
An application of a similar approach can be found in this blog post about procedural racetracks, also a more technical (but still not too technical) explanation can be found in these old slides (pdf) from a computer animations course.
When an insect starts moving, it can constantly move between the second and third point, when you always remove the first and append a new point when the insect reaches the third, thus making that the second point.
If third point is reached
Remove first
Append new point
Recalculate spline
End if
For a smoother curve add more points in total and move somewhere in the middle, the principle stays the same. (Personally I only used this in fixed environments, it should work in dynamic ones as well though.)
This can, if your random point generation is good (maybe you can use an approach similar to the one provided in the above linked blog post, or have a look at algorithms on the PCG Wiki), lead to smooth paths all over the screen.
Avoid other insects
To avoid other insects, three different methods come to my mind.
Bug algorithms
Braitenberg vehicles
An application of potential fields
For the potential fields I recommend reading this paper about dynamic motion planning (pdf). It's from robotics, but fairly easy to apply to your problem as well. You can just use the robots next spline point as the goal and set its velocity to 0 to apply this approach. However, it might be a bit too much for your simple game.
A discussion of Braitenberg vehicles can be found here (pdf). The original idea was more of a technical method (drive towards or away from a light source depending on how your motor is coupled with the photo receptor) and is often used to show how we apply emotional concepts like fear and attraction to other objects. The "fear" behaviour is an approach used for obstacle avoidance in robotics as well.
The third and probably simplest method are bug algorithms (pdf). I always have problems with the boundary following, which is a bit tricky. But to avoid another insect, these algorithms - no matter which one you use (I suggest Bug 1 or Tangent Bug) - should do the trick. They are very simple: Move towards your goal (in this application with the catmull-rom splines) until you have an obstacle in front. If the obstacle is close, change the insect's state to "obstacle avoidance" and run your bug algorithm. If you give both "colliding" insects the same turn direction, they will automatically go around each other and follow their original path.
As a variation you could just let them turn and recalculate a new spline from that point on.
Conclusion
Path finding and random path generation are different things. You have to experiment around what looks best for your insects. A* is definitely meant for finding shortest paths, not for creating random paths and following them.
You cannot plan the trajectories ahead of time for an indefinite duration !
I suggest a simpler approach where you just predict the next collision (knowing the positions and speeds of the objects allows you to tell if they will collide and when), and resolve it by changing the speed or direction of either objects (bounce before objects touch).
Make sure to redo a check for collisions in case you created an even earlier collision !
The real challenge in your case is to efficiently predict collisions among numerous objects, a priori an O(N²) task. You will accelerate that by superimposing a coarse grid on the play field and look at objects in neighboring cells only.
It may also be possible to maintain a list of object pairs that "might interfere in some future" (i.e. considering their distance and relative speed) and keep it updated. Checking that a pair may leave the list is relatively easy; efficiently checking for new pairs needing to enter the list is not.
Look at this and this Which described an AI program to auto - play Mario game.
So in this link, what the author did was using a A* star algorithm to guide Mario Get to the right border of the screen as fast as possible. Avoid being hurt.
So the idea is for each time frame, he will have an Environment which described the current position of other objects in the scene and for each action (up, down left, right and do nothing) , he calculate its cost function and made a decision of the next movement based on this.
Source: http://www.quora.com/What-are-the-coolest-algorithms
For A* you would need a 2D-Grid even if it is not visible. If I get your idea right you could do the following.
Implement a pathfinding (e.g. A*) then just generate random destination points on the screen and calculate the path. Once your insect reaches the destination, generate another destination point/grid-cell and proceed until the insect dies.
As I see it A* would only make sence if you have obstacles on the screen the insect should navigate around, otherwise it would be enough to just calculate a straight vector path and maybe handle collision with other insects/objects.
Note: I implemented A* once, later I found out that Lee's Algorithm
pretty much does the same but was easier to implement.
Consider a Hamiltonian cycle - the idea is a route that visits all the positions on a grid once (and only once). If you construct the cycle in advance (i.e. precalculate it), and set your insects off with some offset between them, they will never collide, simply because the path never intersects itself.
Also, for bonus points, Hamiltonian paths tend to 'wiggle about', and because it's a loop you can predict (and precalculate) the path into the indefinite future.
You can always use the nodes of the grid as knot points for a spline to smooth the movement, or even randomly shift all the points away from their strict 2d grid positions, until you have the desired motion.
Example Hamiltonian cycle from Wikimedia:
On a side note, if you want to generate such a path, consider constructing a loop through many points and just moving the points around in such a manner that they never intersect an existing edge. With some encouragement to move into gaps and away from each other, they should settle into some long, never-intersecting path. Store the result and use for your loop.

Alien tiles heuristic function

I am trying to find a good A* heuristic function for the problem "alien tiles", found at www.alientiles.com for a uni project.
In alien tiles you have a board with NxN tiles, all colored red. By clicking on a tile, all tiles in the same row and column advance by a color, the color order being red->green->blue->purple, resetting to red after purple. The goal is to change all tiles to the specified colors. The simplest goal state is all the tiles going from red to green, blue or purple. The board doesn't have to be 7x7 as the site suggests.
I've thought of summing the difference between each tile and the target tile and dividing by 2N-1 for an NxM board or or finding possible patterns of clicks as the minimum number of clicks, but neither has been working well. I can't think of a way to apply relaxation to the problem or divide it into sub-problems either, since a single click affects an entire row and column.
Of course I'm not asking for anyone to find a solution for me, but some tips or some relevant, simpler problems that I can look at (rubik's cube is such an example that I'm looking at).
Thanks in advance.
The problem you are trying to solve is similar to NIM FOCUS name. Please have a look at it. The solutions for it can be found in Stuart J. Russell book under heuristics section. Hope this helps
Although it is a relatively 'dumb' way of thinking around the problem, one heuristic mechanism i have found that drastically cuts down on the number of states that a star expands, tries to figure out a relationship between the cell that has been clicked most recently and the number of states that clicking on it again would expand. Its like telling a star: "If you have clicked on a cell in your last move, try clicking on another one this time." Obviously in special scenarios,
(e.g. having all the board on your target colour, say green, and only a purple cross where clicking on the center of the cross twice changes the cross colour to green and then you are done)
this way of thinking is actually detrimental. But, it is a place to start.
Please let me know if u figure anything out, as it is something i am working on as well.

Plat former Game - A realistic path-finding algorithm

I am making a game and i have come across a hard part to implement into code. My game is a tile-bases platformer with lots of enemies chasing you. basically, in theory, I want my enemies to be able to, every frame/second/2 seconds, find the realistic, and shortest path to my player. I originally thought of A-star as a solution, but it leads the enemies to paths that defy gravity, which is not good. Also, multiple enemies will be using it every second to get the latest path, and then walk the first few tiles of it. So they will be discarding the rest of the path every second, and just following the first few tiles of it. I know this seems like a lot, to calculate a new path every second, all at the same time, if their is more than one enemy, but I don't know any other way to achieve what i want.
This is a picture of what I want:
Explanation: The green figure is the player, the red one is an enemy. the grey tiles are regular, open, nothing there tiles, the brown tiles being ones that you can stand on. And finally the highlighted yellow tiles represents the path that i want my enemy to be able to find, in order to realistically get to the player.
SO, the question is: What realistic path-finding algorithm can i use to acquire this? While keeping it fast?
EDIT*
I updated the picture to represent the most complicated map that their could be. this map represents what the player of my game actually sees, they just use WASD and can move around and they see themselves move through this 2d plat-former view. Their will be different types of enemies, all with different speeds and jump heights. but all will have enough jump height and speed to make the jumps in this map, and maneuver through it. The maps are generated by simply reading an XML file that has the level data in it. the data is then parsed and different types of tiles are placed in the tile holding sprite, acording to what the XML says. EX( XML node: (type="reg" graphic="grass2" x="5" y="7") and so the x and y are multiplied by the constant gridSize (like 30 or something) and they are placed down accordingly. The enemies get their frame-by-frame instruction from an AI class attached to them. This class is responsible for producing this path and return the first direction to the enemy, this should only happen every second or so, so that the enemies don't follow a old, wrong path. Please let me know if you understand my concept, and you have some thought/ideas or maybe even the answer that i'm looking for.
ALSO: the physics in this game is separate from the pathfinding, they work just fine, using a AABB vs AABB concept (the player and enemies also being AABBs).
The trick with using A* here is how you link tiles together to form available paths. Take for example the first gap the red player would need to cross. The 'link' to the next platform (aka brown tile to the left) is actually a jump action, not a move action. Additionally, it's up to you to determine how the nodes connect together; I'd add a heavy penalty when moving from a gray tile over a brown tile to a gray tile with nothing underneath just for starters (without discouraging jumps that open a shortcut).
There are two routes I see personally: running a quick prediction of how far the player can jump and where they'd jump and adjusting how the algorithm determines node adjacency or accept the path and determine when parts of the path "hang" in the air (no brown tile immediately below) and animate the enemy 'jumping' to the next part of the path. The trick is handling things when the enemy may pass through brown tiles in the even the path isn't a parabola.
I am not versed in either solution; just something I've thought about.
You need to give us the most complicated case of map, player and enemy behaviour (including jumping up and across speed) that you are going to either automatically create or manually create so we can give relevant advice. The given map is so simple, put the map in an 2-dimensional array and then the initial player location as an element of that map and then first test whether lower number column on the same row is occupied by brown if not put player there and repeat until false then same row higher column and so on to move enemy.
Update: from my reading of the stage generation- its sometime you create- not semi-random.
My suggestion is the enemy creates clones of itself with its same AI but invisible and each clone starts going in different direction jump up/left/right/jump diagonal right/left and every time it succeeds it creates a new clone- basically a genetic algorithm. From the map it seems an enemy never need to evaluate one path over another just one way fails to get closer to the player's initial position and other doesn't.

algorithm for the validating the net-walk puzzle game

What is a simplest algorithm for validating if all the connections have been made successfully and all the connections are closed?
I have laid the game tiles and the game is ready to play all i need is an algorithm to verify and make the changes to the connections when the user clicks on each tile every time.
for your reference a game like this one
One simple way would be to do a classic "Depth-First Search" (https://en.wikipedia.org/wiki/Depth-first_search), where tiles are vertices.
Create a boolean variable which is initially "True".
Color in blue the tiles you manage to reach with a Depth First Search from the source, and refresh every time the user rotates a tile. While doing this, check if there are any leaks and give the variable the value "False" if it happens.
The puzzle is solved if all the vertices are visited and the variable is "True".

Resources