Make a sum in thyme

About advanced scenes, and the Thyme scripting language used in Algodoo.

Make a sum in thyme

Postby KarateBrot » Tue Oct 06, 2009 3:20 pm

for(n, (i)=>{ . . . })
How can I make a sum with the for-function?

for examlpe this simple sum
Image

I'm asking you because for example if I type "for(10, (i)=>{i})" it just shows the 10th member:
0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 => it just shows the 10th member (the 9) as a result but not the whole sum.

So again... How can I make a sum with the for-function?

Thanks :thumbup:

- - - - -

I just found out how it works. If anyone needs it, here's the thyme code:

Code: Select all
scene.my.sum = (n) =>
{
   value := 0;
   for(n, (i)=>{value = value + i});
   value
}


For example:
scene.my.sum(6) = 15 (because of 0 + 1 + 2 + 3 + 4 + 5)

I will extend this idea to make a general sum function so you can add everything you want.
Image
User avatar
KarateBrot
 
Posts: 825
Joined: Mon Aug 31, 2009 7:32 pm
Location: Germany

Re: Make a sum in thyme

Postby immibis » Wed Oct 07, 2009 3:16 am

To add the values in an array, use this (based on your code just now):
Code: Select all
scene.my.sum = (length, array) =>
{
    value := 0
    for(length, (i)=>{value = value + array(i)})
    value
}


To add consecutive numbers from 0, I suggest you use this:
Code: Select all
scene.my.sum = (n) => {(n)*(n-1)/2.0}
Last edited by immibis on Fri Oct 09, 2009 1:18 am, edited 1 time in total.
Thymechanic
immibis
 
Posts: 87
Joined: Wed Sep 30, 2009 12:24 am

Re: Make a sum in thyme

Postby KarateBrot » Thu Oct 08, 2009 10:21 pm

thanks for your reply :thumbup:

i've got one question: what is the bracket of array[i] for? i only know array(i)

- - - - -

Code: Select all
scene.my.sum = (n) => {(n)*(n-1)/2.0}

i know this formula but i just wanted to give an example so i don't want to only calculate 1+2+3+4+...+n ;)
Image
User avatar
KarateBrot
 
Posts: 825
Joined: Mon Aug 31, 2009 7:32 pm
Location: Germany

Re: Make a sum in thyme

Postby immibis » Fri Oct 09, 2009 1:18 am

Sorry, that should be array(i). I've edited my post.
Thymechanic
immibis
 
Posts: 87
Joined: Wed Sep 30, 2009 12:24 am


Return to Thyme scripting

Who is online

Users browsing this forum: No registered users and 8 guests

cron