counting occurrences

Anything beyond the basics in using the LiveCode language. Share your handlers, functions and magic here.

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller, robinmiller

Klaus
Posts: 13865
Joined: Sat Apr 08, 2006 8:41 am
Location: Germany
Contact:

Re: counting occurrences

Post by Klaus » Wed Sep 29, 2021 1:33 pm

Hi Michael,

yes, but that does not take doublettes into account what the thread starter asked for.


Best

Klaus

RCozens
Posts: 138
Joined: Thu Aug 05, 2021 6:42 am
Location: Manchester, CA USA

Re: counting occurrences

Post by RCozens » Wed Sep 29, 2021 7:03 pm

adventuresofgreg wrote:
Mon Nov 05, 2012 2:24 pm
Hi: What do you think would be the fastest and most efficient method of counting the number of occurrences of a number in a list? i
Hi Greg,
Here's another approach that might produce quicker results depending on the efficiency of the sort command. This assumes your numbers are in the variable, numberList.

Code: Select all

on countItems numberList
   put .25 into valueRange
   ask "Enter the target value"
   put it into targetValue
   put targetValue+valueRange into maxValue
   sort items numberList ascending numeric
   put itemOffset(targetValue,numberList) into firstHit
   put 0 into matchCount
   if firstHit <> 0 then
      repeat with itemNumber = firstHit to the number of items of numberList
         if item itemNumber of numberList > maxValue then exit repeat
         add 1 to matchCount
      end repeat
   end if
   answer matchCount
end countItems
This works for the small list I tested. Note: the target value should include the decimal point, but no decimal digits. This assumes your value range starts with the whole number (ie: 3.0-3.25, not 2.75-3.25.

Cheers!
Rob Cozens dba Serendipity Software Company
Manchester, CA USA

Each new generation gives more attention to the man-made world...
and less attention to the world that made man.

Fermin
Posts: 142
Joined: Fri Jun 05, 2015 10:44 pm

Re: counting occurrences

Post by Fermin » Sat Aug 26, 2023 7:33 pm

Code: Select all

function CountOccurrences haystack, needle
   set the itemdelimiter to needle
   return the number of items in haystack - 1
end CountOccurrences

Post Reply

Return to “Talking LiveCode”