views:

45

answers:

3

Hi there! I've been trying to wrap my head around this for some time now, but haven't been able to come up with an elegant solution.

The problem: I have a string with different characters ("ABDDEEDDC") and I need to know which character occurs the most. Any help would be greatly appreciated.

Cheers, Niko

A: 

There is as far as I know no built-in support for this. But you can iterate through the string with String.charAt() and maybe save the results in an array. If the array already contains the specific char you can increase a number or something like that.

hering
+4  A: 

I don't know of any built in support for it, but you can use the charAt() property of strings, and associative arrays to do the following:

var charCounter:Object = new Object();
var str:String = "ABDDEEDDC";
var maxCount:int = 0;
var maxChar:String = "";

for(var i = 0; i < str.length; i++) {
    // Must make sure the associate array is initialised!
    if(charCounter.hasOwnProperty(str.charAt(i)) {
        charCounter[str.charAt(i)]++;
    } else {
        charCounter[str.charAt(i)] = 1;
    }
    if(charCounter[str.charAt(i)] > maxCount) {
        maxCount = charCounter[str.charAt(i)];
        maxChar = str.charAt(i);
    }
}

At the end of this the character should be in maxChar, and the number of times it appears in maxCount.

charAt().

Associative Arrays.

(Sidenote: I believe that instead of charCounter.hasOwnProperty(str.charAt(i)) you can use str.charAt(i) in charCounter, but I've not tested it.)

Stephen
Thanks for your reply! For some reason I can't get any output using your code, can't seem to find the problem either, what could be wrong?
You forgot to initialize them. Change `charCounter[str.charAt(i)] += 1;` to `if(charCounter.hasOwnProperty([str.charAt(i)])) charCounter[str.charAt(i)] ++;else charCounter[str.charAt(i)] = 1;` @nikoka
Amarghosh
+1 for providing an example and adding more details to my "answer approach"
hering
Ah, I knew I'd forgotten something. Sorry nikoka, I had forgotten to initialise the values in the map. Cheers @Amarghosh! I will update my answer.
Stephen
Thanks everyone, works like a charm!
A: 

or you could split it into an array, sort and then just count up each value

var str:String = "ABDDEEDDC";
var a:Array = str.split('');
a.sort();
var currChar:String = '';
var currCount:int = 0;
var maxChar:String = '';
var maxCount:int = 0;
for(var i:int=0; a[i]; i++){
    if(currChar == a[i]) {
        currCount++;
        if(currCount > maxCount){
            maxCount = currCount;
            maxChar = currChar;
        }
    } else {
        currChar = a[i];
        currCount = 1;
    }
}
trace(maxChar + ' occurs '+maxCount+' times');
danjp