I've heard that your code can run faster if you indent it in reverse, so that the compiler can process it like a tree design pattern from the very top of the "branches" down. This helps because gravity will speed up the time it takes for your code to be compiled, and the data structure efficiency is improved. Here's an example, in Java scripting:
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;
}
But for some reason Notepad doesn't have a setting to do this automatically, so I need a program to do it for me.
Description
Submissions must take a code snippet as input, reverse the indentation, and output the resulting code.
This is done by the following procedure:
Split the code up into lines. Each line will start with zero or more spaces (there will be no tabs).
Find all unique indentation levels in the code. For example, for the above example, this would be
0 4 8 12
Reverse the order of this list of indentation levels, and map the reversed list to the original list. This is hard to explain in words, but for the example, it would look like
0 — 12 4 — 8 8 — 4 12 — 0
Apply this mapping to the original code. In the example, a line with 0-space-indentation would become indented by 12 spaces, 4 spaces would become 8 spaces, etc.
Input / Output
The input and output can be provided however you would like (STDIN/STDOUT, function parameter/return value, etc.); if your language does not support multiline input (or you just don't want to), you can use the |
character to separate lines instead.
The input will consist of only printable ASCII + newlines, and it will not contain empty lines.
Test cases
Input:
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;
}
Output: the example code above.
Input:
a
b
c
d
e
f
g
h
Output:
a
b
c
d
e
f
g
h
Input:
1
2
3
2
1
Output:
1
2
3
2
1
Input:
foo
Output:
foo