APL, 36 34 39 36 33 29 27
*+/x={(∇⍣(⊃x>¯1↑⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕
Output 1
if Keith, 0
otherwise
GolfScript strikes again!!
Edit
+/x={(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕
Using Right-reduction (⊢/
) instead of Take minus 1 (¯1↑
), directly saving 1 char and indirectly saves 1 from Disclose (⊃
)
Explanation
⍎¨⍕x←⎕
takes evaluated input (treated as a number) and assign it to x
. Converts it to a character array (aka "string" in other languages), and loop through each character (digit), converting it to a number. So this results in a numerical array of the digits.
{(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}
is the main "loop" function:
+/⍵↑⍨-⍴⍕x
takes the last ⍴⍕x
(no. of digits in x
) numbers from the array and sums them.
⍵,
concatenates it to the end of the array.
(x>⊢/⍵)
check if the last number on the array (which doesn't have +/⍵↑⍨-⍴⍕x
concatenated yet) is smaller than x
and returns 1
or 0
∇⍣
executes this function on the new array that many times. So if the last number is smaller than x
, this function recurs. Otherwise just return the new array
After the executing the function, the array contains the sums up to the point where 2 of the numbers are greater than or equal to x
(e.g. 14
will generate 1 4 5 9 14 23
, 13
will generate 1 3 4 7 11 18 29
)
Finally check if each number is equal to x
and output the sum of the resulting binary array.
Edit
1=+/x={(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕
Added 2 chars :-( to make output 0
if the input is one-digit
Yet another edit
+/x=¯1↓{(∇⍣(x>⊢/⍵))1↓⍵,+/⍵}⍎¨⍕x←⎕
Explanation
The function now drops the first number (1↓
) from the array instead of taking the last ⍴⍕x
(↑⍨-⍴⍕x
).
However, this approach makes 1=
not adequate to handle single digit numbers. So it now drops the last number from the array before checking equality to x
, adding 1 char
You guessed it: EDIT
+/x=1↓{1↓⍵,+/⍵}⍣{x≤+/⍵}⍎¨⍕x←⎕
Compares x
to the newly-added item instead of the old last item, so dropping the first (instead of last) item before checking equality to x
is suffice, saving a minus sign.
Saves another 3 by using another form of the Power operator(⍣
)
And a 25-char gs answer appears (Orz)
Last edit
x∊1↓{1↓⍵,+/⍵}⍣{x≤+/⍵}⍎¨⍕x←⎕
Can't believe I missed that.
Can't golf it anymore.
true
/false
or can it be anything truthy/falsey? \$\endgroup\$