我正在使用python创建DS算法,但我相信我无法正确填充Matrix。我在每个其他索引中得到0。我的代码如下,之后提供了一个示例输出。我用它来生成地形数据。通过查看其他示例,我认为我的指数应该更接近而不是从(20,-8)跳跃
import random
class DiamondSq:
def __init__(self, k):
self.size = (2 ** k) + 1
self.max = self.size - 1
self.r = 1
self.grid = self.createGrid(self.size)
self.diamondSquareAlgorithm(self.max)
def diamondSquareAlgorithm(self, size):
x = size / 2
y = size / 2
halfStep = size / 2
scale = self.r * size
if (half < 1):
return None
# Squares
for y in range(halfStep, self.max, size):
for x in range(halfStep, self.max, size):
s_scale = random.uniform(0, 1) * scale * 2 - scale
self.squareStep(x, y, halfStep, s_scale)
# Diamonds
for y in range(0, self.max, halfStep):
for x in range((y + halfStep) % size, self.max, size):
d_scale = random.uniform(0, 1) * scale * 2 - scale
self.diamondStep(x, y, halfStep, d_scale)
self.diamondSquareAlgorithm(size / 2)
def squareStep(self, x, y, size, scale):
topLeft = self.grid[x - size][y - size]
topRight = self.grid[x + size][y - size]
botLeft = self.grid[x + size][y + size]
botRight = self.grid[x - size][y + size]
average = ((topLeft + topRight + botLeft + botRight) / 4)
self.grid[x][y] = average + scale
def diamondStep(self, x, y, size, scale):
top = self.grid[x][y - size]
right = self.grid[x + size][y]
bottom = self.grid[x][y + size]
left = self.grid[x - size][y + size]
average = ((top + right + bottom + left) / 4)
self.grid[x][y] = average + scale
def createGrid(self, size):
grid = [[-1 for x in range(size)] for y in range(size)]
grid[0][0] = random.randint(50,70) #self.max
grid[self.max][0] = random.randint(50,70) #self.max / 2
grid[self.max][self.max] = random.randint(50,70) # 0
grid[0][self.max] = random.randint(50,70) #self.max / 2
for index, i in enumerate(grid):
for index2, b in enumerate(i):
result = '{0:.3g}'.format(list1[index][index2]*100)
print str(result),
print()
return grid
def getGrid(self):
return self.grid
输出
-3.5 0 0.692 0 1.03 0 0.818 0 -4.56 ()
0 12.4 0 19.6 0 17.2 0 18.9 0
-4.84 0 1.69 0 -3.46 0 -1.86 0 -7.43 ()
0 25.7 0 18.7 0 20.8 0 22.3 0
2.41 0 -4.43 0 -8.42 0 6.36 0 -0.151 ()
0 23.4 0 29.5 0 26.7 0 23.6 0
-0.0232 0 8.08 0 5.07 0 -7.31 0 5.78
0 16.7 0 25.4 0 21.5 0 14.9 0
-5.65 0 -7.61 0 -5.09 0 0.282 0 2.49