Count the occurrences of an item in a List or Array

So I came across a situation where I had a whole bunch of items in a collection, and I needed to know how many of each kind there were.  In other words, I needed to know the number of each unique element in an IList, Array, ArrayCollection, or what-have-you.  I looked for some help online, and fiddled around and got it working.  Then a few weeks later I had to do the same thing, and darn near forgot how I did this.  Here is the trick – SORT!

Sort the items in the array (alphabetically, numerically, chronologically, etc…) so that unique items are grouped together.  Then simply loop over the collection counting identical items, and when a new item occurs, make a note of how many you have of the first item, and start counting again.  Below is a quick example.  Click “Generate” to create a list of 50 items, where each item is going to be a fish, cat, dog or pony.  Then click “Count” to count the number of each one.  Also notice how the original list is now sorted so all the ‘dogs’ and ‘cats’ are together.

Sorry, either Adobe flash is not installed or you do not have it enabled

Here’s the meat of the code:

sortedList = new Array();

//Sort Newlist Alphabetically

/*  Create an object to keep track of each unique item in the array. For example
*   { Name: 'cat'
*     Value: 7  }

var countObject:Object;

//Create a var to store the previously examined item in the list.
var previousItem:String;

//Loop over all the items in the newArray
for each ( var currentItem:String in newList )
//If the current item in the list is different from the previous item, then create a new countObject and start counting the new item.
if (previousItem == null || currentItem != previousItem)
//Create a new object
countObject = new Object();

//Set the name to the current item in the loop
countObject.name = currentItem;

//Count this item
countObject.value = 1;

//Put the object in the sorted list so we can see it later

//Done. Set the current item to the previous item.
previousItem = currentItem;
else  //Otherwise, we haven't switched to a new item yet, so keep counting the current item.
/*  Find the last countObject in the sortedList, then add 1 to the value of that object.
*   For example, if we have looped over 3 cat items in a row, and the current item is also cat, then:
*   { Name: cat, Value: 3 + 1 }

sortedList[sortedList.length - 1].value += 1;

and Full Source for the above example.

A Fountain Of Color – AS3 Animation Example from Foundation Actionscript Animation Book

If you are remotely interested in Actionscript, Flash, computer animation, games, or pretty stuff on computers – go get Kieth Peters’ book, “Foundation Actionscript 3.0 Animation: Making Things Move.”  Then check out
Keith Peters blog (but really his other sites).  After reading parts 1 and 2 of the book, which cover basic animation, I felt compelled to take one of the examples a bit further.

In Part 2: Basic Motion, the concepts of moving pixels programatically around the screen by shifting the x and y position every frame is introduced.  A ‘veloctiy’ is assigned to both the x and y values to determine how many pixels the object moves per frame.  The fountain example in the book demonstrates these concepts by shooting a bunch of colored balls from the bottom of the screen, with slightly random values for the x and y velocity.

I added some controls, just for fun.  Use the up and down arrow keys to increase or decrease the height, and use left/right to change the direction.  Also, if you look at the code, I changed the concept of x and y velocities to speed and angle. So rather then setting a velocity value for the x and y values of each ball, I set a speed and angle, and use this information to update the balls’ positions.  The original code remains in comments for reference.  Take a look.


ColorTransform in AS3 – What? How?

ColorTransform is this mysterious class that had me baffled for quite a while.  You punch in a bunch of numbers, and somehow it is supposed to create one color from another.  But how?  How do the colors change? How do I get this thing to change the color of something on the screen when I want it to?  A fair bit of guesswork and luck was my answer.  Then I got learned up.  The Adobe LiveDocs got me started, but as for actually putting ColorTransform to good use in a real, live Flex project called for some additional know-how.

First, learn about colors on computers. You need to know what RGB stands for, and the difference between hexadecimal and decimal numbers.  Here’s a fun site called “Color Tutorial” (aptly named) to get you started.  And here’s a nice little page that demonstrates how RGB and hexadecimal numbers fit together.

Once you understand how colors are constructed from numbers, then understanding ColorTransform comes naturally.  All it does is jumble up the numbers with some simple math.  The math is explained in the AS3 documentation like this:

When a ColorTransform object is applied to a display object, a new value for each color channel is calculated like this:

New red value = (old red value * redMultiplier) + redOffset
New alpha value = (old alpha value * alphaMultiplier) + alphaOffset
New green value = (old green value * greenMultiplier) + greenOffset
New blue value = (old blue value * blueMultiplier) + blueOffset
If any of the color channel values is greater than 255 after the calculation, it is set to 255. If it is less than 0, it is set to 0.

So there you have it.  A DisplayObject has some colors, and you can transform those colors by fiddling with the RGB values.  You can even transform the alpha channel (transparency).  But how do you know what colors you will end up with?  That was a head scratcher.  Unless you have color codes memorized and are quick with the arithmetic, it’s darn tough to get an exact idea.  Here are a few resources that explain ColorTransform, and show it in action:

There, lots of nice examples.  However, in order to really take advantage of colors and ColorTransform, you should really know how to manipulate color values on your own.  In the flashandmath page, you may have notices a line like this:

RGB=(red<<16) | (green<<8) | blue;

What?  Yeah, this is an example of a bitwise shift operation.  Double what?  Well, follow the link from flashandmath to get a brief rundown.  The gist of it is, the little carrots >> help separate the R, G and B values from a color value, or put separate R, G, and B values back together as a single color with the << symbol.  The nitty gritty is still a little fuzzy, but you don’t need to understand all the nuts and bolts to use the tool.

Of course, I haven’t mentioned HSV as an alternative to RGB.  But these resources are just the tip of the iceberg when it comes to color manipulation.  Check out these sites for extra credit if you are feeling ambitious:


© 2017 Eric Terpstra

Theme by Anders NorénUp ↑