What is Alpha beta pruning? How to draw game Values From State? - artificial-intelligence

Hexapawn is a simple turn based game played on a 3 × 3 board. Each player
begins with 3 pawns - WHITE (MAX) in the bottom row and BLACK (MIN) in the top row.
Pawns can move as normal in chess (i.e. white pawns can move up one square or can capture a black pawn diagonally up one square, and black pawns can move down one square or can capture a white pawn diagonally down one square). The goal of each player is to either get one of their pawns to the other end of the board, or to make it such that their opponent is stuck on their next move. Figure 1 shows the initial state of the game.
pseudo-code:
rows = 3;
cols = 3;
scale = 1;
for row in range(rows):
for col in range(cols):
createSquare(origin=(row*scale, col*scale), end=((row+1)*scale, (col+1)*scale))
if row == 0:
createBlackPawn(origin=(row*scale, col*scale), end=((row+1)*scale, (col+1)*scale))
elif row == 2:
createWhitePawn(origin=(row*scale, col*scale), end=((row+1)*scale, (col+1)*scale))
Show the value of the game from the state using Alpha-Beta pruning. Mark any branches that will be pruned, and show what the bounds on the payoffs are for each player at each state not pruned.
From This state of game

Related

Efficient approach or algorithm to search all rectangle that cover a point on Cartesian coordinate system?

I have a set of data which contains a list of array. Each array contains 4 value of coordinates which forms a rectangle.
i.e. the start and end point(Xs, Xe) on X-axis; and the start and end point(Ys, Ye) on y-axis.
Xs|Xe|Ys|Ye
--------------
[[10,15,5,8],
[9,12,5,8],
[1,20,1,20]]
, for example.
And now I had a point(x,y).
To get all the rectangles that will cover the point, I simply loop through all array and compare one by one.
related_rectangles = []
for rectangle in dataset:
if x > rectangle[0] and x < rectangle[1] and y > rectangle[2] and y < rectangle[3]:
related_rectangles.append(rectangle)
The complexity should be O(n).
The question is, is there any algorithm or data structure that could reduce the complexity of searching? Especially for the case that all rectangles are squares.
Thanks.

How do I get an evaluation function from this Alpha Beta Pruning exercise?

I have an alpha beta pruning exercise that states the following (dots and boxes):
Next, a strategy game is described:
Starting with an empty grid of dots, players (A and B) take turns, adding a single horizontal or vertical line between two unjoined adjacent dots.
A player who completes the fourth side of a 1×1 box earns one point and takes another turn.
The game ends when no more lines can be placed. The winner of the game is the player with the most
points.
The question is:
How do I Define an ​evaluation function​ to be used by the algorithm? Assume that ​MAX ​plays with color ​player A
A guiding photo
First thing you should do is to have the coordinates x,y of each point ( (0,0) (0,1) (0,2) ; (1,0) (1,1) (1,2) ; (2,0) (2,1) (2,2) )
Each player will have a list of the points that he linked with a bar , then the evaluation will be in that way , you will see all the linked points , for each point with a coordinates (a,b) you will see if there is 3 points with following conditions { (a,b) (a,b+1) (a+1,b) (a+1,b+1) } , if yes then a cube is created
Example :
The player MAX , created a link between (0,0) and (0,1) , between (0,0) and (1,0) , between (1,0) and (1,1) and between (0,1) and (1,1 ) , then all these points will be added to his list
Now let's take one point (0,0) and make the evaluation , for all elements in the list , if there exist 3 elements which satisfies the 3 conditions { (a,b+1) (a+1,b) (a+1,b+1) } then we can say that there is a created cube

A.I.: Find the princess in as few steps as possible

