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'