Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm - How to find the minimum total reading time of n-texts when we have each text's length and frequency?

Tags:

algorithm

The problem sounds like this, we are given n-texts and they are going to be placed on a tape/ribbon/band(don't really know what's the equivalent in english, but I think you understand what I'm talking about). In order to read the text situated at a position k, we have to read the texts from positions 1,2,...,k.
Each text has its' own length and frequency(number of times it is read). Now, we have to come up with a solution of placing the texts in such an order that the total accesing time to be minimum. The formula for calculating the total accesing time is:

n_
 \  f(Ti)[L(T1)+L(T2)+...+L(Ti)]
 /_    
i=1

Now, that little drawing I did is SUM from 1 to n;

f(T i) is the frequency of T i;

L(T i) is the length of T i;

T i is the text situated at position i;

Here is an equivalent in "pseudocode" in case it helps:

n-number of texts;
Ribbon[n]-array of texts
sum=0, sum2=0;
for(i=0;i<n;i++)
   {sum=0;
   for(j=0;j<=i;j++)
      sum=sum+Ribbon[j].length;
   sum2=sum2+sum*Ribbon[i].frequency;}

Now I tried a couple of tactics, such as sorting the texts in ascending/descending order, according to the length, to the frequency, or even to the length*frequency and also some other couple ideas I had, and none of them worked out, as I always found a counter-example, an element-order that had a smaller total accesing time than what my program gave me.

like image 638
Vasile Turcu Avatar asked Dec 10 '25 02:12

Vasile Turcu


1 Answers

Consider the change in the total sum if we swap two adjacent elements x and y (where x is currently placed immediately before y).

You will find that the difference is f(Tx)L(Ty)-f(Ty)L(Tx).

For example, if the two lengths are the same, then we reduce the sum if we put the higher frequency earlier, while if the frequency is the same, we reduce the sum if we put the shorter length earlier.

We can reach any permutation by swapping adjacent elements (e.g. consider bubble sort), and so if you order the elements according to this comparison function you will achieve the minimum sum.

Note that this comparison function is equivalent to ordering based on L(Tx)/f(Tx), i.e. we want the short/high frequency elements to be done first.

like image 139
Peter de Rivaz Avatar answered Dec 11 '25 17:12

Peter de Rivaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!