How to split a number into its digits in APL

a 夏天 提交于 2019-12-23 17:05:17

问题


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?


回答1:


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+⍵}



回答2:


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

⍎¨⍕

Try it online!




回答3:


Not the most concise, but the power to do this was in the earliest APL. The 1962 book shows how to work with positional number systems using only basic functions and matrix multiply:



来源:https://stackoverflow.com/questions/44989382/how-to-split-a-number-into-its-digits-in-apl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!