Calculating/Summarize Arrays; generate Array

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Calculating/Summarize Arrays; generate Array

NBGer
Hi all,
I need to calculate a summary from array elements.
In detail, the position of an object to print depends on the size of object
before.

I know already, I cannot calculate with simple variable, so I tried to use
array for result.
The problem is, I cannot reference the array x_pos[i-1], when calculating
x_pos[i]:

module gen_slots(dim)
{
    n = len(dim);
    x_pos = [for(i = [0 : n-1]) (i==0)? 0 : x_pos[i-1]+5+dim[i-1] ];   //
<---problem here
    echo(x_pos);
    for (i = [0 : n-1])
    {
        translate([ x_pos[i], 2, 0 ])
         {
             cube([dim[i],dim[i],2],center= false);
         }
    }
}

In C I would write:

void gen_slots(dim)
{
    x_pos = 0;
    for ( int i = 0; i < len(dim); ++i )
    {
        x_pos += 5+dim[i];  
        echo(x_pos);
    }
}

How can I do this in OpenScad?




--
Sent from: http://forum.openscad.org/

_______________________________________________
OpenSCAD mailing list
[hidden email]
http://lists.openscad.org/mailman/listinfo/discuss_lists.openscad.org
tp3
Reply | Threaded
Open this post in threaded view
|

Re: Calculating/Summarize Arrays; generate Array

tp3
Maybe not the most optimized way, but a simple solution
is using a function to calculate the sum of the first
x entries of an array.

dim = [10, 8, 2, 25, 5];

function partial_sum(v, n, r = 0) = n <= 0
        ? r + v[0]
        : partial_sum(v, n - 1, r + v[n]);

n = len(dim);
x_pos = [for(i = [0:n-1]) partial_sum(dim, i)];
echo(x_pos); // ECHO: [10, 18, 20, 45, 50]

Or use a library like https://github.com/thehans/funcutils
which provides lots of additional options based on the
new features. That will need a development snapshot version
though.

ciao,
  Torsten.


_______________________________________________
OpenSCAD mailing list
[hidden email]
http://lists.openscad.org/mailman/listinfo/discuss_lists.openscad.org
-- Torsten
Reply | Threaded
Open this post in threaded view
|

Re: Calculating/Summarize Arrays; generate Array

NBGer
Thank you Torsten,

I will try this recursive approach!



--
Sent from: http://forum.openscad.org/

_______________________________________________
OpenSCAD mailing list
[hidden email]
http://lists.openscad.org/mailman/listinfo/discuss_lists.openscad.org