Assign Value to a Non-method Array

Asked

Viewed 257 times

0

I need to assign a value to an Array and throw it out of a method, but for this I need to take the values that are obtained through this method, to later use this Array obtained in other methods or classes. The print inside the method appears correctly. Now when I step into the Array it does not correctly assign the values. I don’t know if the way the code was made is right for this?

Follow code done so far...

import java.util.Arrays;

public class CombBusca {

    private int numeros[] = {1,2,3,4,5};
    private int quantidade = 3;
    private int resultado[] = new int[3];
    private int count = 0;
    public String[] novosresultados;

    private void busca(int inicio,int fim, int profundidade){

        String todosresultados = "";

        if ( (profundidade + 1) >= quantidade)
        for(int x = inicio; x <= fim; x++){
            resultado[profundidade] = numeros[x];
            // faz alguma coisa com um dos resultados possiveis
            count++;
            //Criei aqui a String para posteriormente passar para o Array 
            todosresultados = resultado[0] + ", " + resultado[1] + ", " + resultado[2];
            System.out.println(resultado[0] + ", " + resultado[1] + ", " + resultado[2]);
        } else
            for(int x = inicio; x <= fim; x++){
                resultado[profundidade] = numeros[x];
                busca(x + 1,fim + 1,profundidade + 1);
        }
        // Novo Array para jogar fora do método "busca" e usar em outros metodos ou classes
        novosresultados = todosresultados.split(", ");
        // Aqui quando mando o print é que acontece o erro
        System.out.println(Arrays.asList(novosresultados));

    }

    public static void main(String args[]){

        CombBusca comb = new CombBusca();
        comb.busca(0, (5-3), 0);

        System.out.println("Total de combinacoes: " + comb.count);

       }
   }

Exit:

[1, 2, 5]
[1, 3, 5]
[1, 4, 5]
[]
[2, 3, 5]
[2, 4, 5]
[]
[3, 4, 5]
[]
[]
Total of combinations: 10

Expected mode:

1, 2, 3
1, 2, 4
1, 2, 5
1, 3, 4
1, 3, 5
1, 4, 5
2, 3, 4
2, 3, 5
2, 4, 5
3, 4, 5
Total of combinations: 10

  • I tried gives suggested form, but not all combinations are generated. Always at the end of each line displays the number 5:

  • 1, 2, 5 1, 3, 5 1, 4, 5 1, 4, 5 2, 3, 5 2, 4, 5 2, 4, 5 3, 4, 5 3, 4, 5&Xa;3, 4, 5 Total of combinations: 10

2 answers

0


There is nothing wrong with your code. The output is also correct.

What happens is that the variable todosresultados is local and when exiting the last recursion it is empty, making the program print '[]' on the console.

To avoid this inconvenience, make a content test before printing it:

if (todosresultados.length() > 0)
            // Novo Array para jogar fora do método "busca" e usar em outros metodos ou classes
            novosresultados = todosresultados.split(", ");

Or choose to sumprimir this impression of the code, since it does not make sense because its result is always the same as the previous line.

Remove the code below:

if (todosresultados.length() > 0) {
        // Novo Array para jogar fora do método "busca" e usar em outros metodos ou classes
        novosresultados = todosresultados.split(", ");
        // Aqui quando mando o print é que acontece o erro
        System.out.println(Arrays.asList(novosresultados));
        }

UPDATE

After your comment I could really understand what you want.

The main issue is that you are not adding the variable novosresultados, but overwriting your data by the last execution of the method busca().

For solution, first replace variable declaration novosresultados for:

private static List<String> novosresultados = new ArrayList<String>();

The guy List is better for those who are starting, and makes it easier to implement this case compared to a vector.

Then replace the line:

System.out.println(resultado[0] + ", " + resultado[1] + ", " + resultado[2]);

for

novosresultados.add(todosresultados);

The method add of the object List does not overwrite the previous data, but adds more data to the list.

Finally remove from the code my previous suggestion as it will no longer be necessary:

if (todosresultados.length() > 0) {
    // Novo Array para jogar fora do método "busca" e usar em outros metodos ou classes
    novosresultados = todosresultados.split(", ");
    // Aqui quando mando o print é que acontece o erro
    System.out.println(Arrays.asList(novosresultados));
}

Your code will stay that way:

public class ComBusca {

    private int numeros[] = {1,2,3,4,5};
    private int quantidade = 3;
    private int resultado[] = new int[3];
    private int count = 0;
    private static List<String> novosresultados = new ArrayList<String>();

    private void busca(int inicio,int fim, int profundidade){

        String todosresultados = "";

        if ( (profundidade + 1) >= quantidade)
            for(int x = inicio; x <= fim; x++){
                resultado[profundidade] = numeros[x];

            // faz alguma coisa com um dos resultados possiveis
            count++;
            //Criei aqui a String para posteriormente passar para o Array 
            todosresultados = resultado[0] + ", " + resultado[1] + ", " + resultado[2];
            novosresultados.add(todosresultados);
        } else
            for(int x = inicio; x <= fim; x++){
                resultado[profundidade] = numeros[x];
                busca(x + 1,fim + 1,profundidade + 1);
            }
    }

    public static void main(String args[]){

        ComBusca comb = new ComBusca();
        comb.busca(0, (5-3), 0);

        //Aqui imprimo o resultado da lista, fora do método busca
        for (String r : novosresultados)
            System.out.println(r);

        System.out.println("Total de combinacoes: " + comb.count);

   }
}
  • I tried it gives suggested form, but not all combinations are generated. Always at the end of each row displays the number 5. See: 1, 2, 5 1, 3, 5 1, 4, 5 2, 3, 5....

  • As I suggested, remove that part of the print from the code, as the value of the last recursion will always be printed. I edited the answer.

  • You see, the doubt is how to work with the "all results" string result outside of the "search" method. Even removing this part of the code I will still not be able to make this String publish. That is, I need that every time I call the "search" method I store the result in an Array, with all combinations, to later work with this Array in another method or by another class. This way I will take this Array where the result of the "search" was inserted to make new combinations, through other methods or other classes. I don’t know if I’ve been able to clarify the idea any further is this.

  • To complete the whole... The code I put in the post is just one example of the numerous attempts I made to store the search result in an Array and to be able to work with this result later by another method or even another class, to make other combinations. In other attempts, the Array only stored the last combination of the 10 possible ones. So what I need is not just to print the result, but to store this result in an Array and make this Array public, to use in other methods or classes.

  • Now I understand what you want. I edited the answer with the solution.

  • That’s exactly what it was!!! Much simpler than I thought it was, I passed by a few times, but I always understood that I had to throw the result out of the method and not assign the results within the method itself. Now I understand..... Thanks!!!!

Show 1 more comment

0

From what I understand you are trying to print all permutations of an array.

If so, has the Heap’s Algorithms that does this.

Has a material from Robert Sandwick very cool talking about the algorithm (in English).

http://homepage.math.uiowa.edu/~Goodman/22m150.dir/2007/Permutation%20Generation%20Methods.pdf

Some examples of implementation:

http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html http://introcs.cs.princeton.edu/java/23recursion/PermutationsLex.java.html

Code in Java

public class HeapsAlgorithms {  
    public void generate( int n, int[] a ){
        if( n ==  1 )
            System.out.println( Arrays.toString(a));
        else{
            for( int i = 0; i < n - 1; i ++ ){
                generate( n - 1, a );
                if( n % 2 == 0 ){
                    swap( a, i, n-1 );
                }else {
                    swap( a, 0, n-1 );
                }
            }
            generate( n - 1, a );
        }
    }

    private void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static void main(String[] args) {
        HeapsAlgorithms hp = new HeapsAlgorithms();

        hp.generate( 4 , new int[]{1,2,3,4} );
    }
}

source: https://en.wikipedia.org/wiki/Heap's_algorithm

  • I can say that this method is already a little advanced, I’m still starting to learn java. Yes, it would be a permutation, but without repetitions. In this example the results are repeated, although not in the same order.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.