我在看 this因为我正在尝试制作一个十五分谜解算器。我真的不明白它在说什么。我将如何检查给定的一组数字(从 0-15,存储在数组中,0 为空白)是否有效,因为“如果列表的排列符号是 +1,则该位置是可能的”。如果相关的话,我正在使用 javascript。
最佳答案
请考虑以下情况:如果您解决了一个 15 字谜题,并且将一对胶合板物理移除并交换并替换了 14 和 15 block ,然后打乱它...你能把它恢复到有效状态吗?
答案是否定的。在 15 拼图中,您可以执行的所有移动都保留了一个不变量,而排列符号可能指的是该不变量。
根据 http://en.wikipedia.org/wiki/Fifteen_puzzle :
The invariant is the parity of the permutation of all 16 squares (15 pieces plus empty square) plus the parity of the taxicab distance moved by the empty square.
This is an invariant because each move changes both the parity of the permutation and the parity of the taxicab distance. In particular if the empty square is not moved the permutation of the remaining pieces must be even.
要计算此奇偶校验,请查看 http://en.wikipedia.org/wiki/Parity_of_a_permutation (您也可以查看 Levi-Civita Symbol,但它有点神秘),在 python 中实现它,然后计算空方 block 从其起始位置移动的曼哈顿距离,并取这两个值之和的奇偶校验。
类似于:
#!/usr/bin/python3
from pprint import pprint
state_starting = list(range(1,16)) + [None]
START = state_starting
def positionIsPossible(state):
"""
state is a list, the starting position is [1,2,3,...,15,None]
"""
numInversions = sum(
state.index(START[j]) > state.index(START[i])
for i in range(16) for j in range(i) # each pair (i,j)
) #sum([True,True,False])==2
# Uncomment if you want to see what's going on here:
#pprint(list(
# ((i,j), (START[i],START[j]), state.index(START[j]) > state.index(START[i]))
# for i in range(15) for j in range(i)
#))
newEmptySquareYPos = state.index(None)//4
newEmptySquareXPos = state.index(None)%4
emptySquareMovedDistance = abs(3-newEmptySquareYPos)+abs(3-newEmptySquareXPos)
parity = (numInversions + emptySquareMovedDistance)%2
print('number of inversions:', numInversions)
print('distance empty square moved:', emptySquareMovedDistance)
print('parity:', parity)
return parity==0
以下是一些示例/测试用例:
def swap(state, i, j):
state = list(state)
state[i], state[j] = (state[j], state[i])
return state
def validate(state):
def formatState(state):
return '\n'.join('|'+' '.join([str(y if y else '').rjust(2) for y in x])+'|' for x in [state[0:4],state[4:8],state[8:12],state[12:16]])
print(formatState(state))
print(state, 'is', 'reachable' if positionIsPossible(state) else 'unreachable')
print()
# reachable
validate(state_starting)
validate(swap(state_starting, 15,14))
validate(swap(state_starting, 15,11))
# unreachable
validate(swap(state_starting, 14,13))
结果:
| 1 2 3 4|
| 5 6 7 8|
| 9 10 11 12|
|13 14 15 |
number of inversions: 0
distance empty square moved: 0
parity: 0
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, None] is reachable
| 1 2 3 4|
| 5 6 7 8|
| 9 10 11 12|
|13 14 15|
number of inversions: 1
distance empty square moved: 1
parity: 0
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, None, 15] is reachable
| 1 2 3 4|
| 5 6 7 8|
| 9 10 11 |
|13 14 15 12|
number of inversions: 7
distance empty square moved: 1
parity: 0
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, None, 13, 14, 15, 12] is reachable
| 1 2 3 4|
| 5 6 7 8|
| 9 10 11 12|
|13 15 14 |
number of inversions: 1
distance empty square moved: 0
parity: 1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 14, None] is unreachable
如果你的算法并不真正关心这个位置是否可能(你这样做只是为了说“无效输入!位置不可能!”你可以忽略这部分,无论如何运行它几百迭代,如果未解决则返回“不可能!”。
关于javascript - 查找排列反转的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5932756/
这是一道面试题,我没有答对,但还是很好奇怎么解。你有N个人的大家庭,分别是1,2,3,...,N岁。你想给你的大家庭拍张照片。所有的家庭成员都排成一排。“我是家里的friend,建议家庭成员安排如下:”1岁的家庭成员坐在这一排的最左边。每两个坐在一起的家庭成员的年龄相差不得超过2岁。输入:整数N,1≤N≤55。输出:摄影师可以拍摄的照片数量。示例->输入:4,输出:4符合条件的数组:[1,2,3,4][1,2,4,3][1,3,2,4][1,3,4,2]另一个例子:输入:5输出:6符合条件的数组:[1,2,3,4,5][1,2,3,5,4][1,2,4,3,5][1,2,4,5,3][
我有这样的哈希trial_hash={"key1"=>1000,"key2"=>34,"key3"=>500,"key4"=>500,"key5"=>500,"key6"=>500}我按值降序排列:my_hash=trial_hash.sort_by{|k,v|v}.reverse我现在是这样理解的:[["key1",1000],["key4",500],["key5",500],["key6",500],["key3",500],["key2",34]]但我希望当值相同时按键的升序排序。我该怎么做?例如:上面的散列将以这种方式排序:[["key1",1000],["key3",500
我刚刚被困在这个问题上一段时间了。以这个基地为例:moduleTopclassTestendmoduleFooendend稍后,我可以通过这样做在Foo中定义扩展Test的类:moduleTopmoduleFooclassSomeTest但是,如果我尝试通过使用::指定模块来最小化缩进:moduleTop::FooclassFailure这失败了:NameError:uninitializedconstantTop::Foo::Test这是一个错误,还是仅仅是Ruby解析变量名的方式的逻辑结果? 最佳答案 Isthisabug,or
我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s
Region是HBase数据管理的基本单位,region有一点像关系型数据的分区。region中存储这用户的真实数据,而为了管理这些数据,HBase使用了RegionSever来管理region。Region的结构hbaseregion的大小设置默认情况下,每个Table起初只有一个Region,随着数据的不断写入,Region会自动进行拆分。刚拆分时,两个子Region都位于当前的RegionServer,但处于负载均衡的考虑,HMaster有可能会将某个Region转移给其他的RegionServer。RegionSplit时机:当1个region中的某个Store下所有StoreFile
我有一个应用需要发送用户事件邀请。当用户邀请friend(用户)参加事件时,如果尚不存在将用户连接到该事件的新记录,则会创建该记录。我的模型由用户、事件和events_user组成。classEventdefinvite(user_id,*args)user_id.eachdo|u|e=EventsUser.find_or_create_by_event_id_and_user_id(self.id,u)e.save!endendend用法Event.first.invite([1,2,3])我不认为以上是完成我的任务的最有效方法。我设想了一种方法,例如Model.find_or_cr
我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的
我想找到给定字符串中的所有匹配项,包括重叠匹配项。我怎样才能实现它?#Example"a-b-c-d".???(/\w-\w/)#=>["a-b","b-c","c-d"]expected#Solutionwithoutoverlappedresults"a-b-c-d".scan(/\w-\w/)#=>["a-b","c-d"],but"b-c"ismissing 最佳答案 在积极的前瞻中使用捕获:"a-b-c-d".scan(/(?=(\w-\w))/).flatten#=>["a-b","b-c","c-d"]参见Rubyde
这应该是一个简单的问题,但我找不到任何相关信息。给定一个Ruby中的正则表达式,对于每个匹配项,我需要检索匹配的模式$1、$2,但我还需要匹配位置。我知道=~运算符为我提供了第一个匹配项的位置,而string.scan(/regex/)为我提供了所有匹配模式。如果可能,我需要在同一步骤中获得两个结果。 最佳答案 MatchDatastring.scan(regex)do$1#Patternatfirstposition$2#Patternatsecondposition$~.offset(1)#Startingandendingpo
我在关注RyanbatesRailsCast的devise和omniauth(第235集-devise-and-omniauth-revised)。当我尝试使用Twitter登录时,标题中不断出现错误。defself.new_with_session(params,session)ifsession["devise.user_attributes"]new(session["devise.user_attributes"],without_protection:true)do|user|user.attributes=paramsuser.valid?end完整跟踪:C:/Ruby20