Fixed line Tag Cloud Algo

I did posted about Generation of Tag Cloud formation based on given width and height in pixels. Instead of extending that one I had to take on another way of doing it so had to make a new strategy of making it work out. This one gives more accuracy the last one was about 95% accurate while this is 100% accurate.

Here also the issues are same but the approach towards it is quite different.

If you haven’t read the previous post, let me educate you that what the scenario is.

The thing is to find an algo that would populate a table cell or area if we specify a width and height parameter.

Normally tags in tag clouds vary in size and length so just counting the characters of it is not going to work. As there is no way to predict what space each tag will occupy. Moreover if a tag consists of two or more words in it then it tends to word wrap itself if the width is too smaller for it. So counting the number of lines is also not going to work. Neither if it doesn’t wraps because font sizes of tags do vary and thus the height will vary.

So here is the new one :

Fixed Line Tag Algo

What I am trying to do here is that I am going to first of all take 2 parameters that will be width and height.

$width = 200;
$height = 300;

Now will also specify the max font size.

$maxsize = 24;

Now just print some character in a table cell of 200 width in test page and see how many it can occupy in one line and also check what pixels it takes in height.

Save that number in some variable. EX: $maxwide = 14; [Here assuming it will hold 14 characters in one line] and $maxhigh = 16 [Here assuming it will be 16 pixels high at max font size].

Dividing total height by maxhigh, we get the number of rows it can accommodate.

If it is not a round number then you can just use settype function of PHP here.

We set counter of lines to 1 and start the loop from 1 to number of rows it can accommodate.

We set $leftwide = 0; [For counting the characters space used in lines]

Tags can be fetched from array or database it doesn’t matters.

Assign the size to tag randomly or with some other function you might be using for assigning font weights to the tags.

Count characters of that tag with strlen();

If it is smaller then $maxwide then print it. If not then also print it but set $counter = $counter + 1;

Also set $leftwide = $maxwide – strlen(Tag1 here);

Assuming it was smaller then $maxwide take another tag.

If another tag does have space in it, then count the first word in that tag.

See if it is possible to fit it in the remaining space…. By checking the length of this tag and $leftwide. [Which is the current counter for this line we are printing right now]

If yes then fit it in… If no then move to line 2 and update the $counter = $counter + 1;
Loop finished here.

DONE 🙂

To make it look more beautiful you can assign text align to justify.