I'm doing an Artificial Intelligence track at HackerRank and this is the first time I do this kind of programs.
On the first program, https://www.hackerrank.com/challenges/saveprincess/problem, I have to do the following:
Princess Peach is trapped in one of the four corners of a square grid.
You are in the center of the grid and can move one step at a time in
any of the four directions. Can you rescue the princess?
Input format
The first line contains an odd integer N (3 <= N < 100) denoting the
size of the grid. This is followed by an NxN grid. Each cell is
denoted by '-' (ascii value: 45). The bot position is denoted by 'm'
and the princess position is denoted by 'p'.
Grid is indexed using Matrix Convention
Output format
Print out the moves you will take to rescue the princess in one go.
The moves must be separated by '\n', a newline. The valid moves are
LEFT or RIGHT or UP or DOWN.
What should I do in these kind of problems?
Move to one corner and check if the princess is there, and it is not, move to another corner?
Here the goal is to do it in as few steps as possible but I think that will only happen if I'm lucky and I find the princess in the first corner to which I move.
I have thought that I could check if the princess is the corner I'm moving to before move to it, but I don't know if it is allowed in this problem.
Read the description of the input format (emphasis mine):
This is followed by an NxN grid. Each cell is denoted by '-' (ascii value: 45). The bot position is denoted by 'm' and the princess position is denoted by 'p'.
You do not have to actually go to each corner to see whether the princess is there, you already know where she is! Just determine the difference in position of the cells containing the bot m and the princess p and print the accordant movements. E.g., if the difference is 2 in x and -1 and y direction, you might go right right up.
What a boring problem... Seriously.
Load in the input data, starting with the grid size.
Accept lines of input corresponding to the grid size.
Since you know that the grid is a square, check the corners and move diagonally corresponding to what corner the princess is in.
Solution in 7 lines of python:
gridsize = int(input('Enter number of rows: '))
grid = [ input('Enter row: ') for r in range(gridsize) ]
move_dist = (gridsize-1)//2
if grid[ 0][ 0] == 'p': print('\n'.join([ 'UP\nLEFT'] * move_dist))
elif grid[ 0][-1] == 'p': print('\n'.join([ 'UP\nRIGHT'] * move_dist))
elif grid[-1][ 0] == 'p': print('\n'.join([ 'DOWN\nLEFT'] * move_dist))
elif grid[-1][-1] == 'p': print('\n'.join(['DOWN\nRIGHT'] * move_dist))

Infinite loop by creating arrays to swap node positions

There are 20 red balls sitting in 20 positions on 4 shelves. I'd like to move each ball to a new position on its own shelf by generating a new array that contains the new positions for all 20 balls. I am using a function (below) that allows me to do this. However, I find that this function keeps crashing; when I print out values it is generating, it seems to hang at the last coordinate of available position but then doesn't exit the "while" loop.
func generateNewLocationArray(previous: [String: CGPoint]) -> [String : CGPoint] {
var refreshedLocations = [String : CGPoint]()
for (location, _) in previous {
let node = fgNode.childNode(withName: location) as? LocationNode
var newLocation = generateRandomLocation(check: refreshedLocations)
let previousLocation = previous[(node?.name!)!]
while (newLocation == previousLocation) || (newLocation.y != previousLocation?.y) {
newLocation = generateRandomLocation(check: refreshedLocations)
}
node?.position = newLocation
refreshedLocations[location] = newLocation
}
return refreshedLocations
}
What I'm trying to achieve:
The function takes in an array of CGPoints, this is the "previous"
array, of positions where all the balls were.
It then creates a brand-new array, called "refreshedLocations".
It loads an existing node, which is located at a position contained in the previous array.
It then generates a new position for that node. This position is obtained from a pre-set array of 20 positions. This new location cannot be the same position the node is currently in; nor can it have a different y-coordinate (so the balls stay on the shelf).
Until this criteria is met, it keeps generating a new position.
It then loads this position into the refreshedLocations array, and the next node is also checked against this array to ensure there are no repeated positions.
The problem again: this code works with 10, or 15 balls. But when the number is pushed to 20, it seems more likely to hang. It will identify how to move all the balls around to new positions, but it gets stuck in the "while" loop more often than not. What's going wrong here?
EDIT: This is the function which returns a random location, but first checks whether the array that is being generated already contains the point being added.
func generateRandomLocation(check: [String : CGPoint]) -> CGPoint {
let randomIndex = GKRandomDistribution(lowestValue: 0, highestValue: allPositions.count - 1)
var position = allPositions[randomIndex.nextInt()]
while check.values.contains(position) {
position = allPositions[randomIndex.nextInt()]
}
return position
}
As far as I can see,
while (newLocation == previousLocation) || (newLocation.y != previousLocation?.y)
is always going to be true if you get to the last ball on a row and the only position left is the one it is already in. You can fix it by detecting how many positions on the shelf have been filled and if it is n - 1 out of n and the only position left is the one the ball is in, just swap it with a randomly selected other ball on the same shelf.
However, there must be a better way of doing this. I'd try a modified Fisher Yates shuffle.
Firstly, organise the balls by shelf and position. Then, for each shelf of n balls (numbered 0 to n - 1)
select a random ball from the first n - 2 balls and swap it with ball n - 1
select a random ball from the first n - 3 balls and swap it with ball n - 2
select a random ball from the first n - 4 balls and swap it with ball n - 3
and so on. Stop when the random selection would be from 0 balls. At the end of this process, all the balls will have changed position.
Repeat for each shelf.

