Revision 97c7ad5f-3883-4193-b93b-80520fd48720 - Code Golf Stack Exchange
# [J], <sub><s>49</s></sub> 45 bytes
-4 bytes thanks to shorter Collatz Sequence code taken from @randomra's comment [here](https://codegolf.stackexchange.com/a/12186/42833).
(2-~[:#(>&1*-:+2&|*+:+>:@-:)^:a:)^:(<101)i.1:
Outputs `101` for invalid results.
[Try it online!][TIO-jc5h2w3z]
# Explanation
Unsurprisingly, this explanation has become quickly outdated. I'm going to leave it in terms of the old 49 byte answer I had, which I'm including below. If you want an update, just let me know. The way that it finds the length of the recursive sequence remains the same, I've just used a shorter Collatz Sequence method.
(1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:)^:(<101)i.1:
### Finding the length of the Collatz Sequence
This section of the code is the following
(1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:)
Here's the explanation:
(1 -~ [: # %&2`(1+3&*)@.(2&|) ^: (1&<) ^: a:) Given an input n
^: a: Apply until convergence, collecting
each result in an array.
^: (1&<) If n > 1 do the following, else
return n.
(2&|) Take n mod 2.
%&2 If n mod 2 == 0, divide by 2.
(1+3&*) If n mod 2 == 1, multiply by 3
and add 1.
# Get the length of the resulting
array.
1 -~ Subtract 1.
Unfortunately, the apply verb (`^:`) when told to store results stores the initial value too, so it means we're (like always) off by one. Hence why we subtract 1.
### Finding the length of the recursive sequence
(1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:) ^: (< 101) i. 1: Given an input n.
^: (< 101) Apply 100 times,
collecting results
in an array.
(1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:) Collatz sequence length.
i. 1: Index of first 1 (returns
101, the length of the
array if 1 not found).
[J]: http://jsoftware.com/
[TIO-jc5h2w3z]: https://tio.run/##y/r/P81WT8NIty7aSlnDTs1QS9dK20itRkvbStvOykHXSjPOKhFEaNgYGhhqZuoZWv1PTc7IV0hTSC1LLapUMFQwUjBVMDQAIiBOBZNGxiamZuYWlgYI1n8A "J – Try It Online"