Forum Moderators: open

Message Too Old, No Replies

FIFO problem with table

want to create a summary from a part of a table

         

mcibor

4:25 pm on Mar 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have a table:
No.¦weight¦amount¦cost
1 ¦ 100.00¦100000¦100
2 ¦ 200.00¦200000¦98
3 ¦ 300.00¦400000¦50

and I have an input: weight, eg 400.

My problem is how to create a summary from the values of the table that won't exceed the weight in input.

In this case it would be sum of 1+2, because 1+2+3 will exceed given weight. the answer I need is: [300, 300000, 198] and a number 2 (on which row the counting ended).

The count has to be done by fifo (first in first out = starting from the top).

please help, or at least say if that cannot be done in javascript, then I'll turn to server side script php.

Michal Cibor

SpaceFrog

4:39 pm on Mar 17, 2005 (gmt 0)

10+ Year Member



can be done in javascript

an array can be sorted!

then loop on array indexes and test if value is > ...

Bernard Marx

7:01 pm on Mar 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




Array.prototype.vectorAdd = function(V){
for(var i=0;i<this.length;) this[i]+=V[i++]
}

var table =
[
[100,100000,100],
[200,200000, 98],
[300,400000, 50]
];

[blue]/*
Don't know what kind of real table you are using.
I have thrown in this function to abstract the
process of getting an array of values from the
table.

If the 'table' is an HTML table, all that's
needed is to change this function's implementation.

! swap the ¦¦ for unbroken pipes!
*/[/blue]
function getRowVector(table,iRow)
{
return table[iRow]¦¦null;
}

function getSummary(maxWeight)
{
var Vsum = [0,0,0];
var totalWeight=0,r=-1, row;
[blue]/* could just do: row = table[++r] */[/blue]
while( row = getRowVector(table,++r))
{
if( (totalWeight += row[0]) > maxWeight) break;
Vsum.vectorAdd(row);
}
[blue]/* Add r to front of array.
It's already 1 ahead of row index, so it suits row no. */[/blue]
Vsum.unshift(r);
return Vsum;
}

alert( '['+getSummary(400)+']' );

mcibor

2:39 pm on Mar 22, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks Bernard for the script! It's really helpful and almost working:). That means it works in any new html I make, but not the desired one. However that is another problem.

Thanks a lot.

BTW I knew theoretically how to do this, but don't have any experience with arrays in javascript, therefore the script provided me with great insight into making and operating an array.