DhNR.n.e+]++.[\.sllN::.Bk\0\.\1\-\ b*]*\ +2sllNt/16lNNjmj*3\ d.t[h"ET"h"IANM"h"SURWDKGO"h"HVF L PJBXCYZQ
在线测试!
说明
简而言之,我在这里要做的是逐列生成表格,然后在打印之前转置表格。我们注意到,在一列中,字母莫尔斯电码可以表示为二进制字符串(替换.
用0
和-
通过1
)时,从零到列的最后一个字母的指数计算。
该算法依赖于一个函数,下面从中给出一个示例(第二列):
1. Takes "IANM" as input
2. Generates the binary representations of zero up to len("IANM"): ["0", "1", "10", "11"]
3. Replace with dots and hyphens: [".", "-", "-.", "--"]
4. Pad with dots up to floor(log2(len("IANM"))): ["..", ".-", "-.", "--"]
5. Add the corresponding letters: [".. I", ".- A", "-. N", "-- M"]
6. After each element, insert a list of 16 / len("IANM") - 1 (= 3) strings containing only spaces of length floor(log2(len("IANM"))) + 2 (= 4):
[".. I", [" ", " ", " "], ".- A", [" ", " ", " "], "-. N", [" ", " ", " "], "-- M", [" ", " ", " "]]
7. Flatten that list:
[".. I", " ", " ", " ", ".- A", " ", " ", " ", "-. N", " ", " ", " ", "-- M", " ", " ", " "]
8. That's it, we have our second column!
代码说明
我将代码切成两半。第一部分是上述功能,第二部分是我如何使用该功能:
DhNR.n.e+]++.[\.sllN::.Bk\0\.\1\-\ b*]*\ +2sllNt/16lNN
DhNR # Define a function h taking N returning the rest of the code. N will be a string
.e N # For each character b in N, let k be its index
.Bk # Convert k to binary
: \0\. # Replace zeros with dots (0 -> .)
: \1\- # Replace ones with hyphens (1 -> -)
.[\.sllN # Pad to the left with dots up to floor(log2(len(N))) which is the num of bits required to represent len(N) in binary
++ \ b # Append a space and b
] # Make a list containing only this string. At this point we have something like [". E"] or [".. I"] or ...
+ *]*\ +2sllNt/16lN # (1) Append as many strings of spaces as there are newlines separating each element vertically in the table
.n # At this point the for each is ended. Flatten the resulting list and return it
(1):在莫尔斯表中的第一列中,在每行之后包含字母(“ E”和“ T”)的七行。在第二栏中,是三行。然后是第一列(第三列),然后是零列(最后一列)。即16 / n - 1
,其中n
是在列字母数(这是N
在上面的代码中)。那第(1)行的代码是什么
:
*]*\ +2sllNt/16lN
sllN # Computes the num of bits required to represent len(N) in binary
+2 # To that, add two. We now have the length of a element of the current column
*\ # Make a string of spaces of that length (note the trailing space)
t/16lN # Computes 16 / len(N) - 1
*] # Make a list of that length with the string of spaces (something like [" ", " ", ...])
好了,现在我们有了一个很好的有用函数h
,该函数基本上是根据字符序列生成表的列的。让我们使用它(注意下面的代码中的两个尾随空格):
jmj*3\ d.t[h"ET"h"IANM"h"SURWDKGO"h"HVF L PJBXCYZQ
h"ET" # Generate the first column
h"IANM" # Generate the second column
h"SURWDKGO" # Generate the third column
h"HVF L PJBXCYZQ # Generate the last column (note the two trailing spaces)
[ # Make a list out of those columns
.t # Transpose, because we can print line by line, but not column by column
mj*3\ d # For each line, join the elements in that line on " " (that is, concatenate the elements of the lines but insert " " between each one)
j # Join all lines on newline
代码仍然可以缩短;也许以后再说。