假设我必须从0-10中选择一个数字。
我选择的数字是6。
我要选择的下一个号码是0。
现在规则是我必须将数字递增1或递减1,数字也可以包围最后一个数字。
现在最重要的是找到最短的方向。
所以
6-5-4-3-2-1-0 = 7 moves.
6-7-8-9-10-0 = 6 moves.
在这种情况下,增加胜利。
好吧,我想出了这段代码(可能坏了)
int movesInc = 1;
int movesDec = 1;
int curNumber = 6;
int nextNumber = 0;
while((curNumber-- % 11) != nextNumber)
movesDec++;
while((curNumber++ % 11) != nextNumber)
movesInc++;
现在而不是在两个方向上使用while循环..并找出哪个移动较少..
没有while循环的任何方法吗?可能只是某种数学方程?
答案 0 :(得分:3)
您的代码实际上无法正常工作,原因有两个:
你应该使用modulo 11而不是10(我看到你现在根据我之前的评论修正了这个。)
Java和C ++中的%
运算符不会以您的思维方式处理符号。
这确实有效,虽然它不漂亮,但它不需要循环。
它在6开始测试并在0结束,我希望它能正常工作。对于不同的范围,您当然需要在结果为负时更改添加的数字。
int curNumber = 6;
int nextNumber = 0;
int movesInc = (nextNumber - curNumber) + 1
+ ((nextNumber > curNumber)? 0: 11);
int movesDec = (curNumber - nextNumber) + 1
+ ((nextNumber < curNumber)? 0: 11);
这里的+ 1
是因为你在计算两个端点。三元表达式处理0左右。
答案 1 :(得分:1)
int curNumber;
int nextNumber;
//calculate the modulo size by the highest number
int module = 10 + 1;
//calculate the direct distance to the nextNumber
int directDist = nextNumber - curNumber;
int nextNumberWrapped;
//calculate the wrapped distance, deciding the direction which wraps
if(directDist < 0)
//wrapping in positive direction: 10 -> 0
nextNumberWrapped = nextNumber + module;
else
//wrapping in negative direction 0 -> 10
nextNumberWrapped = nextNumber - module;
//calculating the wrapped distance
int wrappedDist = nextNumberWrapped - curNumber;
//assume the directDist to be shortest
int shortestDist = directDist;
//proof wrong if neccessary (compare the distances absolute values)
if(abs(wrappedDist) < abs(directDist))
//save the signed distance
shortestDist = wrappedDist;
shortestDist的绝对值告诉你最短距离的长度,标志给你指示方向。 因此,当符号为负时,你必须减少,当它是正数时,你必须增加到最短路。
你的例子似乎也错了。每个 - 在数字之间是一步,让你比你计算的步骤少一步:
6-5-4-3-2-1-0
^ ^ ^ ^ ^ ^
1 2 3 4 5 6 -> 6 moves
6-7-8-9-10-0
^ ^ ^ ^ ^
1 2 3 4 5 -> 5 moves