仿真要求:
算法实现:
仿真程序:
import random
#考虑最终落到哪一个框框里面
#交互处理
#输入球的个数"""
#输入框的个数"""
class Ball():
"""docstring for Ball"""
def __init__(self, OrignalX):
"""描述球的属性"""
self.X = OrignalX
self.path = []
def getX(self):
return self.X
def getPath(self):
return self.path
#输入小球的数量
# ballNum = 9
# slot = 9
ballNum = input("Enter the number of balls to drop:")
slot = input("Enter the number of slots in the beam machine:")
ballNum = int(ballNum)
slot = int(slot)
floor = slot - 1
#创建球群
slotsNum = []
for zero in range(0,floor+1):
slotsNum.append(0)#槽的个数
randomL = []
for number in range(1,ballNum+1):#字典所对应的键,存储每个槽里面的小球个数,防止数组溢出
randomL.append(number)
slots={}
Balls = []
for i in range(0,ballNum):
Balls.append(Ball(0))
# Balls = [Ball(0,8),Ball(0,8),Ball(0,8)]
# Balls = [Ball(4,8),Ball(4,8),Ball(4,8)]
#模拟下落的过程
def down():
#一共是三个小球
for j in range(0,ballNum):
#每个小球下落八层
for i in range(0,floor):
direction = random.randint(0,1);
if direction == 0:#左转
#修改球的路径属性,将此属性写入ball类之中
Balls[j].path.append("L")
#修改ball的x坐标和y的坐标
Balls[j].X = Balls[j].X - 0.5
else: #右转
# path.append("R")
Balls[j].path.append("R")
#修改球的路径属性,将此属性写入ball类之中
Balls[j].X = Balls[j].X + 0.5
"""搞定了每个小球下落,x轴线的变化,路径的存储"""
# print(Balls[j].getX())
for ii in range(0,slot):
if floor % 2 == 1:#奇数个槽
if -(slot)/2+ii < Balls[j].X < 1-(slot)/2+ii: #ii槽
slotsNum[ii] += 1 #ii槽中小球的个数
slots.setdefault(randomL[ii],[]).append(j+1)#ii槽中存储的小球的序号
else: #偶数个槽
if -(floor/2+0.5) + ii < Balls[j].X < 1-(floor/2+0.5) + ii:
slotsNum[ii] += 1 #ii槽中小球的个数
slots.setdefault(randomL[ii],[]).append(j+1)#ii槽中存储的小球的序号
def printf():
for k in range(0,len(slotsNum)):
print("第"+str(k+1)+"个槽中有"+str(slotsNum[k])+"个Ball")
if slotsNum[k] != 0:
#如果这个槽的小求个数不为零,那么输出对应的小球序号以及路径
print(" 落入该槽球的序号和路径分别是:")
for j in range(0,slotsNum[k]):
# print(slots[k+1][j])
print(" "+str(slots[k+1][j])+"号球"+" and its path is "+str(Balls[slots[k+1][j]-1].getPath()))
down()
printf()