Fazendo palavras

1 resposta
H

Pessoal,

Estou querendo fazer uma entrada formada por palavras aleatorias,tipo:
{ agagaha,hdjhasfh,utiweutirut,jsafjdhfjdhf,uuuudye,aababba,2yhgg}

Eu estava pensando em fazer uma rotina “no braço” em que gerava randomicamente um valor TAMANHO,depois entrava num laço while(cujo ponto de parada seria um contador incrementado até TAMANHO) e dentro desse While eu iria gerando um numero aleatoriamente ,covertia pra char e adicionava na palavra.

Mas será que existe um metodo mais “elegante” pra gerar palavras aleatoriamente?

1 Resposta

H

Desenvolvi a classe abaixo para uma suíte de testes. Talvez lhe seja útil.

package hipersoft.estado.teste;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * Usado para gerar padrões estocásticos de teste.
 *
 * @author Alexandre Furtado Neto
 */
public class Gerador
{
  static String consoante [] =
  {
    "b",
    "br",
    "bl",
    "c",
    "cr",
    "cl",
    "d",
    "dr",
    "f",
    "fr",
    "fl",
    "g",
    "gr",
    "gl",
    "h",
    "j",
    "l",
    "m",
    "n",
    "p",
    "pr",
    "pl",
    "qu",
    "r",
    "s",
    "t",
    "tr",
    "v",
    "x",
    "z",
  };

  static String vogal [] =
  {
    "a",
    "e",
    "i",
    "o",
    "u",
    "ao",
    "au",
    "eu",
    "oi",
  };


  static Random rnd = new Random();

  /**
   * Gera um arquivo com dados falsos.
   *
   * @param nome o nome do arquivo
   * @param caminho o diretório onde será armazenado
   */
  public static void geraArquivo(String nome, String caminho) throws IOException
  {
    boolean html = nome.endsWith(".html");
    FileOutputStream fos =
	  new FileOutputStream(caminho + File.separator + nome);
    PrintWriter out = new PrintWriter(fos);
    if(html)
      out.println("<HTML>\r\n<H2 ALIGN=center>");
    out.println("Arquivo " + nome + "\r\n");
    if(html)
      out.println("</H2><PRE>\r\n");
    out.println("(contém padrões aleatórios de texto)\r\n\r\n");
    out.println(centraliza(geraTitulo()) + "\r\n");
    geraTexto(out);
    out.println("\r\n-- Produzido pelo Gerador de Padrões da HiperSoft --");
    if(html)
      out.println("</PRE><HTML>\r\n");
    out.close();
  }

  /**
   * Gera uma String para simular um título de documento/mensagem.
   */
  public static String geraTitulo()
  {
    return Gramatica.geraNome(false).toUpperCase();
  }

  static void geraTexto(PrintWriter out) throws IOException
  {
    int n = rnd.nextInt(50) + 20;
    for(int i = 0; i < n; i++)
    {
      String paragrafo = Gramatica.geraParagrafo();
      int pos1 = 0;
      int pos2 = 60;
      int q = 1;
      while(pos2 < paragrafo.length())
      {
        out.println(paragrafo.substring(pos1, pos2));
        pos1 += 60;
        pos2 += 60;
        q++;
      }
      out.println(paragrafo.substring(pos1));
      out.println();
    }
  }

  public static String geraTexto() throws IOException
  {
    StringBuffer buf = new StringBuffer(
		  "<FONT COLOR=red>(Texto aleatório em pseudo-francês)</FONT>\r\n\r\n");
    int n = rnd.nextInt(15) + 3;
    for(int i = 0; i < n; i++)
    {
      String paragrafo = Gramatica.geraParagrafo();
      int pos1 = 0;
      int pos2 = 60;
      int q = 1;
      while(pos2 < paragrafo.length())
      {
        buf.append(paragrafo.substring(pos1, pos2) + "\r\n");
        pos1 += 60;
        pos2 += 60;
        q++;
      }
      buf.append(paragrafo.substring(pos1));
    }
    return buf.toString();
  }

  public static String geraDescricao()
  {
    StringBuffer buf = new StringBuffer(Gramatica.geraPeriodo());
    buf.replace(0, 1, buf.substring(0, 1).toUpperCase());
    return buf.toString();
  }

