DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

JavaScript - Simple Example Istogramma

05.08.2006
| 4297 views |
  • submit to reddit
        // Semplice esempio di istogramma fatto in javascript

// File istogramma.js
function istogramma()
{
	/*
	 *
	 * Prende in input una serie di numeri, sia positivi che negativi
	 * e crea un istogramma. 
	 */
	 	
	var n = window.prompt('Numero di valori da inserire:', '');
	
	n = parseInt(n); // rende il valore se valido Int altrimenti NaN
	
	if(isNaN(n) == true)
	{
		document.write('<p align=\"center\"><b>Non hai selezionato nessun valore...</b></p>');
		document.write('<br>');
	}
	else
	{
		var num = new Array();
		var max = 0;
		
		for(var i=0; i<n; i++)
		{
			var tmp = window.prompt('Inserire Valore [' + (i+1) + '/' + n + ']', '');
			tmp = parseFloat(tmp);
			
			if(isNaN(tmp) == true)
			{
				n = i;
				break;
			}
			
			num[i] = tmp;
			
			if(max < Math.abs(num[i])) max = Math.abs(num[i]);
		}
		
		for(var i=0; i<n; i++) num[i] *= 100/max;
		
		document.write('<p align=\"center\"><b>Istogramma for JavaScript</b></p>');
		document.write('<br>');
		document.write('<table align=\"center\" border=\"0\" bgcolor=\"red\">');
		document.write('<tr><td>');
		document.write('<table align=\"center\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"200\" bgcolor=\"black\">');

		for(var j=0; j<n; j++)
		{
			document.write('<tr>');
			
			for(var i=0; i<200; i++)
			{
				var aux = num[j];
				
				if(num[j] == 0) document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
				
				if(num[j] > 0 && i < 100) document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
				else if(num[j] > 0 && i >= 100)
				{
					if((i-100) <= aux)
						document.write('<td width=\"1\" bgcolor=\"green\"> </td>');
					else
						document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
				}
				
				if(num[j] < 0 && i < (100+aux)) document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
				else if(num[j] < 0 && (i >= (100+aux) && i < 100)) document.write('<td width=\"1\" bgcolor=\"yellow\"> </td>');
				else if(num[j] < 0 && i >= 100) document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
			}
			
			document.write('</tr>');
		}

		document.write('</table>');
		document.write('</td></tr>');
		document.write('</table>');
	}
}

// File istogramma.html
<html>
	<head>
		<title>Disegnare un Istogramma...</title>
		<script src='istogramma.js' type='text/javascript'></script>
	</head>
	
	<body OnLoad="istogramma();">
	</body>
</html>