We have a matrix with dimensions n and n (n is an odd number and the user enters it) Write a program to simulate the spiral shape pattern in the matrix.
The pattern is such that starting from the central part of the matrix, whose value is equal to zero, 1 unit to the right and up (odd number) and then 2 We move the unit left and down (even number) and repeat this pattern n-1 times according to whether the number is even or odd. 0 to n-1 to be replaced according to the pattern)
6 6 6 6 6 6 5
6 4 4 4 4 3 5
6 4 2 2 1 3 5
6 4 2 0 1 3 5
6 4 2 3 3 3 5
6 4 5 5 5 5 5
6 7 7 7 7 7 7
First of all we get a number from user then assuming you have to draw the spiral out. Start by generating a list of the sequence (from the center to the end) , then write a function to put that list into the spiral
bellow link can explain it in more detail.
I change the directions of it's solution.
newbedev.com/creating-a-spiral-array-in-python
NORTH, S, W, E = (0, 1), (0, -1), (-1, 0), (1, 0) # directions
turn_left = {NORTH: E, E: S, S: W, W: NORTH} # old -> new direction
def spiral(width, height, matrixList):
if width < 1 or height < 1:
raise ValueError
x, y = width // 2, height // 2 # start near the center
dx, dy = NORTH # initial direction
matrix = [[None] * width for _ in range(height)]
count = 0
while True:
matrix[y][x] = matrixList[count] # visit
count += 1
# try to turn left
new_dx, new_dy = turn_left[dx, dy]
new_x, new_y = x + new_dx, y + new_dy
if (0 <= new_x < width and 0 <= new_y < height and
matrix[new_y][new_x] is None): # can turn left
x, y = new_x, new_y
dx, dy = new_dx, new_dy
else: # try to move straight
x, y = x + dx, y + dy
if not (0 <= x < width and 0 <= y < height):
return matrix # nowhere to go
def print_matrix(matrix):
width = len(str(max(el for row in matrix for el in row if el is not None)))
fmt = "{:0%dd}" % width
for row in matrix:
print(" ".join("_"*width if el is None else fmt.format(el)
for el in row))
n = int(input())
totalRecord = n*n
numberOfOccurance = 2
numberOfOccuranceIndex = 1
number = 1
index = 1
row = [0]
while index < totalRecord:
while numberOfOccuranceIndex <= numberOfOccurance:
row.append(number)
index += 1
numberOfOccuranceIndex += 1
if index >= totalRecord:
break
numberOfOccurance += 2
numberOfOccuranceIndex = 1
number += 1
print_matrix(spiral(n, n,row))
Related
y = topLeft.getY()
for i in range(5):
x = topLeft.getX()
for c in range(5):
cellButton = CellButton(window,x,y,size,cellID=(i,c))
self._buttons.append(cellButton)
x= x + (size+padding)
y = y + (size + padding)
#padding being space between each squares
I was expecting a 25 cell which is 5 by 5 with a space between them
We have shape with n angles and its coordinates. I need to divide that figure into 2 figures with the same area. Division is performed in parallel to the axis y. The task is to find such x-coordinate, which would comply with the terms.
Test,E.g
4 (n angles)
0 0
0 2
2 2
2 0
The output must be 1
I wrote
n = int(input())
coordinates = []
for i in range(n):
x,y = map(int,input().split())
coordinates.append([x,y])
s = 0
for i in range(len(coordinates)-1):
s += coordinates[i][0]*coordinates[i+1][1]
s -= coordinates[i][1]*coordinates[i+1][0]
s = s/2
x = 0
print(s)
And after that I don't have any ideas what to do next..
I am trying to create a maze generator using recursive division. I use this link:
Maze generation - recursive division (how it works?) as my guide as to how to approach the problem.
Here is my code so far:
import random
# Maze: 0 - N : 4 x 4 Grid
# Grid: 0 - (2n + 1) : 9 x 9 Array
# TODO: Now, Find a way to save the previous walls and not just only one at a time
rows = 9
cols = 9
start = 2
end = 7
# -------------------------------------------------------------------------------------
# Lists for all even / odd numbers in given range
evens = [n for n in range(start, end+1) if n % 2 == 0]
odds = [m for m in range(start, end+1) if m % 2 != 0]
# Generate random even/odd integer value for walls/ passages respectively
# Walls: Not sure if 2 variables are necessary-----------------------------------------
wallX = random.choice(evens)
wallY = random.choice(evens)
# Passages
passageX = random.choice(odds)
passageY = random.choice(odds)
#--------------------------------------------------------------------------------------
# Random direction: True = Horizontal Slice, False = Vertical Slice
randomDirection = random.choice([True, False])
arr = [['0' for i in range(cols)] for j in range(rows)]
def displayBoard(arr):
print()
for i in range(len(arr)):
for j in range(len(arr[i])):
# Print just the edges
if i == 0 or i == 8 or j == 0 or j == 8:
print('*', end = ' ')
# Print wall
elif arr[i][j] == 1:
print('.', end = ' ')
else:
print (' ', end = ' ')
print()
# Function choose direction to slice
def chooseDir(arr):
for i in range(len(arr)):
for j in range(len(arr[i])):
# Horizontal Direction Slice
if randomDirection:
arr[wallX][j] = 1
arr[wallX][passageY] = 2
print(arr[i][j], end = ' ')
# Vertical Slice
else:
arr[i][wallY] = 1
arr[passageX][wallY] = 2
print(arr[i][j], end = ' ')
print()
displayBoard(arr)
print()
mazeX = 0
mazeY = 0
# Write the recursive division function:
def divide():
chooseDir(arr)
print()
divide()
What this produces is a grid that is randomly sliced at an even index (creating walls) and creates passages at odd indices.
Output: 1 = wall, 2 = passage made
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 2 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0
* * * * * * * * *
* . *
* . *
* *
* . *
* . *
* . *
* . *
* * * * * * * * *
My issue is that I don't know how to write my recursive function. Do I call division on the two new cells created when a wall is made and continuously divide the "sub cells".
Or I know that a 4 x 4 cell grid will provide an array of 9 x 9 and I will have 16 cells total.
Then I can call division until a certain condition is met, increment to the next cell until all 16 were visited.
In both cases, I am not sure how to represent the new walls/cells created so that I can write the division function. Up until now, I've been using the grid coordinates.
You asked "Do I call division on the two new cells created when a wall is made and continuously divide the "sub cells"". Yes, that is the essence of recursion. Take a big problem and make smaller problem(s). Repeat with the smaller problems. Eventually, the problems are small enough to easily solve. Then put all the small problems back together to solve the original problem.
For the maze, the first wall split the maze into two smaller mazes. Use the same algorithm to split each of them and there are not 4 smaller mazes. Repeat until the sub-mazes are too small to split any more.
Your code that splits the maze should go in a function. If the sub-maze is big enough to split, the function splits the sub-maze and then calls itself on the two smaller sub-mazes.
Suppose I have a dataframe, df, consisting of a class of two objects, S, a set of co-ordinates associated with them, X and Y, and a value, V, that was measured there.
For example, the dataframe looks like this:
S X Y V
0 3 3 1
0 4 3 2
1 6 0 1
1 3 3 8
I would like to know the commands that allow me to group the X and Y coordinates associated with the class, S in a new binning. In this new picture, the new value of V should be the sum of the values in the bin for each class, S.
For example, suppose this co-ordinate system was initially binned between 0 and 10 in X and Y respectively. I would like to bin it between 0 and 2. This means:
Values from 0 < X <= 5, 0 < Y <= 5 in the old binning constitute the value 0;
Values from 6 < x <= 10, 6 < y <= 10 in the old binning constitute the value 1;
Edit:
For further example, considering Dataframe df:
Row 1 has X = 3 and Y = 3. Since 0 < X <= 5 and 0 < Y <= 5, this falls into bin (0,0)
Row 2 has X = 4 and Y = 3. Since 0 < X <= 5 and 0 < Y <= 5, this also falls into bin (0,0).
Since Row 1 and 2 are observed in the same bin and are of the same class S, they are added along column V. This gives a combined row, X=0, Y=0, V = 1+2 =3
Row 3 has has X = 6 and Y = 0. Since 6 < X <= 10 and 0 < Y <= 5, this falls into bin (1,0)
Row 4 has has X= 3 and Y = 3. Since 0 < X <= 5 and 0 < Y <= 5, this falls into bin (0,0). However, since the element is of class S=1, It is not added to anything, since we only add between shared classes.
The output should then be:
S X Y V
0 0 0 3
0 1 0 1
1 0 0 8
What commands must I use to achieve this?
This should do the trick:
data.loc[data['X'] <= 5, 'X'] = 0
data.loc[data['X'] > 5, 'X'] = 1
data.loc[data['Y'] <= 5, 'Y'] = 0
data.loc[data['Y'] > 5, 'Y'] = 1
data = data.groupby(['S', 'X', 'Y']).sum().reset_index()
For your example the output is:
S X Y V
0 0 0 0 3
1 1 0 0 8
2 1 1 0 1
I found this answer to be helpful.
I'm calculating Manhattan's distance for a N-Puzzle game. I've searched in all sites, but the proposed solution isn't good.
I'm trying this with this code:
def calculateManhattanDistance(matrix):
size = len(matrix)
manhattanDistanceSum = 0
for i in range(size):
for j in range(size):
value = matrix[i][j]
if(value != 0):
targetX = (value)/size
targetY = (value)%size
dx = i-targetX
dy = j-targetY
manhattanDistanceSum = manhattanDistanceSum + abs(dx)+ abs(dy)
The matrix'goal is:
0 1 2
3 4 5
6 7 8
If I try calculate the distance in the next matrix (the same to the goal):
0 1 2
3 4 5
6 7 8
The proposed solution is 3 :S But It must be 0
I'm using this page to calculate it: Manhattan distance but the solution isn't good for me.
Sorry for my regular english guys!