  static String geraPalavra()
  {
    StringBuffer buf = new StringBuffer();
    int n = rnd.nextInt(5) + 1;
    for(int i = 0; i < n; i++)
      buf.append(geraSilaba());
    return buf.toString();
	}

  static String geraSilaba()
  {
    return consoante[rnd.nextInt(consoante.length - 1) + 1] +
           vogal[rnd.nextInt(vogal.length - 1) + 1];
  }

  static String centraliza(String texto)
  {
    StringBuffer buf = new StringBuffer();
    for(int i = 0; i < 30 - (texto.length() / 2); i++)
      buf.append(' ');
    buf.append(texto);
    return buf.toString();
  }

  static String [] centenas =
  {
    "",
    "cento",
    "duzentos",
    "trezentos",
    "quatrocentos",
    "quinhentos",
    "seiscentos",
    "setecentos",
    "oitocentos",
    "novecentos",
  };

  static String [] dezenas =
  {
    "",
    "",
    "vinte",
    "trinta",
    "quarenta",
    "cinquenta",
    "sessenta",
    "setenta",
    "oitenta",
    "noventa",
  };

  static String [] unidades =
  {
    "zero",
    "um",
    "dois",
    "três",
    "quatro",
    "cinco",
    "seis",
    "sete",
    "oito",
    "nove",
  };

  /**
   * Escreve por extenso um número inteiro.
   */
  public static String expandeNumero(int n)
  {
    if(n == 0)
      return "zero";
    //
	StringBuffer buf = new StringBuffer();
    //
    // gera a centena
    //
    int cent = n / 100;
    if(cent > 0)
    {
      if(cent == 1 && n % 100 == 0)
        buf.append("cem");
      else
        buf.append(centenas[cent]);
      if(n % 100 > 0)
        buf.append(" e ");
    }
    //
    // gera a dezena
    //
    n %= 100;
    if(n > 0)
    {
      switch(n)
      {
        case 10:
          buf.append("dez");
          return buf.toString();
        case 11:
          buf.append("onze");
          return buf.toString();
        case 12:
          buf.append("doze");
          return buf.toString();
        case 13:
          buf.append("treze");
          return buf.toString();
        case 14:
          buf.append("catorze");
          return buf.toString();
        case 15:
          buf.append("quinze");
          return buf.toString();
        case 16:
          buf.append("dezesseis");
          return buf.toString();
        case 17:
          buf.append("dezessete");
          return buf.toString();
        case 18:
          buf.append("dezoito");
          return buf.toString();
        case 19:
          buf.append("dezenove");
          return buf.toString();
      }
      int dezena = n / 10;
      if(dezena > 1)
      {
        buf.append(dezenas[dezena]);
        if(n % 10 > 0)
          buf.append(" e ");
      }
    }
    //
    // gera a unidade
    //
    n %= 10;
    if(n > 0)
      buf.append(unidades[n]);
    return buf.toString();
  }
}

Agora, se vc quiser um texto longo que lembre vagamente o francês, rode o código abaixo:

package hipersoft.estado.teste;

import java.util.Random;

/**
 * Gramática do francês usada para gerar pseudo-texto.
 *
 * @author Alexandre Furtado Neto
 */
public class Gramatica
{
  private static Random rnd = new Random();

  public static void main(String args [])
  {
    Gramatica gramatica = new Gramatica();
    for(int i = 0; i < 500; i++)
	  System.out.println(geraParagrafo() + "\r\n");
  }

  /**
   * Gera um parágrafo gramatical.
   */
  public static String geraParagrafo()
  {
    StringBuffer buf = new StringBuffer();
    for(int i = 0; i < 1 + rnd.nextInt(2); i++)
    {
      if(i > 0)
        buf.append(' ');
      String periodo = geraPeriodo().trim();
      buf.append(periodo.substring(0, 1).toUpperCase());
      buf.append(periodo.substring(1));
    }
    return buf.toString();
  }

  public static String geraPeriodo()
  {
    int prob = rnd.nextInt(100);
    if(prob < 5)
      return interrogativo() + " " + oracao(false).trim() + ".";
    if(prob < 10)
      return interrogativo() + " " + oracao(false).trim() + "?";
    if(prob < 20)
      return vocativo() + imperativo() + " " + objeto().trim() + "!";
    if(prob < 30)
      return "si " + geraNome(true) + " " + condicional() + ", " + oracao(true) + ".";
    if(prob < 35)
      return "si " + geraNome(true) + " " + condicional() + ", alors " + oracao(true) + ".";
    else if(prob < 40)
      return sindetico().trim() + ".";
    else if(prob < 98)
      return assindetico().trim() + ".";
    else
      return exclamacao();
  }

