Thursday, June 4, 2020

#1 2020-03-24 04:56:30 pm

cphil
Member
From:: Japan
Registered: 2020-03-24
Posts: 2

Add numbers in a list until specific value is reached & restart

Hello!
I'd like to loop through a list, adding each item to the next and return the index of every instance where the values are equal to or greater than 5.

So for example, if I loop through {2, 2, 2, 3, 2, 5}, I'd like return a new list of {3,5,6}

2+2+2 ≥ 5
3+2 ≥ 5
5 ≥ 5

I can get this to work for one iteration but my problem is looping through the list again (without starting from the beginning). The script I have below returns 3 but then of course just keeps adding every number together so I'm kinda stuck and wondered if anybody could help sad


Applescript:

set myList to {2, 2, 2, 3, 2, 5}
set newList to {}
set total to 0

repeat with i from 1 to (length of myList)
   set total to total + (item i of myList)
   if total ≥ 5 then
       copy i to end of newList
   end if
end repeat

return newList --> returns {3, 4, 5, 6}

Offline

 

#2 2020-03-24 05:21:04 pm

peavine
Member
From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 485

Re: Add numbers in a list until specific value is reached & restart

cphil wrote:

I'd like to loop through a list, adding each item to the next and return the index of every instance where the values are equal to or greater than 5.



Try this:

Applescript:

set myList to {2, 2, 2, 3, 2, 5}
set newList to {}
set total to 0

repeat with i from 1 to (length of myList)
   set total to total + (item i of myList)
   if total ≥ 5 then
       copy i to end of newList
       set total to 0
   end if
end repeat

return newList --> {3, 5, 6}

Last edited by peavine (2020-03-25 04:51:52 pm)


2018 Mac mini - macOS Catalina

Offline

 

#3 2020-03-25 04:58:25 pm

cphil
Member
From:: Japan
Registered: 2020-03-24
Posts: 2

Re: Add numbers in a list until specific value is reached & restart

It works perfectly!
I really appreciate you taking the time to help with this. Thank you so much!

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)