我目前正试图用Python编程解决一个难题,我希望自己能够解决它,但我发现很难描述这个问题,所以我可以通过在线资源寻求帮助。下面我将描述问题的性质,我们非常感谢您的帮助
因此,有一套4个彩色按钮,每个按钮都被分配一个功能,以循环方式改变一个或多个按钮的颜色。这些按钮的代码表示可能如下所示:
# 1 = green, 2 = red, 3 = blue, 4 = purple
# goes 1->4 then loops
cstate = [1,3,4,1] # current state of the numbers
按钮可以执行的四种不同功能是:
每个功能对每个按钮都是唯一的,因此不能为两个按钮分配相同的功能
我尝试表示这些函数是为了创建一个数组,描述通过单击每个按钮而受影响的按钮的索引,例如:
incArray =[[0,3],[0,1,3],[0,1,2,3],[3]]
接下来,我创建了一个函数,将按钮函数应用于上述cstate
数组:
def increment(currentState, whichClicked, whichEffects):
retArr = currentState
for click in whichClicked:
for change in whichEffects[click]:
if currentState[change] == 4:
retArr[change] = 1
else:
retArr[change] += 1
print(retArr)
return retArr
现在在这个特定的例子中,我给increment
函数添加了whichClicked = [2,2,2,1,0,3,3]
,因为我知道这是fstate = [2,3,3,4]
的正确组合(或最终状态)
我试图实现的是编写代码来生成上面描述的whichClicked
数组,给定cstate
和fstate
。提前感谢您提供的任何帮助
我倾向于开发这类算法,从一个“哑”暴力算法开始,然后进一步优化它
蛮力
您可以通过一种Breadth-first search algorithm以“暴力”的方式实现这一点,您只需:
大概是这样的:
首次优化
您将看到结果输出与您在示例中提供的“whichClicked”数组相同,但所有项都已排序。这是因为单击按钮的顺序不会影响最终结果。 您可以使用这些知识来优化算法,因为它正在评估大量冗余选项。(例如,路径[0,1]给出的结果与路径[1,0]相同)
因此,一个新的策略可能是在解决方案中排除这些冗余选项。如果在纸上绘制整个搜索图(或取消对
# print(new_path)
行的注释),您会看到以下代码仅在“排序”路径上迭代:正如您从输入中看到的,迭代次数已从7172减少到283
现在,首先要评估的路径是:
已编辑
二次优化
第二个优化可以是考虑存在“循环”路径:例如,在按下第四个按钮四次(路径[3,3,3,3])后,您将处于相同的状态。要考虑到这一点,一个简单的方法是保存一个已经遇到的状态列表。如果您再次处于这种状态,您可以忽略它,因为它不会提供更好的解决方案(通过此循环路径到达解决方案的路径总是更长):
如您所见,迭代次数现在只有182次。正如所料,该数字低于唯一状态的最大数量(4^4=256)
分析方法
假设这个问题的复杂性会大得多(例如更多的按钮和颜色),蛮力的方法可能不可行,你可以考虑一种更具分析性的方法,例如,计算每个按钮必须增加多少次(模4)。从开始状态转到结束状态,并找到满足所有按钮要求的按钮单击组合
相关问题 更多 >
编程相关推荐