  private static String assindetico()
  {
    String s = "";
    for(int i = 0; i < 1 + rnd.nextInt(2); i++)
    {
      if(i > 0)
        s += ", ";
      s += oracao(false).trim();
    }
    return s;
  }

  static String vocativo()
  {
    int prob = rnd.nextInt(100);
    if(prob < 5)
      return "oh " + proprio() + ", ";
    if(prob < 8)
      return "s'ill vous plait, ";
    else
      return "";
  }

  private static String sindetico()
  {
    String s = "";
    for(int i = 0; i < 1 + rnd.nextInt(2); i++)
    {
      if(i > 0)
        s += " " + conectivo() + " ";
      s += oracao(false).trim();
    }
    return s;
  }

  static String [] lista1 =
  {
    " ce est",
    " de une",
    " je avais",
    "..",
    "!.",
  };

  static String [] lista2 =
  {
    " c'est",
    " d'une",
    " j'avais",
    ".",
    "!",
  };

  public static String oracao(boolean definido)
  {
    int prob = rnd.nextInt(100);
    if(prob < 2)
      return "il pleut " + objeto();
    if(prob < 5)
      return geraNome(true) + " " + ligacao(0) + " " + geraNome(true);
    if(prob < 10)
      return geraNome(true) + " " + ligacao(3) + " " + adjetivo();
    StringBuffer buf = new StringBuffer(sujeito(definido).trim() + " " + predicado());
    //
    // filtra alguns padrões
    //
    for(int i = 0; i < lista1.length; i++)
    {
      int pos = buf.toString().indexOf(lista1[i] + " ");
      if(pos >= 0)
        buf.replace(pos, pos + lista1[i].length() + 1, lista2[i] + " ");
      pos = buf.toString().indexOf(lista1[i] + ".");
      if(pos >= 0)
        buf.replace(pos, pos + lista1[i].length() + 1, lista2[i] + ".");
      pos = buf.toString().indexOf(lista1[i] + "!");
      if(pos >= 0)
        buf.replace(pos, pos + lista1[i].length() + 1, lista2[i] + "!");
      pos = buf.toString().indexOf(lista1[i] + "?");
      if(pos >= 0)
        buf.replace(pos, pos + lista1[i].length() + 1, lista2[i] + "?");
    }
    return buf.toString();
  }

  private static String sujeito(boolean definido)
  {
    if(definido)
      return geraNome(definido);
    else
    {
      int prob = rnd.nextInt(100);
      if(prob < 70)
        return geraNome(false);
      else
        return "";
    }
  }

  static String ligacao(int pessoa)
  {
    return ligacoes[pessoa];
  }

  private static String predicado()
  {
    return nucleo().trim() + " " + objeto();
  }

  static String nucleo()
  {
    String aux = auxiliar().trim();
    if(aux.length() > 0)
      aux = " " + aux + " ";
    else
      aux = " ";
    return (adverbio_verbo() + aux + verbo(aux.length() > 0).trim()).trim() + " " + adverbio_adjetivo();
  }

  private static String objeto()
  {
    int prob = rnd.nextInt(100);
    if(prob < 90)
      return preposicao() + " " + geraNome(false);
    else
      return preposicao() + " " + adverbio_substantivo();
  }

  public static String geraNome(boolean definido)
  {
    int prob = rnd.nextInt(100);
    if(definido || prob < 50)
    {
      String pre = precomplemento();
      String s;
			if(pre.length() == 0)
			  s = substantivo() + " " + poscomplemento();
      else
			  s = pre + " " + substantivo();
      prob = rnd.nextInt(100);
      if(prob < 3)
        return s + aposto();
      else if(prob < 6)
        return s + " ou " + geraNome(false);
      else if(prob < 9)
        return s + " et " + geraNome(false);
      else
        return s;
    }
		else if(prob < 75)
      return pronome_substantivo();
    else
			return pronome();
  }

  static String pronome_substantivo()
  {
    return pronomes_substantivos[rnd.nextInt(pronomes_substantivos.length)];
  }

  static String pronome()
  {
    return pronomes[rnd.nextInt(pronomes.length)];
  }

  static String precomplemento()
  {
    int prob = rnd.nextInt(100);
    if(prob < 50)
    {
      String determinante = "";
      if(prob < 20)
        determinante = artigo() + " ";
      else if(prob < 28)
        determinante = demonstrativo() + " ";
      prob = rnd.nextInt(100);
      if(prob < 35)
        return determinante + possessivo().trim() + " " + adjetivo();
      else if(prob < 40)
        return determinante + adjetivo();
      else if(prob < 45)
        return determinante + numeral();
      else if(prob < 50)
        return "si " + adjetivo();
      else
        return determinante + possessivo();
		}
		else
      return "";
  }

  static String numeral()
  {
    return numerais[rnd.nextInt(numerais.length)];
  }

  static String demonstrativo()
  {
    return demonstrativos[rnd.nextInt(demonstrativos.length)];
  }

  static String possessivo()
  {
    return possessivos[rnd.nextInt(possessivos.length)];
  }

  static String adverbio_substantivo()
  {
    return adverbios_substantivos[rnd.nextInt(adverbios_substantivos.length)];
  }

  static String poscomplemento()
  {
    int prob = rnd.nextInt(100);
    if(prob < 15)
      return adverbio_adjetivo();
    else if(prob < 30)
			return adverbio_adjetivo() + " " + adjetivo();
    else if(prob < 40)
			return "dont " + oracao(true);
    else if(prob < 60)
			return "de " + substantivo();
    else
      return "";
  }

  static String substantivo()
  {
    int prob = rnd.nextInt(100);
    if(prob < 50)
      return proprio();
    else
			return comum();
  }

  static String proprio()
  {
    return proprios[rnd.nextInt(proprios.length)];
  }

  /*
   * Gera substantivo comum com ou sem plural.
   */
  static String comum()
  {
    String s = comuns[rnd.nextInt(comuns.length)];
    if(s.charAt(0) == '@')
      return s.substring(1);
    boolean plural = rnd.nextBoolean();
    if(s.endsWith("$"))
    {
      s = s.substring(0, s.length() - 1);
      return plural ? s : s + "es";
    }
    return s;
	}

  static String adverbio_verbo()
  {
    int prob = rnd.nextInt(100);
    if(prob < 30)
      return adverbios_verbos[rnd.nextInt(adverbios_verbos.length)];
    else
      return "";
  }

  static String adverbio_adjetivo()
  {
    int prob = rnd.nextInt(100);
    if(prob < 30)
      return adverbios_adjetivos[rnd.nextInt(adverbios_adjetivos.length)];
    else
      return "";
  }

  static String adjetivo()
  {
    return adjetivos[rnd.nextInt(adjetivos.length)];
  }

  static String auxiliar()
  {
    int prob = rnd.nextInt(100);
    if(prob < 30)
      return "est";
    else if(prob < 50)
      return "avais";
    else
      return "";
  }

  static String verbo(boolean aux)
  {
    if(aux)
      return verbos[rnd.nextInt(verbos.length)] + sufixo1();
    else
    {
      int prob = rnd.nextInt(100);
      if(prob < 30)
        return irregular();
      else
			  return verbos[rnd.nextInt(verbos.length)] + sufixo2();
    }
  }

  static String irregular()
  {
    return irregulares[rnd.nextInt(irregulares.length)];
  }

  static String imperativo()
  {
    return verbos[rnd.nextInt(verbos.length)] + "é";
  }

  static String condicional()
  {
    return verbos[rnd.nextInt(verbos.length)] + "ais";
  }

  static String sufixo1()
  {
    return rnd.nextBoolean() ? "ais" : "ent";
  }

  static String sufixo2()
  {
    return sufixos[rnd.nextInt(sufixos.length)];
  }

  /*
   * Gera a preposição para a formação do objeto indireto
   */
  static String preposicao()
  {
    int prob = rnd.nextInt(100);
    if(prob < 50)
      return preposicoes[rnd.nextInt(preposicoes.length)];
    else
      return "";
  }

  static String aposto()
  {
    return rnd.nextInt(100) < 2 ? ", le meilleur," : "";
  }

  static String artigo()
  {
    return artigos[rnd.nextInt(artigos.length)];
  }

  static String exclamacao()
  {
    int prob = rnd.nextInt(100);
    if(prob < 30)
      return exclamacoes[rnd.nextInt(exclamacoes.length)];
    else if(prob < 60)
      return "oh, " + oracao(false) + "!";
    else
      return "oh, " + substantivo() + "!";
  }

  static String conectivo()
  {
    return conectivos[rnd.nextInt(conectivos.length)];
  }

  static String interrogativo()
  {
    return interrogativos[rnd.nextInt(interrogativos.length)];
  }

  static String interrogativos [] =
  {
    "quand", "oú", "pour quoi", "qui", "comme",
  };

	static String artigos [] =
  {
    "le", "la", "les", "las", "un", "une", "uns", "unes", "des",
  };

	static String preposicoes [] =
  {
    "de", "pour", "a", "avec", "sens", "in",
  };

	static String adjetivos [] =
  {
    "bon", "mauvais", "grand", "petit", "beau", "laid", "fort", "faible", "riche", "pauvre",
    "vert", "bleu", "blanc", "noir", "foncé", "clair", "fragile", "intelligent",
    "stupide", "facile", "dificile", "nouvelle", "jeune",
  };

	static String verbos [] =
  {
    "chant", "achet", "us", "namor", "prêt", "aim", "arret", "augment", "escap", "transport",
		"port", "oubli", "pass", "desin",
  };

	static String proprios [] =
  {
    "Marie", "Jean Luc", "Anna", "France", "Brésil", "Rio", "Lucie", "Pimpon", "Aline", "Pixeré",
    "Vanda", "Vera", "Resende", "Parahiba", "Nort", "Ray", "Paris", Jeveaux,
  };

	static String exclamacoes [] =
  {
    "uh lá lá!", "oh mon Dieu!",
  };

	static String adverbios_verbos [] =
  {
    "non", "toujour", "jamais", "bien trop suivante", "rarement", "presque", "in janvier",
		"en été", "mise en",
  };

	static String adverbios_substantivos [] =
  {
    "maintenant", "aujord'hui", "hier", "là-bas",
  };

	static String adverbios_adjetivos [] =
  {
    "trés", "peu", "aujordhui", "tot", "demain", "maintenant", "hier", "la semaine dernière",
		"ainsi", "mais", "moins", "ici", "lá", "plus", "trop",
  };

	static String pronomes [] =
  {
    "je", "tu", "il", "elle", "nous", "celui ci", "celui lá", "on", "ce",
  };

	static String pronomes_substantivos [] =
  {
    "ceci", "cela", "quelque chose", "quelq'un",
  };

	static String comuns [] =
  {
    "plage", "sable", "chez", "auto", "visage", "silence", "mensonge", "monde", "peuple",
		"mer", "corp", "ordinateur", "haine", "amour", "froid", "chaleur", "ciel",
		"terre", "champagne", "cité", "sale", "magasin", "arbre", "lampe", "lumière", "rive",
		"temp", "heure", "jour", "nuit", "homme", "femme", "garçon", "fille", "soleil", "lune",
		"poste", "table", "plain", "lait", "porte", "fenetre", "avril",
		"seigneur", "dame", "numero", "quantité", "qualité", "libre", "telefone", "pluis", "vague",
    "vache", "musique", "chanson", "chanteur", "voix", "radio", "famille", "ami", "vie",
		"maladie", "rendez-vous", "matin", "fleur", "année", "diminuition", "difference",
  };

	static String conectivos [] =
  {
    "et", "mais", "parce que", "ou", "que", "donc",
  };

	static String sufixos [] =
  {
    "e", "es", "e", "mons", "aint", "é", "es", "er", "é", "ent", "arais", "ais", "erai",
  };

	static String possessivos [] =
  {
    "mon", "ton", "notre", "ma", "ta"
  };

	static String demonstrativos [] =
  {
    "cette", "celui", "tout", "toute", "personne", "aucun", "aucune",
  };

	static String numerais [] =
  {
    "un", "deux", "trois", "premiere", "deuxieme", "dernier",
  };

	static String irregulares [] =
  {
    "fais", "fait", "avais",
  };

	static String [] ligacoes =
  {
    "suis",
    "es",
    "est",
    "somes",
    "etez",
    "sont",
  };
}
Criado 11 de abril de 2005
Ultima resposta 12 de abr. de 2005
Respostas 1
Participantes 2