Sunday, January 17, 2016

(Algorithm) How to count frequencies of all elements of array

Question: How can we count frequencies of all elements of array?

Resource: http://www.careercup.com/page?pid=algorithm-interview-questions
Question owner: HimanshuP

ANSWER

Let's give an example of array: a[9] = {5, 3, 7, 3, 3, 1, 6, 5, 7}

In real World, we recognize elements that we "already" count, and so we don't count them again. So, in computer world, we "remember" those already counted elements, too.

I will do this work with two dimensional array. Let's initialize two dimentional dynamic integer array b[1][1]. Then follow steps below:

Read element of array and store it into "k".
Check if this element is already stored into first column of array.(b[a][0] == k)
If it is not, then start to count this element from its location.
Else, skip this element. Because it was already counted.

Let's write pseudocode of this algorithm. End of this code we have two dimentional array which holds in second row that how many times does number repeat:

WHILE i is less than size of array a
SET flag to 0.
STORE a[i] into holder.
DEFINE and INITIALIZE counter m to 0.
WHILE m is less than number of rows of array b
IF b[m][0] is equal to holder.
SET flag to 1.
            END IF
            INCREASE m by 1
END WHILE
IF flag does not equal 1
INCREASE number of rows of array b by 1.
STORE holder into b[m][0].
DEFINE and INITIALIZE counter j to 1.
IF (i+1) is less than size of array a.
ASSIGN (i+1) to h.
WHILE h is less than size of a.
IF a[h] equals holder
INCREASE j by 1
END IF
                        INCREASE h by 1
END WHILE
END IF
STORE j into b[m][1]
END IF
INCREASE i by 1.
END WHILE

No comments:

Post a Comment