How to calculate distance between 2 points in a 2D matrix

I am both new to this website and new to C. I need a program to find the average 'jumps' it takes from all points.
The idea is this: Find "jump" distance from 1 to 2, 1 to 3, 1 to 4 ... 1 to 9, or find 2 to 1, 2 to 3, 2 to 4 2 to 5 etc.
Doing them on the first row is simple, just (2-1) or (3-1) and you get the correct number. But if I want to find the distance between 1 and 4 or 1 to 8 then I have absolutely no idea.
The dimensions of the matrix should potentially be changeable. But I just want help with a 3x3 matrix.
Anyone could show me how to find it?
Jump means vertical or horizontal move from one point to another. from 1 to 2 = 1, from 1 to 9 = 4 (shortest path only)
The definition of "distance" on this kind of problems is always tricky.
Imagine that the points are marks on a field, and you can freely walk all over it. Then, you could take any path from one point to the other. The shortest route then would be a straight line; its length would be the length of the vector that joins the points, which happens to be the difference vector among two points' positions. This length can be computed with the help of Pythagora's theorem: dist = sqrt((x2-x1)^2 + (y2-y1)^2). This is known as the Euclidian distance between the points.
Now imagine that you are in a city, and each point is a building. You can't walk over a building, so the only options are to go either up/down or left/right. Then, the shortest distance is given by the sum of the components of the difference vector; which is the mathematical way of saying that "go down 2 blocks and then one block to the left" means walking 3 blocks' distance: dist = abs(x2-x1) + abs(y2-y1). This is known as the Manhattan distance between the points.
In your problem, however, it looks like the only possible move is to jump to an adjacent point, in a single step, diagonals allowed. Then the problem gets a bit trickier, because the path is very irregular. You need some Graph Theory here, very useful when modeling problems with linked elements, or "nodes". Each point would be a node, connected to their neighbors, and the problem would be to find the shortest path to another given point. If jumps had different weights (for instance, is jumping in diagonal was harder), an easy way to solve this is would be with the Dijkstra's Algorithm; more details on implementation at Wikipedia.
If the cost is always the same, then the problem is reduced to counting the number of jumps in a Breadth-First Search of the destination point from the source.
Let's define the 'jump' distance : "the number of hops required to reach from Point A [Ax,Ay] to Point B [Bx,By]."
Now there can be two ways in which the hops are allowed :
Horizontally/VerticallyIn this case, you can go up/down or left/right. As you have to travel X axis and Y axis independently, your ans is:jumpDistance = abs(Bx - Ax) + abs(By - Ay);
Horizontally/Vertically and also Diagonally
In this case, you can go up/down or left/right and diagonally as well. How it differs from Case 1 is that now you have the ability to change your X axis and Y axis together at the cost of only one jump . Your answer now is:jumpDistance = Max(abs(Bx - Ax),abs(By - Ay));
What is the definition of "jump-distance" ?
If you mean how many jumps a man needs to go from square M to N, if he can only jumps vertically and horizontally, one possibility can:
dist = abs(x2 - x1) + abs(y2 - y1);
For example jump-distance between 1 and 9 is: |3-1|+|3-1| = 4
There are two ways to calculate jump distance.
1) when only horizontal and vertical movements are allowed, in that case all you need to do is form a rectangle in between the two points and calculate the length of two adjacent side. Like if you want to move from 1 to 9 then first move from 1 to 3 and then move from 3 to 9. (Convert it to code)
2) when movements in all eight directions are allowed, things get tricky. Like if you want to move from 1 to 6 suppose. What you'll need to do is you'll have to more from 1 to 5. And then from 5 to 6. The way of doing it in code is to find the maximum in between the difference in x and y coordinates. In this example, in x coordinate, difference is 2 (3-1) and in y coordinate, difference is 1 (2-1). So the maximum of this is 2. So here's the answer. (Convert to code)

Resources