MATL、35 34バイト
1バイトを節約してくれた@Emignaに感謝します!
32Oittn:oEq*Yst1hX<-Q(Vh' 0'95ZtXz
オンラインでお試しください!または、すべてのテストケースを確認します。
使い方
説明ではなくコードをゴルフしましょう!
以下では、入力[2,3,6,8,2]
を例として使用します。実際のコードで中間結果を表示するには、%
(コメント記号)を挿入して、その時点でプログラムを停止し、スタックの内容を表示することができます。たとえば、これはステートメントの後のスタックYs
(累積合計)を示します。
32 % Push 32 (ASCII for space)
O % Push 0
i % Input array
% STACK: 32, 0, [2,3,6,8,2]
t % Duplicate
% STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2]
tn: % Push [1 2 ... n] where n is length of input array
% STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2], [1,2,3,4,5]
o % Modulo 2
% STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2], [1,0,1,0,1]
Eq % Multiply by 2, subtract 1
% STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2], [1,-1,1,-1,1]
* % Multiply elementwise
% STACK: 32, 0, [2,3,6,8,2], [2,-3,6,-8,2]
Ys % Cumulative sum
% STACK: 32, 0, [2,3,6,8,2], [2,-1,5,-3,1]
% The top-most array is the positions where the entries of the second-top
% array will be written. But postions cannot be less than 1; if that's
% the case we need to correct so that the minimum is 1. If this happens,
% it means that the frog has gone further left than where he started
t % Duplicate
1hX< % Append 1 and compute minimum. So if the original minimum is less than 1
% this gives that minimum, and if it is more than 1 it gives 1
% STACK: 32, 0, [2,3,6,8,2], [2,-1,5,-3,1], -3
- % Subtract
% STACK: 32, 0, [2,3,6,8,2], [5 2 8 0 2]
Q % Add 1
% STACK: 32, 0, [2,3,6,8,2], [6 3 9 1 3]
( % Assign values (top array) to specified positions (second-top) into array
% which contains a single 0 (third-top). Newer values overwrite earlier
% values at the same position
% STACK: 32, [8 0 2 0 0 2 0 0 6]
V % Convert to string. This produces spaces between the numbers
% STACK: 32, '8 0 2 0 0 2 0 0 6'
h % Concatenate with initial 32 (space). This converts to char
% STACK: ' 8 0 2 0 0 2 0 0 6'
% Thanks to this initial space, all zeros that need to be replaced by '_'
% are preceded by spaces. (In this example that initial space would not
% be needed, but in other cases it will.) Other zeros, which are part of
% a number like '10', must not be replaced
' 0' % Push this string: source for string replacement
% STACK: ' 8 0 2 0 0 2 0 0 6', ' 0 '
95 % Push 95 (ASCII for '_'): target for string replacement
% STACK: ' 8 0 2 0 0 2 0 0 6', ' 0 ', 95
Zt % String replacement
% STACK: ' 8_2__2__6'
Xz % Remove spaces. Implicit display
% STACK: '8_2__2__6'