Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a number into its digits in APL

Tags:

split

numbers

apl

In APL, how can I split an integer or number into a vector containing its digits? What is the most concise (shortest) way of doing this?

like image 622
lmq_305 Avatar asked Dec 13 '22 22:12

lmq_305


2 Answers

You can use the inverse of Decode with base 10:

10⊥⍣¯1⊢

since Decode would take in as many digits as needed and decode them, its inverse would take a number and encode it to as many digits as needed,

or, with ⎕IO←0, you can try to find the indexes of the formatted number inside the digits vector:

⎕D⍳⍕

Demo for both solutions.

This is better than the uglier use of Encode with custom length derived by shaping an array of 10 to the length of the log10 of the input:

{⍵⊤⍨10⍴⍨⌈10⍟1+⍵}
like image 160
Uriel Avatar answered Dec 25 '22 19:12

Uriel


I did this in APL2 by first applying FORMAT and then EXECUTE EACH (though it might be limited to positive integers) :

⍎¨⍕

Try it online!

like image 39
mappo Avatar answered Dec 25 '22 18:12

mappo