我听说过,如果将代码反向缩进,代码可以运行得更快,这样编译器就可以像树设计模式一样从“分支”顶部向下处理它。这很有帮助,因为重力会加快编译代码所需的时间,并且提高了数据结构的效率。这里有一个例子,在Java脚本中:
function fib(n) {
var a = 1, b = 1;
while (--n > 0) {
var tmp = a;
a = b;
b += tmp;
if (a === Infinity) {
return "Error!";
}
}
return a;
}但是由于某种原因,记事本没有自动完成这个任务的设置,所以我需要一个程序来完成它。
提交必须以代码片段作为输入,反转缩进,并输出结果代码。
这是通过以下程序完成的:
输入和输出可以随时提供(STDIN/STDOUT、函数参数/返回值等);如果您的语言不支持多行输入(或者您只是不想这样做),您可以使用|字符来分隔行。
输入将只包含可打印的ASCII +换行符,并且不包含空行。
输入:
function fib(n) {
var a = 1, b = 1;
while (--n > 0) {
var tmp = a;
a = b;
b += tmp;
if (a === Infinity) {
return "Error!";
}
}
return a;
}输出:上面的示例代码。
输入:
a
b
c
d
e
f
g
h输出:
a
b
c
d
e
f
g
h输入:
1
2
3
2
1输出:
1
2
3
2
1输入:
foo输出:
foo发布于 2014-12-18 22:19:44
->s{l=s.scan(r=/^ */).uniq.sort;s.gsub r,l.zip(l.reverse).to_h}这定义了一个未命名的函数,它接受并返回一个字符串。您可以通过追加["string here"]或将其赋值给变量,然后调用该变量来调用它。
工作原理:s.scan(r=/^ */)给出了所有在r中表示的空格和存储库的列表,供以后使用。uniq消除重复。sort...分类。
现在跳到最后,l.zip(l.reverse)给出了一组我们想要替换的对。to_h将其转换为散列,将这些对解释为键值对。
现在,s.gsub使用该哈希作为查找表来替换regex的所有匹配(所有前导空格)。
发布于 2014-12-18 22:19:42
发布于 2018-06-05 07:28:09
-R,27字节·
mâ\S
Vâ n
Ëx2 iSpWg~WbVgEInput: U = multiline string
qR Split by newline and implicit assign to U
mâ\S
m Map over U...
â\S .search(/\S/); first index of non-whitespace char
Implicit assign to V (V = array of indentations)
Vâ n Take unique elements of V, sort, and implicit assign to W
mDEF{Dx2 iSpWg~WbVgE
mDEF{ Map over U...
Dx2 Trim left
iSp Indent by this many spaces...
VgE Find the current indentation stored in V
Wb Find its index on W
Wg~ Take the opposite element on W
-R Join with newline Input: U = multiline string
qR Split by newline and implicit assign to U
mâ\S
m Map over U...
â\S .search(/\S/); first index of non-whitespace char
Implicit assign to V (V = array of indentations)
Vâ n Take unique elements of V, sort, and implicit assign to W
mDEF{Dx2 iSpWg~WbVgE
mDEF{ Map over U...
Dx2 Trim left
iSp Indent by this many spaces...
VgE Find the current indentation stored in V
Wb Find its index on W
Wg~ Take the opposite element on W
-R Join with newlinehttps://codegolf.stackexchange.com/questions/42510
复制相似问题