PDA

View Full Version : stem and leaf diagram



Markeh
Mar 28th, 2007, 07:25 PM
Hi guys I know this is very boring but hopefully someone can help. As part of an assignment I have to make a steam and leaf diagram to display on a webpage using javascript.

We have been given two arrays in a .js file to work with -

var french = new Array(10, 11, 13, 20, 22, 24, 27, 32, 36, 47);

var english = new Array(15, 28, 29, 31, 35, 36, 38, 42, 42, 45);

I have no idea how to make this work, i was thinking something along the lines of a loop for each array which will check if the values are under 20, under 30 etc then add them to separate arrays which i can display.

my coding sucks so heres what i mean in sortof psuedo code

for(var i = 0; i < french.length; i++)

if french[i] < 20
{(french[i] - 20) then add the value to frenchu20 array }
if french[i] < 30
{(french[i] - 30) then add the value to frenchu30 array }

http://us.f13.yahoofs.com/bc/4446af73mf03f8790/bc/My+Photo+Album/stem.jpg?bfxarCGBLY_1oUR4

If anyone know how to do this or can offer any help, it would be much appreciated. :thumbsup:

shyam
Apr 2nd, 2007, 07:55 PM
var french = [10, 11, 13, 20, 22, 24, 27, 32, 36, 47];
var english = [15, 28, 29, 31, 35, 36, 38, 42, 42, 45];
function buildLeaves(array) {
var index = 0;
var i = 0;
var left = [];
while ( i < array.length ) {
var div = 10 * index;
if ( (array[i]-div) < 10 && parseInt(array[i]/div) == 1 ) {
if ( typeof(left[index]) == 'undefined' ) {
left[index] = [];
}
left[index].push(array[i] % div);
i++;
} else {
index++;
}
} // endwhile
return left;
}
function maxCount(array) {
var max = 0;
for ( i = 0; i < array.length; i++ ) {
if ( typeof(array[i]) != 'undefined' ) {
max = max > array[i].length ? max : array[i].length;
}
}
return max;
}
function stemLeaf(array1, array2) {
if ( array1.length == array2.length ) {
var left = buildLeaves(array1);
var right = buildLeaves(array2);
var lMax = maxCount(left);
var rMax = maxCount(right);
var strBuf = [];
var i = 0;
var max = left.length > right.length ? left.length : right.length;
for ( i = 0; i < max; i++ ) {
var buf = '';
if ( typeof(left[i]) != 'undefined' ) {
buf += (left[i].length < lMax) ? '<td colspan="' + (lMax - left[i].length) + '">&nbsp;</td>' : '';
buf += '<td>' + left[i].join('</td><td>') + '</td>';
}
if ( typeof(left[i]) != 'undefined' || typeof(right[i]) != 'undefined' ) {
buf += '<td class="units">' + i + '</td>';
}
if ( typeof(right[i]) != 'undefined' ) {
buf += '<td>' + right[i].join('</td><td>') + '</td>';
buf += (right[i].length < rMax) ? '<td colspan="' + (rMax - right[i].length) + '">&nbsp;</td>' : '';
}
if ( buf != '' ) {
strBuf.push('<tr>' + buf + '</tr>');
}
} // i
var table = '<table><tr><th colspan="' + lMax + '">left</th>'
+ '<td class="units">&nbsp;</td>'
+ '<th colspan="' + rMax + '">right</th></tr>'
+ strBuf.join('') + '</table>';
document.getElementById('test').innerHTML = table;
}
}