数字螺旋是一个无限网格,其左上角的正方形具有数字1。这是螺旋的前五层:
您的任务是找出y行和x列中的数字。
例:
Input: 2 3
Out : 8
Input: 1 1
Out : 1
Input: 4 2
Out : 15
注意:
- 允许使用任何编程语言。
- 这是一个代码高尔夫挑战,因此最短的代码获胜。
- 祝你好运!
数字螺旋是一个无限网格,其左上角的正方形具有数字1。这是螺旋的前五层:
您的任务是找出y行和x列中的数字。
例:
Input: 2 3
Out : 8
Input: 1 1
Out : 1
Input: 4 2
Out : 15
注意:
Answers:
f(x,y,z){z=x>y?x:y;z=z*z-~(z%2?y-x:x-y)-z;}
螺旋具有多个“臂”:
12345
22345
33345
44445
55555
位置位于臂(分配给变量)上。然后,手臂上的最大数为,它在手臂的左下位置和右上位置之间交替。从减去得出沿臂移动的序列,因此我们根据选择适当的符号的奇偶性,按进行调整以获得从0开始的序列,然后从减去该值。ñ ñ 2 X ý - Ñ + 1 ,- Ñ + 2 ,... ,- 1 ,0 ,1 ,... ,Ñ - 1 ,ñ - 2 Ñ Ñ ñ - 1 ñ 2z
感谢Xcoder先生节省了一个字节。
f(x,y,z){z=x>y?x:y;z=z*z-~(z%2?x-y:y-x)-z;}
保存1个字节。
f(1, 1)
返回值1
。在页脚部分循环通过X = 1〜5且y = 1〜5,要求所有这样的值的功能,并打印输出中的网格,以证明函数是用于在问题中所示所有输入正确的。
def f(a,b):M=max(a,b);return(a-b)*(-1)**M+M*M-M+1
-4个字节,感谢@ChasBrown
-1个字节,感谢@Shaggy
第一次打高尔夫球!我不知道这不是最佳选择,但无论如何。
基本上以与@Doorknob C代码相同的原理运行。
def f(a,b):
方法节省4个字节,请参见此处。
M**2
可以将替换为M*M
。
X>ttq*QwoEqGd*+
编辑:与@Doorknob的答案相同的技术,只是得出了不同的结论。
螺旋线的对角元素之间的差是算术序列。项的总和为(通过通常的AP公式)。该总和加1,得到位置的对角线元素。
给定,我们找到这两者的最大值,这是该点所属的螺旋线的“层”。然后,我们发现该层的对角线值为。对于偶数层,值为,对于奇数层。
X> % Get the maximum of the input coordinates, say n
ttq* % Duplicate that and multiply by n-1
Q % Add 1 to that. This is the diagonal value v at layer n
wo % Bring the original n on top and check if it's odd (1 or 0)
Eq % Change 1 or 0 to 1 or -1
Gd % Push input (x, y) again, get y - x
* % Multiply by 1 or -1
% For odd layers, no change. For even layers, y-x becomes x-y
+ % Add that to the diagonal value v
% Implicit output
备用21字节解决方案:
Pdt|Gs+ttqq*4/QJb^b*+
在线尝试!
收集并打印为矩阵
从上面我们知道,我们想要的功能是
其中。
一些基本的计算将显示最大两个数的一个表达式是
插入另一个,我们发现另一种形式是:
其中。
这是解决方案实现的功能。
改编自Doorknob解决方案,解决了一些啤酒问题。
wV
nU²ÒNr"n-"gUv
:Implicit input of integers U=x and V=y
wV :Maximum of U & V
\n :Reassign to U
U² :U squared
Ò :-~
"n-" :Literal string
Uv :Is U divisible by 2? Return 0 or 1
g :Get the character in the string at that index
Nr :Reduce the array of inputs by that, where n is inverse subtraction (XnY = Y-X)
n :Subtract U from the result of the above
A~Qh.MZQh-+*-GH^_1Q*
Rushabh Mehta 的回答几乎是字面的翻译。
说明:A~Qh.MZQh-+*-GH^_1Q* | Full code
A~Qh.MZQh-+*-GH^_1Q*QQQ | Code with implicit variables filled
| Assign Q as the evaluated input (implicit)
A | Assign [G,H] as
~Q | Q, then assign Q as
h.MZQ | Q's maximal value.
| Print (implicit)
h-+*-GH^_1Q*QQQ | (G-H)*(-1)^Q+Q*Q-Q+1
ZÐ<*>ŠGR}¥+
-1个字节,感谢@Emigna更改Èi
为G
。
@sundar的MATL答案端口,因此请确保支持他!
说明:
Z # Get the maximum of the (implicit) input-coordinate
# i.e. [4,5] → 5
Ð # Triplicate this maximum
< # Decrease it by 1
# i.e. 5 - 1 → 4
* # Multiply it
# i.e. 5 * 4 → 20
> # Increase it by 1
# i.e. 20 + 1 → 21
Š # Triple swap the top threes values on the stack (a,b,c to c,a,b)
# i.e. [4,5], 5, 21 → 21, [4,5], 5
G } # Loop n amount of times
R # Reverse the input-coordinate each iteration
# i.e. 5 and [4,5] → [5,4]→[4,5]→[5,4]→[4,5] → [5,4]
¥ # Calculate the delta of the coordinate
# [5,4] → [1]
+ # And add it to the earlier calculate value (output the result implicitly)
# 21 + [1] → [22]
Èi
可能是G
。