Skip to content

Instantly share code, notes, and snippets.

@lfborjas
Created November 12, 2011 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lfborjas/1360129 to your computer and use it in GitHub Desktop.
Save lfborjas/1360129 to your computer and use it in GitHub Desktop.
/**Programa que genera un arreglo con tamaño aleatorio de enteros aleatorios
e imprime un histograma de frecuencias
*/
package ejercicios;
//clase de java para generar números aleatorios:
import java.util.Random;
//sirve para representar colecciones tabulares
import java.util.HashMap;
//contiene distintas utilidades para colecciones
import java.util.Collections;
//para poder iterar sobre el mapa
import java.util.Map.Entry;
import java.util.Arrays;
public class Histograma{
private static String repeat(String what, int howMany){
StringBuilder buf = new StringBuilder();
for(int i=0; i<howMany; i++){
buf.append(what);
}
return buf.toString();
}
public static void main (String [] args){
Random generator = new Random();
//genera números aleatorios entre 0 y 20
int[] nums = new int[generator.nextInt(20)];
for(int i=0; i< nums.length; i++){
//números aleatorios entre 0 y 10
nums[i] = generator.nextInt(10);
}
//creamos una tabla que guarde el número y su cantidad de ocurrencias
//no se pueden usar tipos primitivos en este tipo de estructuras
HashMap<Integer, Integer> tabla = new HashMap<Integer, Integer>();
System.out.printf("Números generados: \n %s\n", Arrays.toString(nums));
for(int num: nums){
Integer index = new Integer(num);
if(!tabla.containsKey(index))
tabla.put(index, new Integer(1));
else
tabla.put(index, tabla.get(index)+1);
}
for(Entry<Integer, Integer> fila: tabla.entrySet()){
System.out.printf("%s: %s\n",fila.getKey(), repeat("*", fila.getValue().intValue()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment