Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I'm stuck with a quite complex problem:
On an MxN field containing a chicken, an eagle and a yard,
the chicken tries to escape the eagle (by entering the yard),
and the eagle tries to catch the chicken. The chicken escapes
when reaches inside the yard, and the eagle catches the chicken
when it's in the same position as the chicken. In a single step,
the eagle can move one or two small squares, and the chicken can
move a single square in any direction. The program should display
a message saying if the chicken can win. It should compute the moves,
and, at each step, it should write in the output file the current
configuration of the field, and it should also visually represent
it on the screen. The dimensions of the field, position of the chicken
and of the eagle, and also of the yard, are given in a file.
I've solved the part with creating the field (a matrix), but I can't figure it out how to solve this. Perhaps backtracking would be an idea, but it's very complicated, and I can't handle it. I think I should find a way to find out the distance between the chicken and the yard, also between the eagle and the yard, and work somehow with that. It has to be in C. Any suggestion, idea is welcomed!
Thank you in advance!
It is an interesting problem. Let's go over the rules again. Players
Chicken: takes shortest path to field (there could be multiple shortest paths) and away from eagle (maximise the distance between itself and eagle among shortest paths).
Eagle: takes shortest path to chicken
To solve the problem we have to assume it is played in turns: first chicken then eagle and so on.
Game is over when :
Eagle is on chicken.
Chicken is on field.
Here is the trick for the distance:
Update
The distance you want is called Chebyshev distance. You can easily calculate it:
distance = max of(difference of corresponding coordinates between the two points)
For (1,1) and (2,3) distance = max(|1-2|,|2-3|) = 2
For (2,3) and (4,7) distance = 4
For (4,5,6) and (1,1,1) distance = 5
You can ignore the older answer if you want.
Old
distance = Manhattan distance - length of longest 45 deg diagonal
Manhattan distance is easy to understand. See its wiki. Take some examples :
---/F
--/-|
-/--|
C---X
manhattan distance = 7
length of max diagonal = 3
distance = 7-3 = 4
Another one
---/-F
--/--|
-/---|
C----X
distance = 8-3 = 5
Caveat: Remember there can be many shortest possible paths. For eg.
---F
--/F
-/-F
C--F
-\-F
--\F
---F
Lots of places to go in 3 moves. Pick one which is farthest from eagle using distance calculator.
Also if distance between eagle and chicken is less than chicken and field at any time then eagle wins else chicken. Just simulate the moves and you will know.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a 3d box random in space and know the nodes of it. A ray is intersecting this box. I would like to know the length of this intersection and have no idea how to code this in C or describing it mathematically.
This can be broken down into 3 parts:
a) Use "formula for intersection between line and plane" to determine if/where ray hits each plane; where each plane is determined from 3 vertices of the box (from each face of the box)
b) Determine if the intersection point for each plane (if any) is inside or outside the corresponding face of the box. For this I'd flatten everything to 2D (e.g. discard x, y or z for the plane's vertices and its intersection point, depending on which part of the plane's surface normal is largest); then pick a direction (e.g. "towards +x") and see if a line (in 2D space) from the intersection point heading in the chosen direction hits one edge of the face (and not zero edges or 2 edges). From this you get a list of intersections with faces of the box.
c) Find the closest "intersections with faces of box". This is mostly just a simplified Pythagoras thing ("distance_squared = distance_x * distance_x + distance_y * distance_y + distance_z * distance_z") with some "if(distance_squared < best_distance_squared_seen_so_far)".
Note 1: This method works for arbitrary objects/meshes with any number of faces (not just boxes); however if you wanted to support concave polygons (for faces) you'd need to determine if (after flattening to 2D) a line from the intersection point heading in a chosen direction hits an odd number of edges (and not just one edge).
Note 2: There's a tricky case where (after flattening to 2D) a line from the intersection point heading in a chosen direction hits a vertex perfectly. In this case you need to determine if it hits an edge or misses both edges by determining if both edges leading from the vertex are on the same side of your line. I don't think you need to care about this case for boxes (and can assume "hits vertex = hits an edge") but would need to care about it for arbitrary objects/meshes.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Suppose you have two strings. Each string has lines, seperated by a newline character. Now you want to compare both strings and then find the best method (shortest number of steps) by only adding or deleting lines of one string, to transform the second string in to the first string.
i.e.
string #2:
abc
def
efg
hello
123
and string #1:
abc
def
efg
adc
123
The best (shortest steps) solution to transform string #2 in to string #1 would be:
remove line at line position 3 ('hello')
add 'abc' after line
position 3
How would one write a generic algorithm to find the quickest, least steps, solutions for transforming one string to another, given that you can only add or remove lines?
This is a classic problem.
For a given set of allowed operations the edit distance between two strings is the minimal number of operations required to transform one into the other.
When the set of allowed operations consists of insertion and deletion only, it is known as the longest common subsequence edit distance.
You'll find everything you need to compute this distance in Longest common subsequence problem.
Note that to answer this question fully, one would have to thoroughly cover the huge subject of graph similarity search / graph edit distance, which I will not do here. I will, however, point you in directions where you can study the problem more thoroughly on your own.
... to find the quickest, least steps, solutions for transforming
one string to another ...
This is a quite common problem known as the (minimum) edit distance problem (or, originally, the specific 'The String-to-String Correction problem', by R. Wagner and M. Fischer), which is a non-trivial problem for the optimal (minimum = least steps) edit distance, which is what you ask for in your question.
See e.g.:
https://en.wikipedia.org/wiki/Edit_distance
https://web.stanford.edu/class/cs124/lec/med.pdf
The minimum edit distance problem for string similarity is in itself a subclass of the more general minimum graph edit distance problem, or graph similarity search (since any string or even sequenced object, as you have noted yourself, can be represented as a graph), see e.g. A survey on graph edit distance.
For details regarding this problem here on SO, refer to e.g. Edit Distance Algorithm and Faster edit distance algorithm.
This should get you started.
I'd tag this problem rather as a math problem (algorithmic instructions) rather than language specific problems, unless someone could guide you to an existing language (C) library for solving edit distance problems.
The fastest way would be to remove all sub-strings, then append (not insert) all new sub-strings; and to do "all sub-strings at once" if you can (possibly leading to a destPointer = sourcePointer approach).
The overhead of minimising the amount of sub-strings removed and inserted will be higher than removing and inserting/appending without checking if its necessary. It's like spending $100 to pay a consultant to determine if you should spend $5.
The following problem is an exam exercise I found from an Artificial Intelligence course.
"Suggest a heuristic mechanism that allows this problem to be solved, using the Hill-Climbing algorithm. (S=Start point, F=Final point/goal). No diagonal movement is allowed."
Since it's obvious that Manhattan Distance or Euclidean Distance will send the robot at (3,4) and no backtracking is allowed, what is a possible solution (heuristic mechanism) to this problem?
EDIT: To make the problem clearer, I've marked some of the Manhattan distances on the board:
It would be obvious that, using Manhattan distance, the robot's next move would be at (3,4) since it has a heuristic value of 2 - HC will choose that and get stuck forever. The aim is try and never go that path by finding the proper heuristic algorithm.
I thought of the obstructions as being hot, and that heat rises. I make the net cost of a cell the sum of the Manhattan metric distance to F plus a heat-penalty. Thus there is an attractive force drawing the robot towards F as well as a repelling force which forces it away from the obstructions.
There are two types of heat penalties:
1) It is very bad to touch an obstruction. Look at the 2 or 3 cells neighboring cells in the row immediately below a given cell. Add 15 for every obstruction cell which is directly below the given cell and 10 for every diagonal neighbor which is directly below
2) For cells not in direct contact with the instructions -- the heat is more diffuse. I calculate it as 6 times the average number of obstruction blocks below the cell both in its column and in its neighboring columns.
The following shows the result of combining this all, as well as the path taken from S to F:
A crucial point it the way that the averaging causes the robot to turn left rather than right when it hits the top row. The unheated columns towards the left make that the cooler direction. It is interesting to note how all cells (with the possible exception of the two at the upper-right corner) are drawn to F by this heuristic.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i need some help with a math task our professor gave us. Any suggestions would help.
The problem is:
There are N cannibals and M missinaries. All missionaries have a strenght attribute, which can be 1 or any positive whole number. Strenght indicates how many cannibals he can fight off.
Basically: there are two sides of the river, there is a 2-slot boat, and you have to transfer all the guys to the other side, without letting the cannibals eat the missionaries.
How would you write a program for this? What would be the transferring-grouping algorythm?
Thanks in anticipation,
Mark.
Model your problem as a states graph.
In here, a state is ({L,R}n,{L,R}m,{L,R}) Where:
First n entries: one for each missionary - where he is: left/right bank of the river
next,m entries: one for each canibal- where he is: left/right bank of the river
Last entry is for the boat
These are your vertices - you should also trim the invalid states - where strength of missionaries is not enough in one (or more) side. It is easy to calculate it for each state.
Your edges are:
E = { (S1,S2) | Can move in one boat ride from S1 to S2 }
All is left to do - use some shortest path algorithm to find the shortest path from: (L,L,....,L) to (R,R,...,R).
You can use BFS for this task, or even bi-directional search - or an informed algorithm (with admissible heuristic) such as A* Algorithm.
PS. The 'graph' is just conceptual, in practice you will have a function next:S->2^S, that given a state - returns all valid successors of this state (states that you can get to them using one edge on the graph from S). This will allow you to "generate the graph" on the fly.
Your next(S) function should be something like (high level pseudo code, without optimizations):
next(S):
let x be the bank where the boat is, and y the other bank
for each person p1 on bank x:
S' = S where boat and p1 moved from x to y
if S' is valid according to strength limitations, yield S'
for each p2 != p1 on bank x:
S' = S where boat and p1 and p2 moved from x to y
if S' is valid according to strength limitations, yield S'
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to play Tic-tac-toe using an artificial neural network. My configuration for the network is as follows:
For each of the 9 fields, I use 2 input neuron. So I have 18 input neurons, of course. For every field, I have 1 input neuron for a piece of Player 1 and 1 neuron for a piece of Player 2. In addition to that, I have 1 output neuron which gives an evaluation of the current board position. The higher the output value is, the better is the position for Player 1. The lower it is, the better is it for Player 2.
But my problem is: How could I code that neural network? My idea was to use an Array[1-18] for the input neurons. The values of this array are the input weights. The I would walk through the array using a loop. Whenever there is a neuron to be activated, I add the weight to the output value. So the output value is the sum of the weights of the activated input neurons:
Output = SUM(ActivatedInputNeurons)
Do you think this is a good way of programming the network? Do you have better ideas?
I hope you can help me. Thanks in advance!
Well, you have an input layer of 18 neurons, and an output layer of 1 neuron. That's OK. However, you need to give your neural net the opportunity to put the inputs into relation. For that, you need at least one intermediate layer. I would propose to use 9 neurons in the intermediate layer. Each of these should be connected to each input neuron, and the output neuron should be connected to each intermediate. Each such connection has a weight, and each neuron has an activation level.
Then, you go through all neurons, a layer at a time. The input layer is just activated with the board state. For all further neurons, you go through all its respective connections and sum over the product of the connected neuron's activation level and the weight of the connection. Finally, you calculate the activation level by applying a sigmoid function on this sum.
This is the working principle. Now, you need to train this net to get better results. There are several algorithms for this, you will have to do some googling and reading. Finally, you might want to adjust the number of neurons and layers when the results don't get convincing fast enough. For example, you could reduce the input layer to 9 neurons and activate them with +1 for an X and -1 for an O. Perhaps adding another intermediate layer yields better results, or increasing the number of neurons of a layer.
I don't particularly understand how you expect to get a meaningful summary of the board situation out of one output neuron. I would more look at having:
I I I O O O
I I I x O O O
I I I O O O
9 input neurons 9 output neurons
in a fully connected network, i.e. 81 weights. Then train the output neurons for the relative desirability of playing in that position.
Have a look at my Tic project. I've solved this problem with both neural network and genetic algorithm. The source code is freely available.
http://www.roncemer.com/tic-tac-toe-an-experiment-in-machine-learning
I think you should implement a 'traditional' feed-forward ANN using transfer functions, as that allows you to train it using back-propagation. The code for these usually ends up being a few lines of code, something like this:
SetupInputs();
for (l = 1 .. layers.count)
for (i = 0 .. layers[l].count)
sum = 0
for (j = 0 .. layers[l-1].count)
sum += layers[l-1][j] * weights[l-1][j]
layers[l][i] = TransferFunction(sum)
This is an excellent starter project for AI coding, but coming up with a complete solution will be way to big of an answer for SO.
As with most software, I recommend using an object-oriented design. For example: Define a Neuron class which has inputs, weights, and an output function. Then, create several of these Neuron objects in order to build your network.
See the wikipedia article on artificial neural networks for a good starting point.
Good luck with the code! Sounds like a lot of fun.
It is not a direct answer to your question, but you should have a look at the following framework/tool: SNNS or its Java counterpart JavaNNS. I'm pretty sure that there you'll find an answer to your question.
After adding the weights, you need to normalize the sum using a function, people usually use TANH, if you want to allow negative numbers.
edit:
Here is a java multilayer perceptron implementation that i worked on a few years ago. this one was used for checkers, but with less inputs you can use it for checkers too.
Also, you need to probably figure out a way to teach it to win, but thats another problem
You will save time if you use neural network library like FANN or Neuroph.
One way to encode your input is by 9 input neurons. The output is also good to be 9 neurons. What I do not see in the other replays is the size of the hidden layer. I suppose you are going to use MLP with traditional 3 layers. The size of the hidden layer is always mystery. I would try 10 hidden neurons.
If the transfer function is sigmoid you can encode input as follows:
0.0 - O player.
1.0 - X player.
0.5 - Empty.
The output of the ANN will be 9 real numbers. In this case some of the cells will be occupied already. You can search for the highest output value which corresponds to an empty cell.