I've been trying to write a function toTriangle
which converts a given integer to a triangular array. For example:
toTriangle(123456) = {{1, 2, 3}, {4, 5}, {6}}
toTriangle(1010101010) = {{1, 0, 1, 0}, {1, 0, 1}, {0, 1}, {0}}
and so on. Naturally, this only works if the number of digits of the integer n
is a triangular number. (that is, if $n = m(m+1)/2$ for some $m\in\mathbb N$.
I have written the following to try and implement this:
toTriangle := Function[n,
len := 1/2 (Sqrt[1 + 8 IntegerLength[n]] - 1);
digits := IntegerDigits[n];
triangle = {};
For[i = 0, i < len; i++,
AppendTo[triangle, Take[digits, n - i]];
digits = Drop[digits, n - i];
];
triangle
];
I have tried dry running the code bit by bit, and I noticed that it was the Take[]
function which was causing the hassle; I suspect that you cannot give it a variable argument in position 2:
Take::seqs: Sequence specification (+n, -n, {+n}, {-n}, {m, n}, or {m, n, s}) expected at position 2 in Take[{1,2,3,4,5,6},i]. >>
The same exact code I tested worked if I substituted i
with some number. (directly, not by doing /. i->3
). Can someone help me with this?
Module
. Is there any reason to define a pure function rather thantoTriangle[n_]:=...
?AppendTo
andFor
are not "Mathematica like", you might want to try to bring the function into a more functional form $\endgroup$ – Lukas Lang Sep 18 '17 at 21:36