views:

296

answers:

2

I have an XMLList 'Keywords', which consists of about 30 elements. I want to count the number of unique keywords in the List, and how often they occur. Then display the top 3 most occuring keywords.

There's probably a simple sorting/count function to carry this out, however, i'm quite new to as3 so please forgive my naivety.

Cheers.

A: 

I don't think there's a one-line fix for this.

The most straightforward way I can see of doing this is as follows:

  1. Put your keywords into an array so you can sort them. This results in multiple occurrances of any keyword being grouped together.

  2. Now make a second array to hold a key-value pair for each keyword (the value is the number of occurrances). You can do this by stepping through the first array and examining each value: either it's the start of a group (so add a new k-v object to the second array), or it's another occurrance of the previous keyword (so increment the count value of the last k-v object).

  3. Now you can use the sortOn() method on your second array to sort by the number of occurrances of each keyword.

The code (this may need some fixing - afraid my AS3 is not so good yet, and I'm not able to test it... writing this on my iPhone!) would look something like this:

//put the keywords into an array, and sort them
var a1:Array=new Array();
for each (var item in keywords){
a1.push(item);
}
a1.sort();

//make an array to hold a key/value pair for
//each unique keyword, and how often it occurs
var a2:Array=new Array();
var currentKey:String="";
for each (var item in a1){
if (item!=currentKey){
//if we haven't seen this word before,
//make a new k/v pair with a count of 1
a2.push({key:item, keyCount:1});
currentKey=item;    
} else {
//otherwise increment count
a2[a2.length - 1].keyCount++;
}

//now we can sort the array by keyCount
a2.sortOn("keyCount", Array:DESCENDING);

trace("3 top words are: ", a2[0], a2[1], a2[2]);

Hope this works for you.

Richard Inglis
A: 

Just a quick revision:

The line reading 'Array:DESCENDING' should be 'Array.DESCENDING'.

no attack