Created
October 7, 2010 15:36
-
-
Save lfborjas/615295 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package ejercicios; | |
| import java.util.Random; | |
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.Collections; | |
| import java.util.HashMap; | |
| import java.util.Map.Entry; | |
| public class RandWords{ | |
| private static String genPalabra(){ | |
| Random gen = new Random(); | |
| //la palabra más larga en español [dicen en internerd] tiene 27 letras | |
| byte[] bytes = new byte[gen.nextInt(27)]; | |
| //llenar el arreglo con bytes aleatorios | |
| //gen.nextBytes(bytes); | |
| for(int i = 0; i< bytes.length; i++){ | |
| //el byte tiene que estar en el rango [97,122] (letras minúsculas) | |
| //para generar aleatorios en un rango: (fin - inicio +1) * gen.nextDouble() + inicio; | |
| bytes[i] = (byte) (26 * gen.nextDouble() + 97); | |
| } | |
| return new String(bytes); | |
| } | |
| public static void main(String [] args){ | |
| //instanciar el generador de aleatorios | |
| Random gen = new Random(); | |
| //obtener el número de palabras de la línea de comandos: | |
| int numPalabras = args.length == 1 ? Integer.parseInt(args[0]) : gen.nextInt(20); | |
| //guardar las palabras en un ArrayList: | |
| ArrayList<String> palabras = new ArrayList<String>(); | |
| //llenar el arrayList con n palabras al azar: | |
| for(int i=0; i<numPalabras; i++){ | |
| palabras.add(genPalabra()); | |
| } | |
| HashMap<Integer, ArrayList<String>> diccionario = new HashMap<Integer, ArrayList<String>>(); | |
| for(String palabra : palabras){ | |
| if(!diccionario.containsKey(palabra.length())){ | |
| String[] placeholder = {palabra}; | |
| diccionario.put(palabra.length(), new ArrayList<String>(Arrays.asList(placeholder))); | |
| }else{ | |
| diccionario.get(palabra.length()).add(palabra); | |
| } | |
| } | |
| //ordenarlas | |
| for(ArrayList<String> valor : diccionario.values()){ | |
| Collections.sort(valor); | |
| } | |
| //imprimirlas | |
| for(Entry entrada: diccionario.entrySet()){ | |
| System.out.printf("Las palabras con longitud %d: %s \n", entrada.getKey(), entrada.getValue().toString()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment