1

eu preciso de uma pequena ajuda. Pra ir direto ao assunto, eu estava a tentar criar um pequeno sistema de equações que me permitissem obter um conjunto de números com umas pequenas particularidades. Basicamente o que eu pretendia, depois de pressionar um botão, era criar quatro números aleatórios (de 1 a 9) que, juntos e submetidos a certas equações matemáticas, o resultado final fosse por exemplo 22. Imaginem: 8, 2, 5, 1, são quatro números aleatórios que permitem esta equação "(8*2)+5+1=22".

Sei como criar os quatros números aleatórios e passa-los para TextView's:

Random a = new Random();
int i1 = a.nextInt(10 - 1) + 1;
TextView tv = (TextView) findViewById(R.id.textView1);
Random b = new Random();
int i2 = b.nextInt(10 - 1)+1;
TextView tv2 = (TextView) findViewById(R.id.textView2);
Random c = new Random();
int i3 = c.nextInt(10 - 1)+1;
TextView tv3 = (TextView) findViewById(R.id.textView3);
Random d = new Random();
int i4 = d.nextInt(10 - 1)+1;
TextView tv4 = (TextView) findViewById(R.id.textView4);

Aqui estão as várias equações:

    int soma = i1 + i2 + i3 + i4;
    int mult0 = i1 * i2 * i3 * i4;
    int mult1 = (i1*i2*i3)+i4;
    int mult2 = (i1*i2)+i3+i4;
    int mult3 = i1 * (i2 + i3 + i4);
    int mult4 = i2 * (i1+i3+i4);
    int mult5 = i3 * (i1+i2+i4);
    int mult6 = i4 * (i1+i2+i3);
    int mult7 = (i1*i3)+i2+i4;
    int mult8 = (i1*i4)+i2+i3;
    int mult9 = (i2*i3)+i1+i4;
    int mult10 = (i2*i4)+i1+i3;
    int mult11 = (i4*i3)+i1+i2;
    int mult12 = (i1*i3*i4)+i2;
    int mult13 = (i1*i2*i4)+i3;
    int mult14 = (i4*i2*i3)+i1;

Mas o próximo passo que é escolher aleatoriamente uma das equações e conseguir que o conjunto de números aleatórios i1, i2, i3, i4, nessa equação seja igual a 22, isso eu não consigo descobrir como fazer. Eu tenho ainda este código mas não está a fazer o que eu pretendo,(PS: TF = 22):

    if (soma == TF || mult0 == TF || mult1 == TF || 
mult2 == TF || mult3 == TF || mult4 == TF || mult5 == TF || 
mult6 == TF || mult7 == TF || mult8 == TF || mult9 == TF || 
mult10 == TF || mult11 == TF || mult12 == TF || mult13 == TF || mult14 == TF){
        tv.setText(String.valueOf(i1));
        tv2.setText(String.valueOf(i2));
        tv3.setText(String.valueOf(i3));
        tv4.setText(String.valueOf(i4));}

Este código basicamente mostra os quatro números aleatórios que obedecem a uma dessas equações, mas não é de forma automática, é por tentativas(é preciso carregar no botão várias vezes até aparecerem novos números). Eu pretendia mesmo que sempre que carregasse no botão, os números certos aparecessem automaticamente, logo à primeira tentativa.

Obrigado se me puderem ajudar :)

2 Respostas 2

2

Pode fazer uma função que calcule os valores todos e ir chamando até acertar num resultado valido.

Primeiro pode isolar a verificação de quatro números num método à parte:

public boolean verificarNumeros(int i1, int i2, int i3, int i4){

    //construir as equações 
    int[] mults = new int[]{ //agora em array para facilitar
    i1 + i2 + i3 + i4,
    i1 * i2 * i3 * i4,
    (i1*i2*i3)+i4,
    (i1*i2)+i3+i4,
    i1 * (i2 + i3 + i4),
    i2 * (i1+i3+i4),
    i3 * (i1+i2+i4),
    i4 * (i1+i2+i3),
    (i1*i3)+i2+i4,
    (i1*i4)+i2+i3,
    (i2*i3)+i1+i4,
    (i2*i4)+i1+i3,
    (i4*i3)+i1+i2,
    (i1*i3*i4)+i2,
    (i1*i2*i4)+i3,
    (i4*i2*i3)+i1
    };

    //e indicar se alguma se verificou
    for (int i=0; i < mults.length; ++i){
         if(mults[i] == TF){
              return true;
         }
    }

    return false;
}

Agora no método principal pode ir chamando este método de verificação até achar uma combinação que funciona:

public void gerarNumeros(){
    boolean combinacaoEncontrada = false;
    Random a = new Random(); //apenas uma instancia de Random
    int i1,i2,i3,i4;

    while (!combinacaoEncontrada){
       i1 = a.nextInt(10 - 1) + 1;
       i2 = a.nextInt(10 - 1) + 1;
       i3 = a.nextInt(10 - 1) + 1;
       i4 = a.nextInt(10 - 1) + 1;
       combinacaoEncontrada = verificarNumeros(i1,i2,i3,i4);
    }

    //mostrar a combinação encontrada
    TextView tv = (TextView) findViewById(R.id.textView1);
    TextView tv2 = (TextView) findViewById(R.id.textView2);
    TextView tv3 = (TextView) findViewById(R.id.textView3);
    TextView tv4 = (TextView) findViewById(R.id.textView4);

    tv.setText(String.valueOf(i1));
    tv2.setText(String.valueOf(i2));
    tv3.setText(String.valueOf(i3));
    tv4.setText(String.valueOf(i4));
}

Recomendações:

  • Para gerar 4 números de 0 a 8 seria melhor fazer uma permutação entre os números todos possíveis a custa de fors ou recursão pois aleatoriamente podemos processar muitos mais números e potencialmente não chegar a uma solução!

  • Em android e todas as outras linguagens que tenham interface gráfica, todo o processamento pesado não deve ser feito na thread principal, senão o sistema irá ficar como se não estivesse respondendo e bloqueado até chegar ao resultado. Para contornar este efeito pode usar Thread ou AsyncTask

1
  • Obrigado Isac!! Eu mudei umas coisinhas e consegui chegar ao que queria, tá agr nos comentários 12/07/2017 às 20:08
0

Muito obrigado Isac!! Mas tive que mudar umas pequenas coisas no teu código.. Dá uma olhada a ver :

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }

int TF = 24;
Random b = new Random(); //apenas uma instancia de Random
int i1 = b.nextInt(10 - 1) + 1;
int i2 = b.nextInt(10 - 1) + 1;
int i3 = b.nextInt(10 - 1) + 1;
int i4 = b.nextInt(10 - 1) + 1;


public boolean verificarNumeros(){

    //construir as equações
    int[] mults = new int[]{ //agora em array para facilitar
            i1 + i2 + i3 + i4,
            i1 * i2 * i3 * i4,
            (i1*i2*i3)+i4,
            (i1*i2)+i3+i4,
            i1 * (i2 + i3 + i4),
            i2 * (i1+i3+i4),
            i3 * (i1+i2+i4),
            i4 * (i1+i2+i3),
            (i1*i3)+i2+i4,
            (i1*i4)+i2+i3,
            (i2*i3)+i1+i4,
            (i2*i4)+i1+i3,
            (i4*i3)+i1+i2,
            (i1*i3*i4)+i2,
            (i1*i2*i4)+i3,
            (i4*i2*i3)+i1
    };

    //e indicar se alguma se verificou
    for (int i=0; i < mults.length; ++i){
        if(mults[i] == TF){
            return true;
        }


        }

    return false;
    }



public void perform_action(View v){

    boolean combinacaoEncontrada = false;
    Random a = new Random(); //apenas uma instancia de Random



    while (!combinacaoEncontrada){
        i1 = a.nextInt(10 - 1) + 1;
        i2 = a.nextInt(10 - 1) + 1;
        i3 = a.nextInt(10 - 1) + 1;
        i4 = a.nextInt(10 - 1) + 1;
        combinacaoEncontrada = verificarNumeros();
    }

    //mostrar a combinação encontrada
    TextView tv = (TextView) findViewById(R.id.textView1);
    TextView tv2 = (TextView) findViewById(R.id.textView2);
    TextView tv3 = (TextView) findViewById(R.id.textView3);
    TextView tv4 = (TextView) findViewById(R.id.textView4);

    tv.setText(String.valueOf(i1));
    tv2.setText(String.valueOf(i2));
    tv3.setText(String.valueOf(i3));
    tv4.setText(String.valueOf(i4));
}

}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .